Skip to content

feat(tracing): Add metadata around idleTimeout #4251

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 2 commits into from
Dec 8, 2021
Merged
Show file tree
Hide file tree
Changes from all 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
2 changes: 2 additions & 0 deletions packages/tracing/src/browser/backgroundtab.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { getGlobalObject, logger } from '@sentry/utils';

import { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from '../constants';
import { IdleTransaction } from '../idletransaction';
import { SpanStatus } from '../spanstatus';
import { getActiveTransaction } from '../utils';
Expand All @@ -24,6 +25,7 @@ export function registerBackgroundTabDetection(): void {
activeTransaction.setStatus(SpanStatus.Cancelled);
}
activeTransaction.setTag('visibilitychange', 'document.hidden');
activeTransaction.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[2]);
activeTransaction.finish();
}
});
Expand Down
28 changes: 16 additions & 12 deletions packages/tracing/src/browser/browsertracing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../idletransaction';
import { SpanStatus } from '../spanstatus';
import { extractTraceparentData, secToMs } from '../utils';
import { registerBackgroundTabDetection } from './backgroundtab';
import { DEFAULT_METRICS_INSTR_OPTIONS, MetricsInstrumentation, MetricsInstrumentationOptions } from './metrics';
import { MetricsInstrumentation } from './metrics';
import {
defaultRequestInstrumentationOptions,
instrumentOutgoingRequests,
Expand Down Expand Up @@ -67,7 +67,7 @@ export interface BrowserTracingOptions extends RequestInstrumentationOptions {
*
* Default: undefined
*/
_metricOptions?: Partial<MetricsInstrumentationOptions>;
_metricOptions?: Partial<{ _reportAllChanges: boolean }>;

/**
* beforeNavigate is called before a pageload/navigation transaction is created and allows users to modify transaction
Expand Down Expand Up @@ -129,18 +129,19 @@ export class BrowserTracing implements Integration {

private readonly _emitOptionsWarning: boolean = false;

/** Store configured idle timeout so that it can be added as a tag to transactions */
private _configuredIdleTimeout: BrowserTracingOptions['idleTimeout'] | undefined = undefined;

public constructor(_options?: Partial<BrowserTracingOptions>) {
let tracingOrigins = defaultRequestInstrumentationOptions.tracingOrigins;
// NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances
if (
_options &&
_options.tracingOrigins &&
Array.isArray(_options.tracingOrigins) &&
_options.tracingOrigins.length !== 0
) {
tracingOrigins = _options.tracingOrigins;
} else {
this._emitOptionsWarning = true;
if (_options) {
this._configuredIdleTimeout = _options.idleTimeout;
if (_options.tracingOrigins && Array.isArray(_options.tracingOrigins) && _options.tracingOrigins.length !== 0) {
tracingOrigins = _options.tracingOrigins;
} else {
this._emitOptionsWarning = true;
}
}

this.options = {
Expand All @@ -149,7 +150,8 @@ export class BrowserTracing implements Integration {
tracingOrigins,
};

this._metrics = new MetricsInstrumentation({ ...DEFAULT_METRICS_INSTR_OPTIONS, ...this.options._metricOptions });
const { _metricOptions } = this.options;
this._metrics = new MetricsInstrumentation(_metricOptions && _metricOptions._reportAllChanges);
}

/**
Expand Down Expand Up @@ -236,6 +238,8 @@ export class BrowserTracing implements Integration {
adjustTransactionDuration(secToMs(maxTransactionDuration), transaction, endTimestamp);
});

idleTransaction.setTag('idleTimeout', this._configuredIdleTimeout);

return idleTransaction as Transaction;
}
}
Expand Down
21 changes: 6 additions & 15 deletions packages/tracing/src/browser/metrics.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,6 @@ import { NavigatorDeviceMemory, NavigatorNetworkInformation } from './web-vitals

const global = getGlobalObject<Window>();

/**
* Exports a way to add options to our metric collection. Currently experimental.
*/
export interface MetricsInstrumentationOptions {
_reportAllChanges: boolean;
}

export const DEFAULT_METRICS_INSTR_OPTIONS: MetricsInstrumentationOptions = {
_reportAllChanges: false,
};
Copy link
Member Author

Choose a reason for hiding this comment

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

Removed this logic to save on bundle size. We can add back in an options object when we have more than 1 option.


/** Class tracking metrics */
export class MetricsInstrumentation {
private _measurements: Measurements = {};
Expand All @@ -33,14 +22,14 @@ export class MetricsInstrumentation {
private _lcpEntry: LargestContentfulPaint | undefined;
private _clsEntry: LayoutShift | undefined;

public constructor(_options: MetricsInstrumentationOptions) {
public constructor(private _reportAllChanges: boolean = false) {
if (!isNodeEnv() && global?.performance && global?.document) {
if (global.performance.mark) {
global.performance.mark('sentry-tracing-init');
}

this._trackCLS();
this._trackLCP(_options._reportAllChanges);
this._trackLCP();
this._trackFID();
}
}
Expand Down Expand Up @@ -206,6 +195,8 @@ export class MetricsInstrumentation {

transaction.setMeasurements(this._measurements);
this._tagMetricInfo(transaction);

transaction.setTag('sentry_reportAllChanges', this._reportAllChanges);
}
}

Expand Down Expand Up @@ -296,7 +287,7 @@ export class MetricsInstrumentation {
}

/** Starts tracking the Largest Contentful Paint on the current page. */
private _trackLCP(reportAllChanges: boolean): void {
private _trackLCP(): void {
getLCP(metric => {
const entry = metric.entries.pop();

Expand All @@ -310,7 +301,7 @@ export class MetricsInstrumentation {
this._measurements['lcp'] = { value: metric.value };
this._measurements['mark.lcp'] = { value: timeOrigin + startTime };
this._lcpEntry = entry as LargestContentfulPaint;
}, reportAllChanges);
}, this._reportAllChanges);
}

/** Starts tracking the First Input Delay on the current page. */
Expand Down
5 changes: 5 additions & 0 deletions packages/tracing/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Store finish reasons in tuple to save on bundle size
// Readonly type should enforce that this is not mutated.
export const FINISH_REASON_TAG = 'finishReason';

export const IDLE_TRANSACTION_FINISH_REASONS = ['heartbeatFailed', 'idleTimeout', 'documentHidden'] as const;
4 changes: 3 additions & 1 deletion packages/tracing/src/idletransaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Hub } from '@sentry/hub';
import { TransactionContext } from '@sentry/types';
import { logger, timestampWithMs } from '@sentry/utils';

import { FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS } from './constants';
import { Span, SpanRecorder } from './span';
import { SpanStatus } from './spanstatus';
import { Transaction } from './transaction';
Expand Down Expand Up @@ -223,6 +224,7 @@ export class IdleTransaction extends Transaction {

setTimeout(() => {
if (!this._finished) {
this.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[1]);
this.finish(end);
}
}, timeout);
Expand Down Expand Up @@ -252,7 +254,7 @@ export class IdleTransaction extends Transaction {
if (this._heartbeatCounter >= 3) {
logger.log(`[Tracing] Transaction finished because of no change for 3 heart beats`);
this.setStatus(SpanStatus.DeadlineExceeded);
this.setTag('heartbeat', 'failed');
this.setTag(FINISH_REASON_TAG, IDLE_TRANSACTION_FINISH_REASONS[0]);
this.finish();
} else {
this._pingHeartbeat();
Expand Down
12 changes: 7 additions & 5 deletions packages/tracing/test/browser/browsertracing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import {
getHeaderContext,
getMetaContent,
} from '../../src/browser/browsertracing';
import { DEFAULT_METRICS_INSTR_OPTIONS, MetricsInstrumentation } from '../../src/browser/metrics';
import { MetricsInstrumentation } from '../../src/browser/metrics';
import { defaultRequestInstrumentationOptions } from '../../src/browser/request';
import { instrumentRoutingWithDefaults } from '../../src/browser/router';
import * as hubExtensions from '../../src/hubextensions';
Expand Down Expand Up @@ -246,6 +246,8 @@ describe('BrowserTracing', () => {
expect(mockFinish).toHaveBeenCalledTimes(0);
jest.advanceTimersByTime(DEFAULT_IDLE_TIMEOUT);
expect(mockFinish).toHaveBeenCalledTimes(1);

expect(transaction.tags).toEqual({ finishReason: 'idleTimeout', idleTimeout: undefined });
});

it('can be a custom value', () => {
Expand All @@ -260,6 +262,8 @@ describe('BrowserTracing', () => {
expect(mockFinish).toHaveBeenCalledTimes(0);
jest.advanceTimersByTime(2000);
expect(mockFinish).toHaveBeenCalledTimes(1);

expect(transaction.tags).toEqual({ finishReason: 'idleTimeout', idleTimeout: 2000 });
});
});

Expand Down Expand Up @@ -507,7 +511,7 @@ describe('BrowserTracing', () => {
createBrowserTracing(true, {});

expect(MetricsInstrumentation).toHaveBeenCalledTimes(1);
expect(MetricsInstrumentation).toHaveBeenLastCalledWith(DEFAULT_METRICS_INSTR_OPTIONS);
expect(MetricsInstrumentation).toHaveBeenLastCalledWith(undefined);
});

it('creates metrics instrumentation with custom options', () => {
Expand All @@ -518,9 +522,7 @@ describe('BrowserTracing', () => {
});

expect(MetricsInstrumentation).toHaveBeenCalledTimes(1);
expect(MetricsInstrumentation).toHaveBeenLastCalledWith({
_reportAllChanges: true,
});
expect(MetricsInstrumentation).toHaveBeenLastCalledWith(true);
});
});
});