-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
Copy pathtransaction.ts
277 lines (224 loc) · 7.69 KB
/
transaction.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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import type { Hub } from '@sentry/core';
import { DEFAULT_ENVIRONMENT, getCurrentHub } from '@sentry/core';
import type {
Context,
Contexts,
DynamicSamplingContext,
Event,
Measurements,
MeasurementUnit,
Transaction as TransactionInterface,
TransactionContext,
TransactionMetadata,
} from '@sentry/types';
import { dropUndefinedKeys, logger } from '@sentry/utils';
import { Span as SpanClass, SpanRecorder } from './span';
/** JSDoc */
export class Transaction extends SpanClass implements TransactionInterface {
public metadata: TransactionMetadata;
/**
* The reference to the current hub.
*/
public readonly _hub: Hub;
private _name: string;
private _measurements: Measurements = {};
private _contexts: Contexts = {};
private _trimEnd?: boolean;
private _frozenDynamicSamplingContext: Readonly<Partial<DynamicSamplingContext>> | undefined = undefined;
/**
* This constructor should never be called manually. Those instrumenting tracing should use
* `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`.
* @internal
* @hideconstructor
* @hidden
*/
public constructor(transactionContext: TransactionContext, hub?: Hub) {
super(transactionContext);
this._hub = hub || getCurrentHub();
this._name = transactionContext.name || '';
this.metadata = {
source: 'custom',
...transactionContext.metadata,
spanMetadata: {},
};
this._trimEnd = transactionContext.trimEnd;
// this is because transactions are also spans, and spans have a transaction pointer
this.transaction = this;
// If Dynamic Sampling Context is provided during the creation of the transaction, we freeze it as it usually means
// there is incoming Dynamic Sampling Context. (Either through an incoming request, a baggage meta-tag, or other means)
const incomingDynamicSamplingContext = this.metadata.dynamicSamplingContext;
if (incomingDynamicSamplingContext) {
// We shallow copy this in case anything writes to the original reference of the passed in `dynamicSamplingContext`
this._frozenDynamicSamplingContext = { ...incomingDynamicSamplingContext };
}
}
/** Getter for `name` property */
public get name(): string {
return this._name;
}
/** Setter for `name` property, which also sets `source` as custom */
public set name(newName: string) {
this.setName(newName);
}
/**
* JSDoc
*/
public setName(name: string, source: TransactionMetadata['source'] = 'custom'): void {
this._name = name;
this.metadata.source = source;
}
/**
* Attaches SpanRecorder to the span itself
* @param maxlen maximum number of spans that can be recorded
*/
public initSpanRecorder(maxlen: number = 1000): void {
if (!this.spanRecorder) {
this.spanRecorder = new SpanRecorder(maxlen);
}
this.spanRecorder.add(this);
}
/**
* @inheritDoc
*/
public setContext(key: string, context: Context | null): void {
if (context === null) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this._contexts[key];
} else {
this._contexts[key] = context;
}
}
/**
* @inheritDoc
*/
public setMeasurement(name: string, value: number, unit: MeasurementUnit = ''): void {
this._measurements[name] = { value, unit };
}
/**
* @inheritDoc
*/
public setMetadata(newMetadata: Partial<TransactionMetadata>): void {
this.metadata = { ...this.metadata, ...newMetadata };
}
/**
* @inheritDoc
*/
public finish(endTimestamp?: number): string | undefined {
// This transaction is already finished, so we should not flush it again.
if (this.endTimestamp !== undefined) {
return undefined;
}
if (!this.name) {
__DEBUG_BUILD__ && logger.warn('Transaction has no name, falling back to `<unlabeled transaction>`.');
this.name = '<unlabeled transaction>';
}
// just sets the end timestamp
super.finish(endTimestamp);
if (this.sampled !== true) {
// At this point if `sampled !== true` we want to discard the transaction.
__DEBUG_BUILD__ && logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.');
const client = this._hub.getClient();
if (client) {
client.recordDroppedEvent('sample_rate', 'transaction');
}
return undefined;
}
const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : [];
if (this._trimEnd && finishedSpans.length > 0) {
this.endTimestamp = finishedSpans.reduce((prev: SpanClass, current: SpanClass) => {
if (prev.endTimestamp && current.endTimestamp) {
return prev.endTimestamp > current.endTimestamp ? prev : current;
}
return prev;
}).endTimestamp;
}
const metadata = this.metadata;
const transaction: Event = {
contexts: {
...this._contexts,
// We don't want to override trace context
trace: this.getTraceContext(),
},
spans: finishedSpans,
start_timestamp: this.startTimestamp,
tags: this.tags,
timestamp: this.endTimestamp,
transaction: this.name,
type: 'transaction',
sdkProcessingMetadata: {
...metadata,
dynamicSamplingContext: this.getDynamicSamplingContext(),
},
...(metadata.source && {
transaction_info: {
source: metadata.source,
},
}),
};
const hasMeasurements = Object.keys(this._measurements).length > 0;
if (hasMeasurements) {
__DEBUG_BUILD__ &&
logger.log(
'[Measurements] Adding measurements to transaction',
JSON.stringify(this._measurements, undefined, 2),
);
transaction.measurements = this._measurements;
}
__DEBUG_BUILD__ && logger.log(`[Tracing] Finishing ${this.op} transaction: ${this.name}.`);
return this._hub.captureEvent(transaction);
}
/**
* @inheritDoc
*/
public toContext(): TransactionContext {
const spanContext = super.toContext();
return dropUndefinedKeys({
...spanContext,
name: this.name,
trimEnd: this._trimEnd,
});
}
/**
* @inheritDoc
*/
public updateWithContext(transactionContext: TransactionContext): this {
super.updateWithContext(transactionContext);
this.name = transactionContext.name || '';
this._trimEnd = transactionContext.trimEnd;
return this;
}
/**
* @inheritdoc
*
* @experimental
*/
public getDynamicSamplingContext(): Readonly<Partial<DynamicSamplingContext>> {
if (this._frozenDynamicSamplingContext) {
return this._frozenDynamicSamplingContext;
}
const hub: Hub = this._hub || getCurrentHub();
const client = hub && hub.getClient();
if (!client) return {};
const { environment, release } = client.getOptions() || {};
const { publicKey: public_key } = client.getDsn() || {};
const maybeSampleRate = this.metadata.sampleRate;
const sample_rate = maybeSampleRate !== undefined ? maybeSampleRate.toString() : undefined;
const scope = hub.getScope();
const { segment: user_segment } = (scope && scope.getUser()) || {};
const source = this.metadata.source;
// We don't want to have a transaction name in the DSC if the source is "url" because URLs might contain PII
const transaction = source && source !== 'url' ? this.name : undefined;
const dsc = dropUndefinedKeys({
environment: environment || DEFAULT_ENVIRONMENT,
release,
transaction,
user_segment,
public_key,
trace_id: this.traceId,
sample_rate,
});
// Uncomment if we want to make DSC immutable
// this._frozenDynamicSamplingContext = dsc;
return dsc;
}
}