-
-
Notifications
You must be signed in to change notification settings - Fork 244
/
Copy pathsentry_tracer.dart
388 lines (320 loc) · 10.3 KB
/
sentry_tracer.dart
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
import 'dart:async';
import 'package:meta/meta.dart';
import '../sentry.dart';
import 'sentry_tracer_finish_status.dart';
import 'utils/sample_rate_format.dart';
@internal
class SentryTracer extends ISentrySpan {
final Hub _hub;
late bool _waitForChildren;
late String name;
late final SentrySpan _rootSpan;
final List<SentrySpan> _children = [];
final Map<String, dynamic> _extra = {};
final Map<String, SentryMeasurement> _measurements = {};
Timer? _autoFinishAfterTimer;
Duration? _autoFinishAfter;
@visibleForTesting
Timer? get autoFinishAfterTimer => _autoFinishAfterTimer;
OnTransactionFinish? _onFinish;
var _finishStatus = SentryTracerFinishStatus.notFinishing();
late final bool _trimEnd;
late SentryTransactionNameSource transactionNameSource;
SentryTraceContextHeader? _sentryTraceContextHeader;
/// If [waitForChildren] is true, this transaction will not finish until all
/// its children are finished.
///
/// When [autoFinishAfter] is provided, started transactions will
/// automatically be finished after this duration.
///
/// If [trimEnd] is true, sets the end timestamp of the transaction to the
/// highest timestamp of child spans, trimming the duration of the
/// transaction. This is useful to discard extra time in the transaction that
/// is not accounted for in child spans, like what happens in the
/// [SentryNavigatorObserver] idle transactions, where we finish the
/// transaction after a given "idle time" and we don't want this "idle time"
/// to be part of the transaction.
SentryTracer(
SentryTransactionContext transactionContext,
this._hub, {
DateTime? startTimestamp,
bool waitForChildren = false,
Duration? autoFinishAfter,
bool trimEnd = false,
OnTransactionFinish? onFinish,
}) {
_rootSpan = SentrySpan(
this,
transactionContext,
_hub,
samplingDecision: transactionContext.samplingDecision,
startTimestamp: startTimestamp,
);
_waitForChildren = waitForChildren;
_autoFinishAfter = autoFinishAfter;
_scheduleTimer();
name = transactionContext.name;
// always default to custom if not provided
transactionNameSource = transactionContext.transactionNameSource ??
SentryTransactionNameSource.custom;
_trimEnd = trimEnd;
_onFinish = onFinish;
}
@override
Future<void> finish({SpanStatus? status, DateTime? endTimestamp}) async {
final commonEndTimestamp = endTimestamp ?? _hub.options.clock();
_autoFinishAfterTimer?.cancel();
_finishStatus = SentryTracerFinishStatus.finishing(status);
if (!_rootSpan.finished &&
(!_waitForChildren || _haveAllChildrenFinished())) {
_rootSpan.status ??= status;
// remove span where its endTimestamp is before startTimestamp
_children.removeWhere(
(span) => !_hasSpanSuitableTimestamps(span, commonEndTimestamp));
// finish unfinished spans otherwise transaction gets dropped
final spansToBeFinished = _children.where((span) => !span.finished);
for (final span in spansToBeFinished) {
await span.finish(
status: SpanStatus.deadlineExceeded(),
endTimestamp: commonEndTimestamp,
);
}
var _rootEndTimestamp = commonEndTimestamp;
if (_trimEnd && children.isNotEmpty) {
final childEndTimestamps = children
.where((child) => child.endTimestamp != null)
.map((child) => child.endTimestamp!);
if (childEndTimestamps.isNotEmpty) {
final oldestChildEndTimestamp =
childEndTimestamps.reduce((a, b) => a.isAfter(b) ? a : b);
if (_rootEndTimestamp.isAfter(oldestChildEndTimestamp)) {
_rootEndTimestamp = oldestChildEndTimestamp;
}
}
}
// the callback should run before because if the span is finished,
// we cannot attach data, its immutable after being finished.
final finish = _onFinish?.call(this);
if (finish is Future) {
await finish;
}
await _rootSpan.finish(endTimestamp: _rootEndTimestamp);
// remove from scope
await _hub.configureScope((scope) {
if (scope.span == this) {
scope.span = null;
}
});
// if it's an idle transaction which has no children, we drop it to save user's quota
if (children.isEmpty && _autoFinishAfter != null) {
return;
}
final transaction = SentryTransaction(this);
transaction.measurements.addAll(_measurements);
await _hub.captureTransaction(
transaction,
traceContext: traceContext(),
);
}
}
@override
void removeData(String key) {
if (finished) {
return;
}
_extra.remove(key);
}
@override
void removeTag(String key) {
if (finished) {
return;
}
_rootSpan.removeTag(key);
}
@override
void setData(String key, dynamic value) {
if (finished) {
return;
}
_extra[key] = value;
}
@override
void setTag(String key, String value) {
if (finished) {
return;
}
_rootSpan.setTag(key, value);
}
@override
ISentrySpan startChild(
String operation, {
String? description,
DateTime? startTimestamp,
}) {
if (finished) {
return NoOpSentrySpan();
}
if (children.length >= _hub.options.maxSpans) {
_hub.options.logger(
SentryLevel.warning,
'Span operation: $operation, description: $description dropped due to limit reached. Returning NoOpSpan.',
);
return NoOpSentrySpan();
}
return _rootSpan.startChild(
operation,
description: description,
startTimestamp: startTimestamp,
);
}
ISentrySpan startChildWithParentSpanId(
SpanId parentSpanId,
String operation, {
String? description,
DateTime? startTimestamp,
}) {
if (finished) {
return NoOpSentrySpan();
}
// reset the timer if a new child is added
_scheduleTimer();
if (children.length >= _hub.options.maxSpans) {
_hub.options.logger(
SentryLevel.warning,
'Span operation: $operation, description: $description dropped due to limit reached. Returning NoOpSpan.',
);
return NoOpSentrySpan();
}
final context = SentrySpanContext(
traceId: _rootSpan.context.traceId,
parentSpanId: parentSpanId,
operation: operation,
description: description);
final child = SentrySpan(
this,
context,
_hub,
samplingDecision: _rootSpan.samplingDecision,
startTimestamp: startTimestamp,
finishedCallback: _finishedCallback,
);
_children.add(child);
return child;
}
Future<void> _finishedCallback({
DateTime? endTimestamp,
}) async {
final finishStatus = _finishStatus;
if (finishStatus.finishing) {
await finish(status: finishStatus.status, endTimestamp: endTimestamp);
}
}
@override
SpanStatus? get status => _rootSpan.status;
@override
SentrySpanContext get context => _rootSpan.context;
@override
String? get origin => _rootSpan.origin;
@override
set origin(String? origin) => _rootSpan.origin = origin;
@override
DateTime get startTimestamp => _rootSpan.startTimestamp;
@override
DateTime? get endTimestamp => _rootSpan.endTimestamp;
Map<String, dynamic> get data => Map.unmodifiable(_extra);
@override
bool get finished => _rootSpan.finished;
List<SentrySpan> get children => _children;
@override
dynamic get throwable => _rootSpan.throwable;
@override
set throwable(throwable) => _rootSpan.throwable = throwable;
@override
set status(SpanStatus? status) => _rootSpan.status = status;
Map<String, String> get tags => _rootSpan.tags;
@override
SentryTraceHeader toSentryTrace() => _rootSpan.toSentryTrace();
@visibleForTesting
Map<String, SentryMeasurement> get measurements =>
Map.unmodifiable(_measurements);
bool _haveAllChildrenFinished() {
for (final child in children) {
if (!child.finished) {
return false;
}
}
return true;
}
bool _hasSpanSuitableTimestamps(
SentrySpan span, DateTime endTimestampCandidate) =>
!span.startTimestamp
.isAfter((span.endTimestamp ?? endTimestampCandidate));
@override
void setMeasurement(String name, num value, {SentryMeasurementUnit? unit}) {
if (finished) {
return;
}
final measurement = SentryMeasurement(name, value, unit: unit);
_measurements[name] = measurement;
}
@override
SentryBaggageHeader? toBaggageHeader() {
final context = traceContext();
if (context != null) {
final baggage = context.toBaggage(logger: _hub.options.logger);
return SentryBaggageHeader.fromBaggage(baggage);
}
return null;
}
@override
SentryTraceContextHeader? traceContext() {
// TODO: freeze context after 1st envelope or outgoing HTTP request
if (_sentryTraceContextHeader != null) {
return _sentryTraceContextHeader;
}
SentryUser? user;
_hub.configureScope((scope) => user = scope.user);
_sentryTraceContextHeader = SentryTraceContextHeader(
_rootSpan.context.traceId,
Dsn.parse(_hub.options.dsn!).publicKey,
release: _hub.options.release,
environment: _hub.options.environment,
userId: null, // because of PII not sending it for now
userSegment: user?.segment,
transaction:
_isHighQualityTransactionName(transactionNameSource) ? name : null,
sampleRate: _sampleRateToString(_rootSpan.samplingDecision?.sampleRate),
);
return _sentryTraceContextHeader;
}
String? _sampleRateToString(double? sampleRate) {
if (!isValidSampleRate(sampleRate)) {
return null;
}
return sampleRate != null ? SampleRateFormat().format(sampleRate) : null;
}
bool _isHighQualityTransactionName(SentryTransactionNameSource source) {
return source != SentryTransactionNameSource.url;
}
@override
SentryTracesSamplingDecision? get samplingDecision =>
_rootSpan.samplingDecision;
@override
void scheduleFinish() {
if (finished) {
return;
}
if (_autoFinishAfterTimer != null) {
_scheduleTimer();
}
}
void _scheduleTimer() {
final autoFinishAfter = _autoFinishAfter;
if (autoFinishAfter != null) {
_autoFinishAfterTimer?.cancel();
_autoFinishAfterTimer = Timer(autoFinishAfter, () async {
await finish(status: status ?? SpanStatus.ok());
});
}
}
}