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
|
import { logger, timestampInSeconds } from '@sentry/utils';
import { SpanRecorder } from './span.js';
import { Transaction } from './transaction.js';
const TRACING_DEFAULTS = {
idleTimeout: 1000,
finalTimeout: 30000,
heartbeatInterval: 5000,
};
const FINISH_REASON_TAG = 'finishReason';
const IDLE_TRANSACTION_FINISH_REASONS = [
'heartbeatFailed',
'idleTimeout',
'documentHidden',
'finalTimeout',
'externalFinish',
'cancelled',
];
/**
* @inheritDoc
*/
class IdleTransactionSpanRecorder extends SpanRecorder {
constructor(
_pushActivity,
_popActivity,
transactionSpanId,
maxlen,
) {
super(maxlen);this._pushActivity = _pushActivity;this._popActivity = _popActivity;this.transactionSpanId = transactionSpanId; }
/**
* @inheritDoc
*/
add(span) {
// We should make sure we do not push and pop activities for
// the transaction that this span recorder belongs to.
if (span.spanId !== this.transactionSpanId) {
// We patch span.finish() to pop an activity after setting an endTimestamp.
span.finish = (endTimestamp) => {
span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampInSeconds();
this._popActivity(span.spanId);
};
// We should only push new activities if the span does not have an end timestamp.
if (span.endTimestamp === undefined) {
this._pushActivity(span.spanId);
}
}
super.add(span);
}
}
/**
* An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.
* You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will
* put itself on the scope on creation.
*/
class IdleTransaction extends Transaction {
// Activities store a list of active spans
__init() {this.activities = {};}
// Track state of activities in previous heartbeat
// Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.
__init2() {this._heartbeatCounter = 0;}
// We should not use heartbeat if we finished a transaction
__init3() {this._finished = false;}
// Idle timeout was canceled and we should finish the transaction with the last span end.
__init4() {this._idleTimeoutCanceledPermanently = false;}
__init5() {this._beforeFinishCallbacks = [];}
/**
* Timer that tracks Transaction idleTimeout
*/
__init6() {this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];}
constructor(
transactionContext,
_idleHub,
/**
* The time to wait in ms until the idle transaction will be finished. This timer is started each time
* there are no active spans on this transaction.
*/
_idleTimeout = TRACING_DEFAULTS.idleTimeout,
/**
* The final value in ms that a transaction cannot exceed
*/
_finalTimeout = TRACING_DEFAULTS.finalTimeout,
_heartbeatInterval = TRACING_DEFAULTS.heartbeatInterval,
// Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends
_onScope = false,
) {
super(transactionContext, _idleHub);this._idleHub = _idleHub;this._idleTimeout = _idleTimeout;this._finalTimeout = _finalTimeout;this._heartbeatInterval = _heartbeatInterval;this._onScope = _onScope;IdleTransaction.prototype.__init.call(this);IdleTransaction.prototype.__init2.call(this);IdleTransaction.prototype.__init3.call(this);IdleTransaction.prototype.__init4.call(this);IdleTransaction.prototype.__init5.call(this);IdleTransaction.prototype.__init6.call(this);
if (_onScope) {
// We set the transaction here on the scope so error events pick up the trace
// context and attach it to the error.
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanId}`);
_idleHub.configureScope(scope => scope.setSpan(this));
}
this._restartIdleTimeout();
setTimeout(() => {
if (!this._finished) {
this.setStatus('deadline_exceeded');
this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];
this.finish();
}
}, this._finalTimeout);
}
/** {@inheritDoc} */
finish(endTimestamp = timestampInSeconds()) {
this._finished = true;
this.activities = {};
if (this.op === 'ui.action.click') {
this.setTag(FINISH_REASON_TAG, this._finishReason);
}
if (this.spanRecorder) {
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&
logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op);
for (const callback of this._beforeFinishCallbacks) {
callback(this, endTimestamp);
}
this.spanRecorder.spans = this.spanRecorder.spans.filter((span) => {
// If we are dealing with the transaction itself, we just return it
if (span.spanId === this.spanId) {
return true;
}
// We cancel all pending spans with status "cancelled" to indicate the idle transaction was finished early
if (!span.endTimestamp) {
span.endTimestamp = endTimestamp;
span.setStatus('cancelled');
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&
logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));
}
const keepSpan = span.startTimestamp < endTimestamp;
if (!keepSpan) {
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) &&
logger.log(
'[Tracing] discarding Span since it happened after Transaction was finished',
JSON.stringify(span, undefined, 2),
);
}
return keepSpan;
});
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] flushing IdleTransaction');
} else {
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] No active IdleTransaction');
}
// if `this._onScope` is `true`, the transaction put itself on the scope when it started
if (this._onScope) {
const scope = this._idleHub.getScope();
if (scope.getTransaction() === this) {
scope.setSpan(undefined);
}
}
return super.finish(endTimestamp);
}
/**
* Register a callback function that gets excecuted before the transaction finishes.
* Useful for cleanup or if you want to add any additional spans based on current context.
*
* This is exposed because users have no other way of running something before an idle transaction
* finishes.
*/
registerBeforeFinishCallback(callback) {
this._beforeFinishCallbacks.push(callback);
}
/**
* @inheritDoc
*/
initSpanRecorder(maxlen) {
if (!this.spanRecorder) {
const pushActivity = (id) => {
if (this._finished) {
return;
}
this._pushActivity(id);
};
const popActivity = (id) => {
if (this._finished) {
return;
}
this._popActivity(id);
};
this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen);
// Start heartbeat so that transactions do not run forever.
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('Starting heartbeat');
this._pingHeartbeat();
}
this.spanRecorder.add(this);
}
/**
* Cancels the existing idle timeout, if there is one.
* @param restartOnChildSpanChange Default is `true`.
* If set to false the transaction will end
* with the last child span.
*/
cancelIdleTimeout(
endTimestamp,
{
restartOnChildSpanChange,
}
= {
restartOnChildSpanChange: true,
},
) {
this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;
if (this._idleTimeoutID) {
clearTimeout(this._idleTimeoutID);
this._idleTimeoutID = undefined;
if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {
this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];
this.finish(endTimestamp);
}
}
}
/**
* Temporary method used to externally set the transaction's `finishReason`
*
* ** WARNING**
* This is for the purpose of experimentation only and will be removed in the near future, do not use!
*
* @internal
*
*/
setFinishReason(reason) {
this._finishReason = reason;
}
/**
* Restarts idle timeout, if there is no running idle timeout it will start one.
*/
_restartIdleTimeout(endTimestamp) {
this.cancelIdleTimeout();
this._idleTimeoutID = setTimeout(() => {
if (!this._finished && Object.keys(this.activities).length === 0) {
this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];
this.finish(endTimestamp);
}
}, this._idleTimeout);
}
/**
* Start tracking a specific activity.
* @param spanId The span id that represents the activity
*/
_pushActivity(spanId) {
this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] pushActivity: ${spanId}`);
this.activities[spanId] = true;
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);
}
/**
* Remove an activity from usage
* @param spanId The span id that represents the activity
*/
_popActivity(spanId) {
if (this.activities[spanId]) {
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`[Tracing] popActivity ${spanId}`);
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete this.activities[spanId];
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);
}
if (Object.keys(this.activities).length === 0) {
const endTimestamp = timestampInSeconds();
if (this._idleTimeoutCanceledPermanently) {
this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];
this.finish(endTimestamp);
} else {
// We need to add the timeout here to have the real endtimestamp of the transaction
// Remember timestampInSeconds is in seconds, timeout is in ms
this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);
}
}
}
/**
* Checks when entries of this.activities are not changing for 3 beats.
* If this occurs we finish the transaction.
*/
_beat() {
// We should not be running heartbeat if the idle transaction is finished.
if (this._finished) {
return;
}
const heartbeatString = Object.keys(this.activities).join('');
if (heartbeatString === this._prevHeartbeatString) {
this._heartbeatCounter++;
} else {
this._heartbeatCounter = 1;
}
this._prevHeartbeatString = heartbeatString;
if (this._heartbeatCounter >= 3) {
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');
this.setStatus('deadline_exceeded');
this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];
this.finish();
} else {
this._pingHeartbeat();
}
}
/**
* Pings the heartbeat
*/
_pingHeartbeat() {
(typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__) && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);
setTimeout(() => {
this._beat();
}, this._heartbeatInterval);
}
}
export { IdleTransaction, IdleTransactionSpanRecorder, TRACING_DEFAULTS };
//# sourceMappingURL=idletransaction.js.map
|