Skip to content

fix(tracing-internal): Delay pageload transaction finish until document is interactive #10215

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jan 18, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/core/src/tracing/hubextensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,22 @@ export function startIdleTransaction(
onScope?: boolean,
customSamplingContext?: CustomSamplingContext,
heartbeatInterval?: number,
delayAutoFinishUntilSignal: boolean = false,
): IdleTransaction {
// eslint-disable-next-line deprecation/deprecation
const client = hub.getClient();
const options: Partial<ClientOptions> = (client && client.getOptions()) || {};

// eslint-disable-next-line deprecation/deprecation
let transaction = new IdleTransaction(transactionContext, hub, idleTimeout, finalTimeout, heartbeatInterval, onScope);
let transaction = new IdleTransaction(
transactionContext,
hub,
idleTimeout,
finalTimeout,
heartbeatInterval,
onScope,
delayAutoFinishUntilSignal,
);
transaction = sampleTransaction(transaction, options, {
parentSampled: transactionContext.parentSampled,
transactionContext,
Expand Down
48 changes: 39 additions & 9 deletions packages/core/src/tracing/idletransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,8 @@ export class IdleTransaction extends Transaction {

private _finishReason: (typeof IDLE_TRANSACTION_FINISH_REASONS)[number];

private _autoFinishAllowed: boolean;

/**
* @deprecated Transactions will be removed in v8. Use spans instead.
*/
Expand All @@ -113,6 +115,15 @@ export class IdleTransaction extends Transaction {
private readonly _heartbeatInterval: number = TRACING_DEFAULTS.heartbeatInterval,
// Whether or not the transaction should put itself on the scope when it starts and pop itself off when it ends
private readonly _onScope: boolean = false,
/**
* When set to `true`, will disable the idle timeout (`_idleTimeout` option) and heartbeat mechanisms (`_heartbeatInterval`
* option) until the `sendAutoFinishSignal()` method is called. The final timeout mechanism (`_finalTimeout` option)
* will not be affected by this option, meaning the transaction will definitely be finished when the final timeout is
* reached, no matter what this option is configured to.
*
* Defaults to `false`.
*/
delayAutoFinishUntilSignal: boolean = false,
) {
super(transactionContext, _idleHub);

Expand All @@ -122,6 +133,7 @@ export class IdleTransaction extends Transaction {
this._idleTimeoutCanceledPermanently = false;
this._beforeFinishCallbacks = [];
this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[4];
this._autoFinishAllowed = !delayAutoFinishUntilSignal;

if (_onScope) {
// We set the transaction here on the scope so error events pick up the trace
Expand All @@ -131,7 +143,10 @@ export class IdleTransaction extends Transaction {
_idleHub.getScope().setSpan(this);
}

this._restartIdleTimeout();
if (!delayAutoFinishUntilSignal) {
this._restartIdleTimeout();
}

setTimeout(() => {
if (!this._finished) {
this.setStatus('deadline_exceeded');
Expand Down Expand Up @@ -215,7 +230,7 @@ export class IdleTransaction extends Transaction {
}

/**
* Register a callback function that gets excecuted before the transaction finishes.
* Register a callback function that gets executed 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
Expand Down Expand Up @@ -296,13 +311,24 @@ export class IdleTransaction extends Transaction {
this._finishReason = reason;
}

/**
* Permits the IdleTransaction to automatically end itself via the idle timeout and heartbeat mechanisms when the `delayAutoFinishUntilSignal` option was set to `true`.
*/
public sendAutoFinishSignal(): void {
if (!this._autoFinishAllowed) {
DEBUG_BUILD && logger.log('[Tracing] Received finish signal for idle transaction.');
this._restartIdleTimeout();
this._autoFinishAllowed = true;
}
}

/**
* Restarts idle timeout, if there is no running idle timeout it will start one.
*/
private _restartIdleTimeout(endTimestamp?: Parameters<IdleTransaction['end']>[0]): void {
this.cancelIdleTimeout();
this._idleTimeoutID = setTimeout(() => {
if (!this._finished && Object.keys(this.activities).length === 0) {
if (!this._finished && Object.keys(this.activities).length === 0 && this._autoFinishAllowed) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need this check here? 🤔 as we are guarding even calling this function above?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

great point

this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[1];
this.end(endTimestamp);
}
Expand Down Expand Up @@ -335,8 +361,10 @@ export class IdleTransaction extends Transaction {
if (Object.keys(this.activities).length === 0) {
const endTimestamp = timestampInSeconds();
if (this._idleTimeoutCanceledPermanently) {
this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];
this.end(endTimestamp);
if (this._autoFinishAllowed) {
this._finishReason = IDLE_TRANSACTION_FINISH_REASONS[5];
this.end(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
Expand Down Expand Up @@ -366,10 +394,12 @@ export class IdleTransaction extends Transaction {
this._prevHeartbeatString = heartbeatString;

if (this._heartbeatCounter >= 3) {
DEBUG_BUILD && 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.end();
if (this._autoFinishAllowed) {
DEBUG_BUILD && 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.end();
}
} else {
this._pingHeartbeat();
}
Expand Down
13 changes: 13 additions & 0 deletions packages/tracing-internal/src/browser/browsertracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -368,8 +368,21 @@ export class BrowserTracing implements Integration {
true,
{ location }, // for use in the tracesSampler
heartbeatInterval,
isPageloadTransaction, // should wait for finish signal if it's a pageload transaction
);

if (isPageloadTransaction) {
WINDOW.document.addEventListener('readystatechange', () => {
if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {
idleTransaction.sendAutoFinishSignal();
}
});

if (['interactive', 'complete'].includes(WINDOW.document.readyState)) {
idleTransaction.sendAutoFinishSignal();
}
}

// eslint-disable-next-line deprecation/deprecation
const scope = hub.getScope();

Expand Down
4 changes: 4 additions & 0 deletions packages/tracing-internal/test/browser/browsertracing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -411,6 +411,7 @@ conditionalTest({ min: 10 })('BrowserTracing', () => {
expect.any(Boolean),
expect.any(Object),
expect.any(Number),
true,
);
});

Expand All @@ -419,6 +420,7 @@ conditionalTest({ min: 10 })('BrowserTracing', () => {
createBrowserTracing(true, { routingInstrumentation: customInstrumentRouting });
const mockFinish = jest.fn();
const transaction = getActiveTransaction(hub) as IdleTransaction;
transaction.sendAutoFinishSignal();
transaction.end = mockFinish;

const span = transaction.startChild(); // activities = 1
Expand All @@ -433,6 +435,7 @@ conditionalTest({ min: 10 })('BrowserTracing', () => {
createBrowserTracing(true, { idleTimeout: 2000, routingInstrumentation: customInstrumentRouting });
const mockFinish = jest.fn();
const transaction = getActiveTransaction(hub) as IdleTransaction;
transaction.sendAutoFinishSignal();
transaction.end = mockFinish;

const span = transaction.startChild(); // activities = 1
Expand Down Expand Up @@ -461,6 +464,7 @@ conditionalTest({ min: 10 })('BrowserTracing', () => {
createBrowserTracing(true, { heartbeatInterval: interval, routingInstrumentation: customInstrumentRouting });
const mockFinish = jest.fn();
const transaction = getActiveTransaction(hub) as IdleTransaction;
transaction.sendAutoFinishSignal();
transaction.end = mockFinish;

const span = transaction.startChild(); // activities = 1
Expand Down