idletransaction.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. import { logger, timestampInSeconds } from '@sentry/utils';
  2. import { DEBUG_BUILD } from '../debug-build.js';
  3. import { spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils.js';
  4. import { SpanRecorder } from './span.js';
  5. import { Transaction } from './transaction.js';
  6. const TRACING_DEFAULTS = {
  7. idleTimeout: 1000,
  8. finalTimeout: 30000,
  9. heartbeatInterval: 5000,
  10. };
  11. const FINISH_REASON_TAG = 'finishReason';
  12. const IDLE_TRANSACTION_FINISH_REASONS = [
  13. 'heartbeatFailed',
  14. 'idleTimeout',
  15. 'documentHidden',
  16. 'finalTimeout',
  17. 'externalFinish',
  18. 'cancelled',
  19. ];
  20. /**
  21. * @inheritDoc
  22. */
  23. class IdleTransactionSpanRecorder extends SpanRecorder {
  24. constructor(
  25. _pushActivity,
  26. _popActivity,
  27. transactionSpanId,
  28. maxlen,
  29. ) {
  30. super(maxlen);this._pushActivity = _pushActivity;this._popActivity = _popActivity;this.transactionSpanId = transactionSpanId; }
  31. /**
  32. * @inheritDoc
  33. */
  34. add(span) {
  35. // We should make sure we do not push and pop activities for
  36. // the transaction that this span recorder belongs to.
  37. if (span.spanContext().spanId !== this.transactionSpanId) {
  38. // We patch span.end() to pop an activity after setting an endTimestamp.
  39. // eslint-disable-next-line @typescript-eslint/unbound-method
  40. const originalEnd = span.end;
  41. span.end = (...rest) => {
  42. this._popActivity(span.spanContext().spanId);
  43. return originalEnd.apply(span, rest);
  44. };
  45. // We should only push new activities if the span does not have an end timestamp.
  46. if (spanToJSON(span).timestamp === undefined) {
  47. this._pushActivity(span.spanContext().spanId);
  48. }
  49. }
  50. super.add(span);
  51. }
  52. }
  53. /**
  54. * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities.
  55. * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will
  56. * put itself on the scope on creation.
  57. */
  58. class IdleTransaction extends Transaction {
  59. // Activities store a list of active spans
  60. // Track state of activities in previous heartbeat
  61. // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats.
  62. // We should not use heartbeat if we finished a transaction
  63. // Idle timeout was canceled and we should finish the transaction with the last span end.
  64. /**
  65. * Timer that tracks Transaction idleTimeout
  66. */
  67. /**
  68. * @deprecated Transactions will be removed in v8. Use spans instead.
  69. */
  70. constructor(
  71. transactionContext,
  72. _idleHub,
  73. /**
  74. * The time to wait in ms until the idle transaction will be finished. This timer is started each time
  75. * there are no active spans on this transaction.
  76. */
  77. _idleTimeout = TRACING_DEFAULTS.idleTimeout,
  78. /**
  79. * The final value in ms that a transaction cannot exceed
  80. */
  81. _finalTimeout = TRACING_DEFAULTS.finalTimeout,
  82. _heartbeatInterval = TRACING_DEFAULTS.heartbeatInterval,
  83. // Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends
  84. _onScope = false,
  85. /**
  86. * When set to `true`, will disable the idle timeout (`_idleTimeout` option) and heartbeat mechanisms (`_heartbeatInterval`
  87. * option) until the `sendAutoFinishSignal()` method is called. The final timeout mechanism (`_finalTimeout` option)
  88. * will not be affected by this option, meaning the transaction will definitely be finished when the final timeout is
  89. * reached, no matter what this option is configured to.
  90. *
  91. * Defaults to `false`.
  92. */
  93. delayAutoFinishUntilSignal = false,
  94. ) {
  95. super(transactionContext, _idleHub);this._idleHub = _idleHub;this._idleTimeout = _idleTimeout;this._finalTimeout = _finalTimeout;this._heartbeatInterval = _heartbeatInterval;this._onScope = _onScope;
  96. this.activities = {};
  97. this._heartbeatCounter = 0;
  98. this._finished = false;
  99. this._idleTimeoutCanceledPermanently = false;
  100. this._beforeFinishCallbacks = [];
  101. this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];
  102. this._autoFinishAllowed = !delayAutoFinishUntilSignal;
  103. if (_onScope) {
  104. // We set the transaction here on the scope so error events pick up the trace
  105. // context and attach it to the error.
  106. DEBUG_BUILD && logger.log(`Setting idle transaction on scope. Span ID: ${this.spanContext().spanId}`);
  107. // eslint-disable-next-line deprecation/deprecation
  108. _idleHub.getScope().setSpan(this);
  109. }
  110. if (!delayAutoFinishUntilSignal) {
  111. this._restartIdleTimeout();
  112. }
  113. setTimeout(() => {
  114. if (!this._finished) {
  115. this.setStatus('deadline_exceeded');
  116. this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[3];
  117. this.end();
  118. }
  119. }, this._finalTimeout);
  120. }
  121. /** {@inheritDoc} */
  122. end(endTimestamp) {
  123. const endTimestampInS = spanTimeInputToSeconds(endTimestamp);
  124. this._finished = true;
  125. this.activities = {};
  126. // eslint-disable-next-line deprecation/deprecation
  127. if (this.op === 'ui.action.click') {
  128. this.setAttribute(FINISH_REASON_TAG, this._finishReason);
  129. }
  130. // eslint-disable-next-line deprecation/deprecation
  131. if (this.spanRecorder) {
  132. DEBUG_BUILD &&
  133. // eslint-disable-next-line deprecation/deprecation
  134. logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestampInS * 1000).toISOString(), this.op);
  135. for (const callback of this._beforeFinishCallbacks) {
  136. callback(this, endTimestampInS);
  137. }
  138. // eslint-disable-next-line deprecation/deprecation
  139. this.spanRecorder.spans = this.spanRecorder.spans.filter((span) => {
  140. // If we are dealing with the transaction itself, we just return it
  141. if (span.spanContext().spanId === this.spanContext().spanId) {
  142. return true;
  143. }
  144. // We cancel all pending spans with status "cancelled" to indicate the idle transaction was finished early
  145. if (!spanToJSON(span).timestamp) {
  146. span.setStatus('cancelled');
  147. span.end(endTimestampInS);
  148. DEBUG_BUILD &&
  149. logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2));
  150. }
  151. const { start_timestamp: startTime, timestamp: endTime } = spanToJSON(span);
  152. const spanStartedBeforeTransactionFinish = startTime && startTime < endTimestampInS;
  153. // Add a delta with idle timeout so that we prevent false positives
  154. const timeoutWithMarginOfError = (this._finalTimeout + this._idleTimeout) / 1000;
  155. const spanEndedBeforeFinalTimeout = endTime && startTime && endTime - startTime < timeoutWithMarginOfError;
  156. if (DEBUG_BUILD) {
  157. const stringifiedSpan = JSON.stringify(span, undefined, 2);
  158. if (!spanStartedBeforeTransactionFinish) {
  159. logger.log('[Tracing] discarding Span since it happened after Transaction was finished', stringifiedSpan);
  160. } else if (!spanEndedBeforeFinalTimeout) {
  161. logger.log('[Tracing] discarding Span since it finished after Transaction final timeout', stringifiedSpan);
  162. }
  163. }
  164. return spanStartedBeforeTransactionFinish && spanEndedBeforeFinalTimeout;
  165. });
  166. DEBUG_BUILD && logger.log('[Tracing] flushing IdleTransaction');
  167. } else {
  168. DEBUG_BUILD && logger.log('[Tracing] No active IdleTransaction');
  169. }
  170. // if `this._onScope` is `true`, the transaction put itself on the scope when it started
  171. if (this._onScope) {
  172. // eslint-disable-next-line deprecation/deprecation
  173. const scope = this._idleHub.getScope();
  174. // eslint-disable-next-line deprecation/deprecation
  175. if (scope.getTransaction() === this) {
  176. // eslint-disable-next-line deprecation/deprecation
  177. scope.setSpan(undefined);
  178. }
  179. }
  180. return super.end(endTimestamp);
  181. }
  182. /**
  183. * Register a callback function that gets executed before the transaction finishes.
  184. * Useful for cleanup or if you want to add any additional spans based on current context.
  185. *
  186. * This is exposed because users have no other way of running something before an idle transaction
  187. * finishes.
  188. */
  189. registerBeforeFinishCallback(callback) {
  190. this._beforeFinishCallbacks.push(callback);
  191. }
  192. /**
  193. * @inheritDoc
  194. */
  195. initSpanRecorder(maxlen) {
  196. // eslint-disable-next-line deprecation/deprecation
  197. if (!this.spanRecorder) {
  198. const pushActivity = (id) => {
  199. if (this._finished) {
  200. return;
  201. }
  202. this._pushActivity(id);
  203. };
  204. const popActivity = (id) => {
  205. if (this._finished) {
  206. return;
  207. }
  208. this._popActivity(id);
  209. };
  210. // eslint-disable-next-line deprecation/deprecation
  211. this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanContext().spanId, maxlen);
  212. // Start heartbeat so that transactions do not run forever.
  213. DEBUG_BUILD && logger.log('Starting heartbeat');
  214. this._pingHeartbeat();
  215. }
  216. // eslint-disable-next-line deprecation/deprecation
  217. this.spanRecorder.add(this);
  218. }
  219. /**
  220. * Cancels the existing idle timeout, if there is one.
  221. * @param restartOnChildSpanChange Default is `true`.
  222. * If set to false the transaction will end
  223. * with the last child span.
  224. */
  225. cancelIdleTimeout(
  226. endTimestamp,
  227. {
  228. restartOnChildSpanChange,
  229. }
  230. = {
  231. restartOnChildSpanChange: true,
  232. },
  233. ) {
  234. this._idleTimeoutCanceledPermanently = restartOnChildSpanChange === false;
  235. if (this._idleTimeoutID) {
  236. clearTimeout(this._idleTimeoutID);
  237. this._idleTimeoutID = undefined;
  238. if (Object.keys(this.activities).length === 0 && this._idleTimeoutCanceledPermanently) {
  239. this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];
  240. this.end(endTimestamp);
  241. }
  242. }
  243. }
  244. /**
  245. * Temporary method used to externally set the transaction's `finishReason`
  246. *
  247. * ** WARNING**
  248. * This is for the purpose of experimentation only and will be removed in the near future, do not use!
  249. *
  250. * @internal
  251. *
  252. */
  253. setFinishReason(reason) {
  254. this._finishReason = reason;
  255. }
  256. /**
  257. * Permits the IdleTransaction to automatically end itself via the idle timeout and heartbeat mechanisms when the `delayAutoFinishUntilSignal` option was set to `true`.
  258. */
  259. sendAutoFinishSignal() {
  260. if (!this._autoFinishAllowed) {
  261. DEBUG_BUILD && logger.log('[Tracing] Received finish signal for idle transaction.');
  262. this._restartIdleTimeout();
  263. this._autoFinishAllowed = true;
  264. }
  265. }
  266. /**
  267. * Restarts idle timeout, if there is no running idle timeout it will start one.
  268. */
  269. _restartIdleTimeout(endTimestamp) {
  270. this.cancelIdleTimeout();
  271. this._idleTimeoutID = setTimeout(() => {
  272. if (!this._finished && Object.keys(this.activities).length === 0) {
  273. this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];
  274. this.end(endTimestamp);
  275. }
  276. }, this._idleTimeout);
  277. }
  278. /**
  279. * Start tracking a specific activity.
  280. * @param spanId The span id that represents the activity
  281. */
  282. _pushActivity(spanId) {
  283. this.cancelIdleTimeout(undefined, { restartOnChildSpanChange: !this._idleTimeoutCanceledPermanently });
  284. DEBUG_BUILD && logger.log(`[Tracing] pushActivity: ${spanId}`);
  285. this.activities[spanId] = true;
  286. DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);
  287. }
  288. /**
  289. * Remove an activity from usage
  290. * @param spanId The span id that represents the activity
  291. */
  292. _popActivity(spanId) {
  293. if (this.activities[spanId]) {
  294. DEBUG_BUILD && logger.log(`[Tracing] popActivity ${spanId}`);
  295. // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
  296. delete this.activities[spanId];
  297. DEBUG_BUILD && logger.log('[Tracing] new activities count', Object.keys(this.activities).length);
  298. }
  299. if (Object.keys(this.activities).length === 0) {
  300. const endTimestamp = timestampInSeconds();
  301. if (this._idleTimeoutCanceledPermanently) {
  302. if (this._autoFinishAllowed) {
  303. this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];
  304. this.end(endTimestamp);
  305. }
  306. } else {
  307. // We need to add the timeout here to have the real endtimestamp of the transaction
  308. // Remember timestampInSeconds is in seconds, timeout is in ms
  309. this._restartIdleTimeout(endTimestamp + this._idleTimeout / 1000);
  310. }
  311. }
  312. }
  313. /**
  314. * Checks when entries of this.activities are not changing for 3 beats.
  315. * If this occurs we finish the transaction.
  316. */
  317. _beat() {
  318. // We should not be running heartbeat if the idle transaction is finished.
  319. if (this._finished) {
  320. return;
  321. }
  322. const heartbeatString = Object.keys(this.activities).join('');
  323. if (heartbeatString === this._prevHeartbeatString) {
  324. this._heartbeatCounter++;
  325. } else {
  326. this._heartbeatCounter = 1;
  327. }
  328. this._prevHeartbeatString = heartbeatString;
  329. if (this._heartbeatCounter >= 3) {
  330. if (this._autoFinishAllowed) {
  331. DEBUG_BUILD && logger.log('[Tracing] Transaction finished because of no change for 3 heart beats');
  332. this.setStatus('deadline_exceeded');
  333. this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[0];
  334. this.end();
  335. }
  336. } else {
  337. this._pingHeartbeat();
  338. }
  339. }
  340. /**
  341. * Pings the heartbeat
  342. */
  343. _pingHeartbeat() {
  344. DEBUG_BUILD && logger.log(`pinging Heartbeat -> current counter: ${this._heartbeatCounter}`);
  345. setTimeout(() => {
  346. this._beat();
  347. }, this._heartbeatInterval);
  348. }
  349. }
  350. export { IdleTransaction, IdleTransactionSpanRecorder, TRACING_DEFAULTS };
  351. //# sourceMappingURL=idletransaction.js.map