From 3c90917b48e14375295daa44d556552d05370bd8 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Fri, 3 Jul 2020 13:00:46 -0400 Subject: [PATCH] feat: Add @sentry/tracing CHANGELOG Rename tracing to APM bring back APM fix: APM -> tracing feat(tracing): Add @sentry/tracing delete src mass rename mass move test chore: Change APM -> Tracing feat(tracing): Add IdleTransaction class ref: Delete Tracing integration feat: BrowserTracing integration some comments about what I've done so far router stuff more router changes more comments and thoughts refactor heartbeat beforeFinish Squash 1 router tracing init reset active transactions more idle transaction refactor Revert "mass move test" This reverts commit c1a11a16ac9981e71ba180a5f0a1dd86a4c19813. Revert "mass rename" This reverts commit 8173c5d0716e4b7e59a4e32dc6e5701208525b30. Revert "delete src" This reverts commit 0298cd442c31644764da93901a5bfae5c90f9881. fix routing typings sentry-trace meta tag Add request logic smaller errors + backgroundtab performance fix stuff fix some errors get it working it finally works :) zero counter react changes Vue changes Fix all errors delete tracing again again any typings any changes more refactors Fix performance and router better --- packages/hub/src/hub.ts | 4 +- packages/integrations/src/vue.ts | 63 +- packages/react/src/profiler.tsx | 116 +- packages/tracing/src/hubextensions.ts | 5 +- packages/tracing/src/idletransaction.ts | 272 +++++ packages/tracing/src/index.bundle.ts | 4 +- packages/tracing/src/index.ts | 4 +- .../src/integrations/browsertracing.ts | 275 +++++ packages/tracing/src/integrations/index.ts | 2 +- packages/tracing/src/integrations/tracing.ts | 1058 ----------------- .../src/integrations/tracing/backgroundtab.ts | 30 + .../src/integrations/tracing/errors.ts | 29 + .../src/integrations/tracing/performance.ts | 251 ++++ .../src/integrations/tracing/request.ts | 256 ++++ .../src/integrations/tracing/router.ts | 220 ++++ .../tracing/src/integrations/tracing/types.ts | 109 ++ .../tracing/src/integrations/tracing/utils.ts | 27 + packages/tracing/test/idletransaction.test.ts | 203 ++++ packages/types/src/hub.ts | 2 +- 19 files changed, 1740 insertions(+), 1190 deletions(-) create mode 100644 packages/tracing/src/idletransaction.ts create mode 100644 packages/tracing/src/integrations/browsertracing.ts delete mode 100644 packages/tracing/src/integrations/tracing.ts create mode 100644 packages/tracing/src/integrations/tracing/backgroundtab.ts create mode 100644 packages/tracing/src/integrations/tracing/errors.ts create mode 100644 packages/tracing/src/integrations/tracing/performance.ts create mode 100644 packages/tracing/src/integrations/tracing/request.ts create mode 100644 packages/tracing/src/integrations/tracing/router.ts create mode 100644 packages/tracing/src/integrations/tracing/types.ts create mode 100644 packages/tracing/src/integrations/tracing/utils.ts create mode 100644 packages/tracing/test/idletransaction.test.ts diff --git a/packages/hub/src/hub.ts b/packages/hub/src/hub.ts index a6bf56bcb45c..5177f591765c 100644 --- a/packages/hub/src/hub.ts +++ b/packages/hub/src/hub.ts @@ -376,8 +376,8 @@ export class Hub implements HubInterface { /** * @inheritDoc */ - public startTransaction(context: TransactionContext): Transaction { - return this._callExtensionMethod('startTransaction', context); + public startTransaction(context: TransactionContext, idleTimeout?: number): Transaction { + return this._callExtensionMethod('startTransaction', context, idleTimeout); } /** diff --git a/packages/integrations/src/vue.ts b/packages/integrations/src/vue.ts index 6d62d811ca5e..064c93ab915a 100644 --- a/packages/integrations/src/vue.ts +++ b/packages/integrations/src/vue.ts @@ -1,13 +1,19 @@ -import { EventProcessor, Hub, Integration, IntegrationClass, Span } from '@sentry/types'; +import { EventProcessor, Hub, Integration, Scope, Span, Transaction } from '@sentry/types'; import { basename, getGlobalObject, logger, timestampWithMs } from '@sentry/utils'; -/** - * Used to extract Tracing integration from the current client, - * without the need to import `Tracing` itself from the @sentry/apm package. - */ -const TRACING_GETTER = ({ - id: 'Tracing', -} as any) as IntegrationClass; +// tslint:disable-next-line: completed-docs +function getActiveTransaction(hub: Hub & { getScope?(): Scope }): Transaction | undefined { + if (!hub.getScope) { + return undefined; + } + + const scope = hub.getScope(); + if (scope) { + return scope.getTransaction(); + } + + return undefined; +} /** Global Vue object limited to the methods/attributes we require */ interface VueInstance { @@ -137,7 +143,6 @@ export class Vue implements Integration { private readonly _componentsCache: { [key: string]: string } = {}; private _rootSpan?: Span; private _rootSpanTimer?: ReturnType; - private _tracingActivity?: number; /** * @inheritDoc @@ -221,7 +226,7 @@ export class Vue implements Integration { // On the first handler call (before), it'll be undefined, as `$once` will add it in the future. // However, on the second call (after), it'll be already in place. if (this._rootSpan) { - this._finishRootSpan(now, getCurrentHub); + this._finishRootSpan(now); } else { vm.$once(`hook:${hook}`, () => { // Create an activity on the first event call. There'll be no second call, as rootSpan will be in place, @@ -229,19 +234,12 @@ export class Vue implements Integration { // We do this whole dance with `TRACING_GETTER` to prevent `@sentry/apm` from becoming a peerDependency. // We also need to ask for the `.constructor`, as `pushActivity` and `popActivity` are static, not instance methods. - const tracingIntegration = getCurrentHub().getIntegration(TRACING_GETTER); - if (tracingIntegration) { - // tslint:disable-next-line:no-unsafe-any - this._tracingActivity = (tracingIntegration as any).constructor.pushActivity('Vue Application Render'); - // tslint:disable-next-line:no-unsafe-any - const transaction = (tracingIntegration as any).constructor.getTransaction(); - if (transaction) { - // tslint:disable-next-line:no-unsafe-any - this._rootSpan = transaction.startChild({ - description: 'Application Render', - op: 'Vue', - }); - } + const activeTransaction = getActiveTransaction(getCurrentHub()); + if (activeTransaction) { + this._rootSpan = activeTransaction.startChild({ + description: 'Application Render', + op: 'Vue', + }); } }); } @@ -264,7 +262,7 @@ export class Vue implements Integration { // However, on the second call (after), it'll be already in place. if (span) { span.finish(); - this._finishRootSpan(now, getCurrentHub); + this._finishRootSpan(now); } else { vm.$once(`hook:${hook}`, () => { if (this._rootSpan) { @@ -306,23 +304,14 @@ export class Vue implements Integration { }; /** Finish top-level span and activity with a debounce configured using `timeout` option */ - private _finishRootSpan(timestamp: number, getCurrentHub: () => Hub): void { + private _finishRootSpan(timestamp: number): void { if (this._rootSpanTimer) { clearTimeout(this._rootSpanTimer); } this._rootSpanTimer = setTimeout(() => { - if (this._tracingActivity) { - // We do this whole dance with `TRACING_GETTER` to prevent `@sentry/apm` from becoming a peerDependency. - // We also need to ask for the `.constructor`, as `pushActivity` and `popActivity` are static, not instance methods. - const tracingIntegration = getCurrentHub().getIntegration(TRACING_GETTER); - if (tracingIntegration) { - // tslint:disable-next-line:no-unsafe-any - (tracingIntegration as any).constructor.popActivity(this._tracingActivity); - if (this._rootSpan) { - this._rootSpan.finish(timestamp); - } - } + if (this._rootSpan) { + this._rootSpan.finish(timestamp); } }, this._options.tracingOptions.timeout); } @@ -333,7 +322,7 @@ export class Vue implements Integration { this._options.Vue.mixin({ beforeCreate(this: ViewModel): void { - if (getCurrentHub().getIntegration(TRACING_GETTER)) { + if (getActiveTransaction(getCurrentHub())) { // `this` points to currently rendered component applyTracingHooks(this, getCurrentHub); } else { diff --git a/packages/react/src/profiler.tsx b/packages/react/src/profiler.tsx index 2af9dbaab86d..e11ef64009c9 100644 --- a/packages/react/src/profiler.tsx +++ b/packages/react/src/profiler.tsx @@ -1,79 +1,19 @@ import { getCurrentHub } from '@sentry/browser'; -import { Integration, IntegrationClass, Span } from '@sentry/types'; -import { logger, timestampWithMs } from '@sentry/utils'; +import { Span, Transaction } from '@sentry/types'; +import { timestampWithMs } from '@sentry/utils'; import * as hoistNonReactStatic from 'hoist-non-react-statics'; import * as React from 'react'; export const UNKNOWN_COMPONENT = 'unknown'; -const TRACING_GETTER = ({ - id: 'Tracing', -} as any) as IntegrationClass; - -let globalTracingIntegration: Integration | null = null; -const getTracingIntegration = () => { - if (globalTracingIntegration) { - return globalTracingIntegration; - } - - globalTracingIntegration = getCurrentHub().getIntegration(TRACING_GETTER); - return globalTracingIntegration; -}; - -/** - * Warn if tracing integration not configured. Will only warn once. - */ -function warnAboutTracing(name: string): void { - if (globalTracingIntegration === null) { - logger.warn( - `Unable to profile component ${name} due to invalid Tracing Integration. Please make sure the Tracing integration is setup properly.`, - ); - } -} - -/** - * pushActivity creates an new react activity. - * Is a no-op if Tracing integration is not valid - * @param name displayName of component that started activity - */ -function pushActivity(name: string, op: string): number | null { - if (globalTracingIntegration === null) { - return null; +function getActiveTransaction(): Transaction | undefined { + const hub = getCurrentHub(); + const scope = hub.getScope(); + if (scope) { + return scope.getTransaction(); } - // tslint:disable-next-line:no-unsafe-any - return (globalTracingIntegration as any).constructor.pushActivity(name, { - description: `<${name}>`, - op: `react.${op}`, - }); -} - -/** - * popActivity removes a React activity. - * Is a no-op if Tracing integration is not valid. - * @param activity id of activity that is being popped - */ -function popActivity(activity: number | null): void { - if (activity === null || globalTracingIntegration === null) { - return; - } - - // tslint:disable-next-line:no-unsafe-any - (globalTracingIntegration as any).constructor.popActivity(activity); -} - -/** - * Obtain a span given an activity id. - * Is a no-op if Tracing integration is not valid. - * @param activity activity id associated with obtained span - */ -function getActivitySpan(activity: number | null): Span | undefined { - if (activity === null || globalTracingIntegration === null) { - return undefined; - } - - // tslint:disable-next-line:no-unsafe-any - return (globalTracingIntegration as any).constructor.getActivitySpan(activity) as Span | undefined; + return undefined; } export type ProfilerProps = { @@ -95,8 +35,6 @@ export type ProfilerProps = { * spans based on component lifecycles. */ class Profiler extends React.Component { - // The activity representing how long it takes to mount a component. - public mountActivity: number | null = null; // The span of the mount activity public mountSpan: Span | undefined = undefined; // The span of the render @@ -116,18 +54,21 @@ class Profiler extends React.Component { return; } - if (getTracingIntegration()) { - this.mountActivity = pushActivity(name, 'mount'); - } else { - warnAboutTracing(name); + const activeTransaction = getActiveTransaction(); + + if (activeTransaction) { + this.mountSpan = activeTransaction.startChild({ + description: `<${name}>`, + op: 'react.mount', + }); } } // If a component mounted, we can finish the mount activity. public componentDidMount(): void { - this.mountSpan = getActivitySpan(this.mountActivity); - popActivity(this.mountActivity); - this.mountActivity = null; + if (this.mountSpan) { + this.mountSpan.finish(); + } } public componentDidUpdate({ updateProps, includeUpdates = true }: ProfilerProps): void { @@ -221,22 +162,27 @@ function useProfiler( hasRenderSpan: true, }, ): void { - const [mountActivity] = React.useState(() => { + const [mountSpan] = React.useState(() => { if (options && options.disabled) { - return null; + return undefined; } - if (getTracingIntegration()) { - return pushActivity(name, 'mount'); + const activeTransaction = getActiveTransaction(); + + if (activeTransaction) { + return activeTransaction.startChild({ + description: `<${name}>`, + op: 'react.mount', + }); } - warnAboutTracing(name); - return null; + return undefined; }); React.useEffect(() => { - const mountSpan = getActivitySpan(mountActivity); - popActivity(mountActivity); + if (mountSpan) { + mountSpan.finish(); + } return () => { if (mountSpan && options.hasRenderSpan) { diff --git a/packages/tracing/src/hubextensions.ts b/packages/tracing/src/hubextensions.ts index 8480ffbf1bde..7e2a80420069 100644 --- a/packages/tracing/src/hubextensions.ts +++ b/packages/tracing/src/hubextensions.ts @@ -2,6 +2,7 @@ import { getMainCarrier, Hub } from '@sentry/hub'; import { SpanContext, TransactionContext } from '@sentry/types'; import { logger } from '@sentry/utils'; +import { IdleTransaction } from './idletransaction'; import { Span } from './span'; import { Transaction } from './transaction'; @@ -22,8 +23,8 @@ function traceHeaders(this: Hub): { [key: string]: string } { /** * {@see Hub.startTransaction} */ -function startTransaction(this: Hub, context: TransactionContext): Transaction { - const transaction = new Transaction(context, this); +function startTransaction(this: Hub, context: TransactionContext, idleTimeout?: number): Transaction { + const transaction = idleTimeout ? new IdleTransaction(context, this, idleTimeout) : new Transaction(context, this); const client = this.getClient(); // Roll the dice for sampling transaction, all child spans inherit the sampling decision. diff --git a/packages/tracing/src/idletransaction.ts b/packages/tracing/src/idletransaction.ts new file mode 100644 index 000000000000..85a877ae5d47 --- /dev/null +++ b/packages/tracing/src/idletransaction.ts @@ -0,0 +1,272 @@ +// tslint:disable:max-classes-per-file +import { Hub } from '@sentry/hub'; +import { TransactionContext } from '@sentry/types'; +import { logger, timestampWithMs } from '@sentry/utils'; + +import { Span } from './span'; +import { SpanStatus } from './spanstatus'; +import { SpanRecorder, Transaction } from './transaction'; + +/** + * @inheritDoc + */ +export class IdleTransactionSpanRecorder extends SpanRecorder { + private readonly _pushActivity?: (id: string) => void; + private readonly _popActivity?: (id: string) => void; + public transactionSpanId: string = ''; + + public constructor( + maxlen?: number, + pushActivity?: (id: string) => void, + popActivity?: (id: string) => void, + transactionSpanId: string = '', + ) { + super(maxlen); + this._pushActivity = pushActivity; + this._popActivity = popActivity; + this.transactionSpanId = transactionSpanId; + } + + /** + * @inheritDoc + */ + public add(span: Span): void { + if (span.spanId !== this.transactionSpanId) { + span.finish = (endTimestamp?: number) => { + span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs(); + if (this._popActivity) { + this._popActivity(span.spanId); + } + }; + } + + super.add(span); + if (span.spanId !== this.transactionSpanId) { + if (span && !span.endTimestamp) { + if (this._pushActivity) { + this._pushActivity(span.spanId); + } + } + } + } +} + +/** + * @inheritDoc + */ +export class IdleTransaction extends Transaction { + /** + * Activities store a list of active spans + */ + public activities: Record = {}; + + private _heartbeatTimer: number = 0; + + private _prevHeartbeatString: string | undefined; + + private _heartbeatCounter: number = 1; + + // We should not use heartbeat if we finished a transaction + private _finished: boolean = false; + + private _finishCallback: Function | undefined = undefined; + + private readonly _idleTimeout: number = 500; + private readonly _idleHub?: Hub; + + public constructor(transactionContext: TransactionContext, hub?: Hub, idleTimeout: number = 500) { + super(transactionContext, hub); + this._idleTimeout = idleTimeout; + this._idleHub = hub; + + if (hub) { + // There should only be one active transaction on the scope + resetActiveTransaction(hub); + + // We set the transaction here on the scope so error events pick up the trace + // context and attach it to the error. + logger.log('Setting idle transaction on scope'); + hub.configureScope(scope => scope.setSpan(this)); + } + + // Start heartbeat so that transactions do not run forever.\ + logger.log('Starting heartbeat'); + this._pingHeartbeat(); + } + + /** + * Checks when entries of this.activities are not changing for 3 beats. + * If this occurs we finish the transaction. + */ + private _beat(): void { + clearTimeout(this._heartbeatTimer); + // We should not be running heartbeat if the idle transaction is finished. + if (this._finished) { + return; + } + const keys = Object.keys(this.activities); + const heartbeatString = keys.length ? keys.reduce((prev: string, current: string) => prev + current) : ''; + + if (heartbeatString === this._prevHeartbeatString) { + this._heartbeatCounter++; + } else { + this._heartbeatCounter = 1; + } + + this._prevHeartbeatString = heartbeatString; + + if (this._heartbeatCounter >= 3) { + logger.log( + `[Tracing] Transaction: ${ + SpanStatus.Cancelled + } -> Heartbeat safeguard kicked in since content hasn't changed for 3 beats`, + ); + this.setStatus(SpanStatus.DeadlineExceeded); + this.setTag('heartbeat', 'failed'); + this.finishIdleTransaction(timestampWithMs()); + } else { + this._pingHeartbeat(); + } + } + + /** + * Pings the heartbeat + */ + private _pingHeartbeat(): void { + logger.log(`ping Heartbeat -> current counter: ${this._heartbeatCounter}`); + this._heartbeatTimer = (setTimeout(() => { + this._beat(); + }, 5000) as any) as number; + } + + /** + * Finish the current active idle transaction + */ + public finishIdleTransaction(endTimestamp: number): void { + if (this.spanRecorder) { + logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); + + if (this._finishCallback) { + this._finishCallback(this); + } + + this.spanRecorder.spans = this.spanRecorder.spans.filter((span: 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(SpanStatus.Cancelled); + logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); + } + + const keepSpan = span.startTimestamp < endTimestamp; + if (!keepSpan) { + logger.log( + '[Tracing] discarding Span since it happened after Transaction was finished', + JSON.stringify(span, undefined, 2), + ); + } + return keepSpan; + }); + + logger.log('[Tracing] flushing IdleTransaction'); + this.finish(endTimestamp); + } else { + logger.log('[Tracing] No active IdleTransaction'); + } + } + + /** + * @inheritDoc + */ + public finish(endTimestamp?: number): string | undefined { + this._finished = true; + this.activities = {}; + resetActiveTransaction(this._idleHub); + return super.finish(endTimestamp); + } + + /** + * Start tracking a specific activity. + * @param spanId The span id that represents the activity + */ + private _pushActivity(spanId: string): void { + logger.log(`[Tracing] pushActivity: ${spanId}`); + this.activities[spanId] = true; + 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 + */ + private _popActivity(spanId: string): void { + if (this.activities[spanId]) { + logger.log(`[Tracing] popActivity ${spanId}`); + // tslint:disable-next-line: no-dynamic-delete + delete this.activities[spanId]; + logger.log('[Tracing] new activities count', Object.keys(this.activities).length); + } + + if (Object.keys(this.activities).length === 0) { + const timeout = this._idleTimeout; + // We need to add the timeout here to have the real endtimestamp of the transaction + // Remember timestampWithMs is in seconds, timeout is in ms + const end = timestampWithMs() + timeout / 1000; + + setTimeout(() => { + if (!this._finished) { + this.finishIdleTransaction(end); + } + }, timeout); + } + } + + /** + * 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. + */ + public beforeFinish(callback: (transactionSpan: IdleTransaction) => void): void { + this._finishCallback = callback; + } + + /** + * @inheritDoc + */ + public initSpanRecorder(maxlen?: number): void { + if (!this.spanRecorder) { + const pushActivity = (id: string) => { + if (id !== this.spanId) { + this._pushActivity(id); + } + }; + const popActivity = (id: string) => { + if (id !== this.spanId) { + this._popActivity(id); + } + }; + // tslint:disable-next-line: no-unbound-method + this.spanRecorder = new IdleTransactionSpanRecorder(maxlen, pushActivity, popActivity, this.spanId); + } + this.spanRecorder.add(this); + } +} + +/** + * Reset active transaction on scope + */ +function resetActiveTransaction(hub?: Hub): void { + if (hub) { + const scope = hub.getScope(); + if (scope) { + const transaction = scope.getTransaction(); + if (transaction) { + scope.setSpan(undefined); + } + } + } +} diff --git a/packages/tracing/src/index.bundle.ts b/packages/tracing/src/index.bundle.ts index 0d39253e7980..bab462006662 100644 --- a/packages/tracing/src/index.bundle.ts +++ b/packages/tracing/src/index.bundle.ts @@ -53,7 +53,7 @@ import { Integrations as BrowserIntegrations } from '@sentry/browser'; import { getGlobalObject } from '@sentry/utils'; import { addExtensionMethods } from './hubextensions'; -import * as ApmIntegrations from './integrations'; +import * as TracingIntegrations from './integrations'; export { Span, TRACEPARENT_REGEXP } from './span'; @@ -70,7 +70,7 @@ if (_window.Sentry && _window.Sentry.Integrations) { const INTEGRATIONS = { ...windowIntegrations, ...BrowserIntegrations, - Tracing: ApmIntegrations.Tracing, + Tracing: TracingIntegrations.BrowserTracing, }; export { INTEGRATIONS as Integrations }; diff --git a/packages/tracing/src/index.ts b/packages/tracing/src/index.ts index 9f59e3515f40..6381b2bc0bac 100644 --- a/packages/tracing/src/index.ts +++ b/packages/tracing/src/index.ts @@ -1,7 +1,7 @@ import { addExtensionMethods } from './hubextensions'; -import * as ApmIntegrations from './integrations'; +import * as TracingIntegrations from './integrations'; -export { ApmIntegrations as Integrations }; +export { TracingIntegrations as Integrations }; export { Span, TRACEPARENT_REGEXP } from './span'; export { Transaction } from './transaction'; diff --git a/packages/tracing/src/integrations/browsertracing.ts b/packages/tracing/src/integrations/browsertracing.ts new file mode 100644 index 000000000000..f48e81bc1e0f --- /dev/null +++ b/packages/tracing/src/integrations/browsertracing.ts @@ -0,0 +1,275 @@ +import { Hub } from '@sentry/hub'; +import { Event, EventProcessor, Integration, Severity, TransactionContext } from '@sentry/types'; +import { logger, safeJoin } from '@sentry/utils'; + +import { IdleTransaction } from '../idletransaction'; +import { Span as SpanClass } from '../span'; +import { SpanStatus } from '../spanstatus'; + +import { registerBackgroundTabDetection } from './tracing/backgroundtab'; +import { registerErrorHandlers } from './tracing/errors'; +import { Metrics } from './tracing/performance'; +import { + defaultRequestInstrumentionOptions, + RequestInstrumentationClass, + RequestInstrumentationOptions, + RequestTracing, +} from './tracing/request'; +import { + defaultRoutingInstrumentationOptions, + RouterTracing, + RoutingInstrumentationClass, + RoutingInstrumentationOptions, +} from './tracing/router'; + +/** + * Options for Browser Tracing integration + */ +export type BrowserTracingOptions = { + /** + * The maximum duration of a transaction before it will be marked as "deadline_exceeded". + * If you never want to mark a transaction set it to 0. + * Time is in seconds. + * + * Default: 600 + */ + maxTransactionDuration: number; + + /** + * Flag Transactions where tabs moved to background with "cancelled". Browser background tab timing is + * not suited towards doing precise measurements of operations. Background transaction can mess up your + * statistics in non deterministic ways that's why we by default recommend leaving this opition enabled. + * + * Default: true + */ + markBackgroundTransactions: boolean; + + /** + * This is only if you want to debug in prod. + * writeAsBreadcrumbs: Instead of having console.log statements we log messages to breadcrumbs + * so you can investigate whats happening in production with your users to figure why things might not appear the + * way you expect them to. + * + * You shouldn't care about this. + * + * Default: { + * writeAsBreadcrumbs: false; + * } + */ + debug: { + writeAsBreadcrumbs: boolean; + }; + + routerTracing: RoutingInstrumentationClass; + + requestTracing: RequestInstrumentationClass; +} & RoutingInstrumentationOptions & + RequestInstrumentationOptions; + +export class BrowserTracing implements Integration { + /** + * @inheritDoc + */ + public static id: string = 'BrowserTracing'; + + /** + * @inheritDoc + */ + public name: string = BrowserTracing.id; + + /** + * Browser Tracing integration options + */ + public static options: BrowserTracingOptions; + + private readonly _emitOptionsWarning: boolean = false; + + /** + * Returns current hub. + */ + private static _getCurrentHub?: () => Hub; + + public constructor(_options?: Partial) { + Metrics.init(); + + const defaults = { + debug: { + writeAsBreadcrumbs: false, + }, + markBackgroundTransactions: true, + maxTransactionDuration: 600, + requestTracing: RequestTracing, + routerTracing: RouterTracing, + }; + + // NOTE: Logger doesn't work in contructors, as it's initialized after integrations instances + if (!_options || !Array.isArray(_options.tracingOrigins) || _options.tracingOrigins.length === 0) { + this._emitOptionsWarning = true; + } + + BrowserTracing.options = { + ...defaultRoutingInstrumentationOptions, + ...defaultRequestInstrumentionOptions, + ...defaults, + ..._options, + }; + } + + /** + * @inheritDoc + */ + public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { + BrowserTracing._getCurrentHub = getCurrentHub; + + if (this._emitOptionsWarning) { + logger.warn( + '[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.', + ); + logger.warn( + `[Tracing] We added a reasonable default for you: ${defaultRequestInstrumentionOptions.tracingOrigins}`, + ); + } + + const hub = getCurrentHub(); + + // Track pageload/navigation transactions + BrowserTracing._initRoutingInstrumentation(hub); + // Track XHR and Fetch requests + BrowserTracing._initRequestInstrumentation(); + // Set status of transactions on error + registerErrorHandlers(); + // Finish transactions if document is no longer visible + if (BrowserTracing.options.markBackgroundTransactions) { + registerBackgroundTabDetection(); + } + + // This EventProcessor makes sure that the transaction is not longer than maxTransactionDuration + addGlobalEventProcessor((event: Event) => { + const self = getCurrentHub().getIntegration(BrowserTracing); + if (!self) { + return event; + } + + const isOutdatedTransaction = + event.timestamp && + event.start_timestamp && + (event.timestamp - event.start_timestamp > BrowserTracing.options.maxTransactionDuration || + event.timestamp - event.start_timestamp < 0); + + if ( + BrowserTracing.options.maxTransactionDuration !== 0 && + event.type === 'transaction' && + isOutdatedTransaction + ) { + BrowserTracing.log(`[Tracing] Transaction: ${SpanStatus.Cancelled} since it maxed out maxTransactionDuration`); + if (event.contexts && event.contexts.trace) { + event.contexts.trace = { + ...event.contexts.trace, + status: SpanStatus.DeadlineExceeded, + }; + event.tags = { + ...event.tags, + maxTransactionDurationExceeded: 'true', + }; + } + } + + return event; + }); + } + + /** + * Initialize routing instrumentation + */ + private static _initRoutingInstrumentation(hub: Hub): void { + BrowserTracing.log('Set up Routing instrumentation'); + const { + beforeNavigate, + idleTimeout, + startTransactionOnLocationChange, + startTransactionOnPageLoad, + } = BrowserTracing.options; + + const routerTracing = new BrowserTracing.options.routerTracing({ + beforeNavigate, + idleTimeout, + startTransactionOnLocationChange, + startTransactionOnPageLoad, + }); + + const transactionContext = BrowserTracing._getTransactionContext(); + + const beforeFinish = (transaction: IdleTransaction) => { + Metrics.addPerformanceEntries(transaction); + }; + + routerTracing.init(hub, beforeFinish, transactionContext); + } + + /** + * Initialize request instrumentation + */ + private static _initRequestInstrumentation(): void { + const { shouldCreateSpanForRequest, traceFetch, traceXHR, tracingOrigins } = BrowserTracing.options; + + const requestTracing = new BrowserTracing.options.requestTracing({ + shouldCreateSpanForRequest, + traceFetch, + traceXHR, + tracingOrigins, + }); + + requestTracing.init(); + } + + /** + * Gets transaction context from a sentry-trace meta. + */ + private static _getTransactionContext(): Partial { + const header = getMeta('sentry-trace'); + if (header) { + const span = SpanClass.fromTraceparent(header); + if (span) { + BrowserTracing.log( + `[Tracing] found 'sentry-meta' '' continuing trace with: trace_id: ${span.traceId} span_id: ${ + span.parentSpanId + }`, + ); + + return { + parentSpanId: span.parentSpanId, + sampled: span.sampled, + traceId: span.traceId, + }; + } + } + + return {}; + } + + /** + * Uses logger.log to log things in the SDK or as breadcrumbs if defined in options + */ + public static log(...args: any[]): void { + if (BrowserTracing.options && BrowserTracing.options.debug && BrowserTracing.options.debug.writeAsBreadcrumbs) { + const _getCurrentHub = BrowserTracing._getCurrentHub; + if (_getCurrentHub) { + _getCurrentHub().addBreadcrumb({ + category: 'tracing', + level: Severity.Debug, + message: safeJoin(args, ' '), + type: 'debug', + }); + } + } + logger.log(...args); + } +} + +/** + * Returns the value of a meta tag + */ +function getMeta(metaName: string): string | null { + const el = document.querySelector(`meta[name=${metaName}]`); + return el ? el.getAttribute('content') : null; +} diff --git a/packages/tracing/src/integrations/index.ts b/packages/tracing/src/integrations/index.ts index 8833c8cd301c..83967ef8309b 100644 --- a/packages/tracing/src/integrations/index.ts +++ b/packages/tracing/src/integrations/index.ts @@ -1,2 +1,2 @@ export { Express } from './express'; -export { Tracing } from './tracing'; +export { BrowserTracing } from './browsertracing'; diff --git a/packages/tracing/src/integrations/tracing.ts b/packages/tracing/src/integrations/tracing.ts deleted file mode 100644 index 59451647569f..000000000000 --- a/packages/tracing/src/integrations/tracing.ts +++ /dev/null @@ -1,1058 +0,0 @@ -// tslint:disable: max-file-line-count -import { Hub } from '@sentry/hub'; -import { Event, EventProcessor, Integration, Severity, Span, SpanContext, TransactionContext } from '@sentry/types'; -import { - addInstrumentationHandler, - getGlobalObject, - isInstanceOf, - isMatchingPattern, - logger, - safeJoin, - supportsNativeFetch, - timestampWithMs, -} from '@sentry/utils'; - -import { Span as SpanClass } from '../span'; -import { SpanStatus } from '../spanstatus'; -import { Transaction } from '../transaction'; - -import { Location } from './types'; - -/** - * Options for Tracing integration - */ -export interface TracingOptions { - /** - * List of strings / regex where the integration should create Spans out of. Additionally this will be used - * to define which outgoing requests the `sentry-trace` header will be attached to. - * - * Default: ['localhost', /^\//] - */ - tracingOrigins: Array; - /** - * Flag to disable patching all together for fetch requests. - * - * Default: true - */ - traceFetch: boolean; - /** - * Flag to disable patching all together for xhr requests. - * - * Default: true - */ - traceXHR: boolean; - /** - * This function will be called before creating a span for a request with the given url. - * Return false if you don't want a span for the given url. - * - * By default it uses the `tracingOrigins` options as a url match. - */ - shouldCreateSpanForRequest(url: string): boolean; - /** - * The time to wait in ms until the transaction will be finished. The transaction will use the end timestamp of - * the last finished span as the endtime for the transaction. - * Time is in ms. - * - * Default: 500 - */ - idleTimeout: number; - - /** - * Flag to enable/disable creation of `navigation` transaction on history changes. Useful for react applications with - * a router. - * - * Default: true - */ - startTransactionOnLocationChange: boolean; - - /** - * Flag to enable/disable creation of `pageload` transaction on first pageload. - * - * Default: true - */ - startTransactionOnPageLoad: boolean; - - /** - * The maximum duration of a transaction before it will be marked as "deadline_exceeded". - * If you never want to mark a transaction set it to 0. - * Time is in seconds. - * - * Default: 600 - */ - maxTransactionDuration: number; - - /** - * Flag Transactions where tabs moved to background with "cancelled". Browser background tab timing is - * not suited towards doing precise measurements of operations. Background transaction can mess up your - * statistics in non deterministic ways that's why we by default recommend leaving this opition enabled. - * - * Default: true - */ - markBackgroundTransactions: boolean; - - /** - * This is only if you want to debug in prod. - * writeAsBreadcrumbs: Instead of having console.log statements we log messages to breadcrumbs - * so you can investigate whats happening in production with your users to figure why things might not appear the - * way you expect them to. - * - * spanDebugTimingInfo: Add timing info to spans at the point where we create them to figure out browser timing - * issues. - * - * You shouldn't care about this. - * - * Default: { - * writeAsBreadcrumbs: false; - * spanDebugTimingInfo: false; - * } - */ - debug: { - writeAsBreadcrumbs: boolean; - spanDebugTimingInfo: boolean; - }; - - /** - * beforeNavigate is called before a pageload/navigation transaction is created and allows for users - * to set a custom navigation transaction name based on the current `window.location`. Defaults to returning - * `window.location.pathname`. - * - * @param location the current location before navigation span is created - */ - beforeNavigate(location: Location): string; -} - -/** JSDoc */ -interface Activity { - name: string; - span?: Span; -} - -const global = getGlobalObject(); -const defaultTracingOrigins = ['localhost', /^\//]; - -/** - * Tracing Integration - */ -export class Tracing implements Integration { - /** - * @inheritDoc - */ - public name: string = Tracing.id; - - /** - * @inheritDoc - */ - public static id: string = 'Tracing'; - - /** JSDoc */ - public static options: TracingOptions; - - /** - * Returns current hub. - */ - private static _getCurrentHub?: () => Hub; - - private static _activeTransaction?: Transaction; - - private static _currentIndex: number = 1; - - public static _activities: { [key: number]: Activity } = {}; - - private readonly _emitOptionsWarning: boolean = false; - - private static _performanceCursor: number = 0; - - private static _heartbeatTimer: number = 0; - - private static _prevHeartbeatString: string | undefined; - - private static _heartbeatCounter: number = 0; - - /** Holds the latest LargestContentfulPaint value (it changes during page load). */ - private static _lcp?: { [key: string]: any }; - - /** Force any pending LargestContentfulPaint records to be dispatched. */ - private static _forceLCP = () => { - /* No-op, replaced later if LCP API is available. */ - }; - - /** - * Constructor for Tracing - * - * @param _options TracingOptions - */ - public constructor(_options?: Partial) { - if (global.performance) { - if (global.performance.mark) { - global.performance.mark('sentry-tracing-init'); - } - Tracing._trackLCP(); - } - const defaults = { - beforeNavigate(location: Location): string { - return location.pathname; - }, - debug: { - spanDebugTimingInfo: false, - writeAsBreadcrumbs: false, - }, - idleTimeout: 500, - markBackgroundTransactions: true, - maxTransactionDuration: 600, - shouldCreateSpanForRequest(url: string): boolean { - const origins = (_options && _options.tracingOrigins) || defaultTracingOrigins; - return ( - origins.some((origin: string | RegExp) => isMatchingPattern(url, origin)) && - !isMatchingPattern(url, 'sentry_key') - ); - }, - startTransactionOnLocationChange: true, - startTransactionOnPageLoad: true, - traceFetch: true, - traceXHR: true, - tracingOrigins: defaultTracingOrigins, - }; - // NOTE: Logger doesn't work in contructors, as it's initialized after integrations instances - if (!_options || !Array.isArray(_options.tracingOrigins) || _options.tracingOrigins.length === 0) { - this._emitOptionsWarning = true; - } - Tracing.options = { - ...defaults, - ..._options, - }; - } - - /** - * @inheritDoc - */ - public setupOnce(addGlobalEventProcessor: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { - Tracing._getCurrentHub = getCurrentHub; - - if (this._emitOptionsWarning) { - logger.warn( - '[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.', - ); - logger.warn(`[Tracing] We added a reasonable default for you: ${defaultTracingOrigins}`); - } - - // Starting pageload transaction - if (global.location && Tracing.options && Tracing.options.startTransactionOnPageLoad) { - Tracing.startIdleTransaction({ - name: Tracing.options.beforeNavigate(window.location), - op: 'pageload', - }); - } - - this._setupXHRTracing(); - - this._setupFetchTracing(); - - this._setupHistory(); - - this._setupErrorHandling(); - - this._setupBackgroundTabDetection(); - - Tracing._pingHeartbeat(); - - // This EventProcessor makes sure that the transaction is not longer than maxTransactionDuration - addGlobalEventProcessor((event: Event) => { - const self = getCurrentHub().getIntegration(Tracing); - if (!self) { - return event; - } - - const isOutdatedTransaction = - event.timestamp && - event.start_timestamp && - (event.timestamp - event.start_timestamp > Tracing.options.maxTransactionDuration || - event.timestamp - event.start_timestamp < 0); - - if (Tracing.options.maxTransactionDuration !== 0 && event.type === 'transaction' && isOutdatedTransaction) { - Tracing._log(`[Tracing] Transaction: ${SpanStatus.Cancelled} since it maxed out maxTransactionDuration`); - if (event.contexts && event.contexts.trace) { - event.contexts.trace = { - ...event.contexts.trace, - status: SpanStatus.DeadlineExceeded, - }; - event.tags = { - ...event.tags, - maxTransactionDurationExceeded: 'true', - }; - } - } - - return event; - }); - } - - /** - * Returns a new Transaction either continued from sentry-trace meta or a new one - */ - private static _getNewTransaction(hub: Hub, transactionContext: TransactionContext): Transaction { - let traceId; - let parentSpanId; - let sampled; - - const header = Tracing._getMeta('sentry-trace'); - if (header) { - const span = SpanClass.fromTraceparent(header); - if (span) { - traceId = span.traceId; - parentSpanId = span.parentSpanId; - sampled = span.sampled; - Tracing._log( - `[Tracing] found 'sentry-meta' '' continuing trace with: trace_id: ${traceId} span_id: ${parentSpanId}`, - ); - } - } - - return hub.startTransaction({ - parentSpanId, - sampled, - traceId, - trimEnd: true, - ...transactionContext, - }) as Transaction; - } - - /** - * Returns the value of a meta tag - */ - private static _getMeta(metaName: string): string | null { - const el = document.querySelector(`meta[name=${metaName}]`); - return el ? el.getAttribute('content') : null; - } - - /** - * Pings the heartbeat - */ - private static _pingHeartbeat(): void { - Tracing._heartbeatTimer = (setTimeout(() => { - Tracing._beat(); - }, 5000) as any) as number; - } - - /** - * Checks when entries of Tracing._activities are not changing for 3 beats. If this occurs we finish the transaction - * - */ - private static _beat(): void { - clearTimeout(Tracing._heartbeatTimer); - const keys = Object.keys(Tracing._activities); - if (keys.length) { - const heartbeatString = keys.reduce((prev: string, current: string) => prev + current); - if (heartbeatString === Tracing._prevHeartbeatString) { - Tracing._heartbeatCounter++; - } else { - Tracing._heartbeatCounter = 0; - } - if (Tracing._heartbeatCounter >= 3) { - if (Tracing._activeTransaction) { - Tracing._log( - `[Tracing] Transaction: ${ - SpanStatus.Cancelled - } -> Heartbeat safeguard kicked in since content hasn't changed for 3 beats`, - ); - Tracing._activeTransaction.setStatus(SpanStatus.DeadlineExceeded); - Tracing._activeTransaction.setTag('heartbeat', 'failed'); - Tracing.finishIdleTransaction(timestampWithMs()); - } - } - Tracing._prevHeartbeatString = heartbeatString; - } - Tracing._pingHeartbeat(); - } - - /** - * Discards active transactions if tab moves to background - */ - private _setupBackgroundTabDetection(): void { - if (Tracing.options && Tracing.options.markBackgroundTransactions && global.document) { - document.addEventListener('visibilitychange', () => { - if (document.hidden && Tracing._activeTransaction) { - Tracing._log(`[Tracing] Transaction: ${SpanStatus.Cancelled} -> since tab moved to the background`); - Tracing._activeTransaction.setStatus(SpanStatus.Cancelled); - Tracing._activeTransaction.setTag('visibilitychange', 'document.hidden'); - Tracing.finishIdleTransaction(timestampWithMs()); - } - }); - } - } - - /** - * Unsets the current active transaction + activities - */ - private static _resetActiveTransaction(): void { - // We want to clean up after ourselves - // If there is still the active transaction on the scope we remove it - const _getCurrentHub = Tracing._getCurrentHub; - if (_getCurrentHub) { - const hub = _getCurrentHub(); - const scope = hub.getScope(); - if (scope) { - if (scope.getSpan() === Tracing._activeTransaction) { - scope.setSpan(undefined); - } - } - } - // ------------------------------------------------------------------ - Tracing._activeTransaction = undefined; - Tracing._activities = {}; - } - - /** - * Registers to History API to detect navigation changes - */ - private _setupHistory(): void { - if (Tracing.options.startTransactionOnLocationChange) { - addInstrumentationHandler({ - callback: historyCallback, - type: 'history', - }); - } - } - - /** - * Attaches to fetch to add sentry-trace header + creating spans - */ - private _setupFetchTracing(): void { - if (Tracing.options.traceFetch && supportsNativeFetch()) { - addInstrumentationHandler({ - callback: fetchCallback, - type: 'fetch', - }); - } - } - - /** - * Attaches to XHR to add sentry-trace header + creating spans - */ - private _setupXHRTracing(): void { - if (Tracing.options.traceXHR) { - addInstrumentationHandler({ - callback: xhrCallback, - type: 'xhr', - }); - } - } - - /** - * Configures global error listeners - */ - private _setupErrorHandling(): void { - // tslint:disable-next-line: completed-docs - function errorCallback(): void { - if (Tracing._activeTransaction) { - /** - * If an error or unhandled promise occurs, we mark the active transaction as failed - */ - Tracing._log(`[Tracing] Transaction: ${SpanStatus.InternalError} -> Global error occured`); - Tracing._activeTransaction.setStatus(SpanStatus.InternalError); - } - } - addInstrumentationHandler({ - callback: errorCallback, - type: 'error', - }); - addInstrumentationHandler({ - callback: errorCallback, - type: 'unhandledrejection', - }); - } - - /** - * Uses logger.log to log things in the SDK or as breadcrumbs if defined in options - */ - private static _log(...args: any[]): void { - if (Tracing.options && Tracing.options.debug && Tracing.options.debug.writeAsBreadcrumbs) { - const _getCurrentHub = Tracing._getCurrentHub; - if (_getCurrentHub) { - _getCurrentHub().addBreadcrumb({ - category: 'tracing', - level: Severity.Debug, - message: safeJoin(args, ' '), - type: 'debug', - }); - } - } - logger.log(...args); - } - - /** - * Starts a Transaction waiting for activity idle to finish - */ - public static startIdleTransaction(transactionContext: TransactionContext): Transaction | undefined { - Tracing._log('[Tracing] startIdleTransaction'); - - const _getCurrentHub = Tracing._getCurrentHub; - if (!_getCurrentHub) { - return undefined; - } - - const hub = _getCurrentHub(); - if (!hub) { - return undefined; - } - - Tracing._activeTransaction = Tracing._getNewTransaction(hub, transactionContext); - - // We set the transaction here on the scope so error events pick up the trace context and attach it to the error - hub.configureScope(scope => scope.setSpan(Tracing._activeTransaction)); - - // The reason we do this here is because of cached responses - // If we start and transaction without an activity it would never finish since there is no activity - const id = Tracing.pushActivity('idleTransactionStarted'); - setTimeout(() => { - Tracing.popActivity(id); - }, (Tracing.options && Tracing.options.idleTimeout) || 100); - - return Tracing._activeTransaction; - } - - /** - * Finishes the current active transaction - */ - public static finishIdleTransaction(endTimestamp: number): void { - const active = Tracing._activeTransaction; - if (active) { - Tracing._log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString()); - Tracing._addPerformanceEntries(active); - - if (active.spanRecorder) { - active.spanRecorder.spans = active.spanRecorder.spans.filter((span: Span) => { - // If we are dealing with the transaction itself, we just return it - if (span.spanId === active.spanId) { - return span; - } - - // We cancel all pending spans with status "cancelled" to indicate the idle transaction was finished early - if (!span.endTimestamp) { - span.endTimestamp = endTimestamp; - span.setStatus(SpanStatus.Cancelled); - Tracing._log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); - } - - // We remove all spans that happend after the end of the transaction - // This is here to prevent super long transactions and timing issues - const keepSpan = span.startTimestamp < endTimestamp; - if (!keepSpan) { - Tracing._log( - '[Tracing] discarding Span since it happened after Transaction was finished', - JSON.stringify(span, undefined, 2), - ); - } - return keepSpan; - }); - } - - Tracing._log('[Tracing] flushing IdleTransaction'); - active.finish(); - Tracing._resetActiveTransaction(); - } else { - Tracing._log('[Tracing] No active IdleTransaction'); - } - } - - /** - * This uses `performance.getEntries()` to add additional spans to the active transaction. - * Also, we update our timings since we consider the timings in this API to be more correct than our manual - * measurements. - * - * @param transactionSpan The transaction span - */ - private static _addPerformanceEntries(transactionSpan: SpanClass): void { - if (!global.performance || !global.performance.getEntries) { - // Gatekeeper if performance API not available - return; - } - - Tracing._log('[Tracing] Adding & adjusting spans using Performance API'); - - // FIXME: depending on the 'op' directly is brittle. - if (transactionSpan.op === 'pageload') { - // Force any pending records to be dispatched. - Tracing._forceLCP(); - if (Tracing._lcp) { - // Set the last observed LCP score. - transactionSpan.setData('_sentry_web_vitals', { LCP: Tracing._lcp }); - } - } - - const timeOrigin = Tracing._msToSec(performance.timeOrigin); - - // tslint:disable-next-line: completed-docs - function addPerformanceNavigationTiming(parent: Span, entry: { [key: string]: number }, event: string): void { - parent.startChild({ - description: event, - endTimestamp: timeOrigin + Tracing._msToSec(entry[`${event}End`]), - op: 'browser', - startTimestamp: timeOrigin + Tracing._msToSec(entry[`${event}Start`]), - }); - } - - // tslint:disable-next-line: completed-docs - function addRequest(parent: Span, entry: { [key: string]: number }): void { - parent.startChild({ - description: 'request', - endTimestamp: timeOrigin + Tracing._msToSec(entry.responseEnd), - op: 'browser', - startTimestamp: timeOrigin + Tracing._msToSec(entry.requestStart), - }); - - parent.startChild({ - description: 'response', - endTimestamp: timeOrigin + Tracing._msToSec(entry.responseEnd), - op: 'browser', - startTimestamp: timeOrigin + Tracing._msToSec(entry.responseStart), - }); - } - - let entryScriptSrc: string | undefined; - - if (global.document) { - // tslint:disable-next-line: prefer-for-of - for (let i = 0; i < document.scripts.length; i++) { - // We go through all scripts on the page and look for 'data-entry' - // We remember the name and measure the time between this script finished loading and - // our mark 'sentry-tracing-init' - if (document.scripts[i].dataset.entry === 'true') { - entryScriptSrc = document.scripts[i].src; - break; - } - } - } - - let entryScriptStartEndTime: number | undefined; - let tracingInitMarkStartTime: number | undefined; - - // tslint:disable: no-unsafe-any - performance - .getEntries() - .slice(Tracing._performanceCursor) - .forEach((entry: any) => { - const startTime = Tracing._msToSec(entry.startTime as number); - const duration = Tracing._msToSec(entry.duration as number); - - if (transactionSpan.op === 'navigation' && timeOrigin + startTime < transactionSpan.startTimestamp) { - return; - } - - switch (entry.entryType) { - case 'navigation': - addPerformanceNavigationTiming(transactionSpan, entry, 'unloadEvent'); - addPerformanceNavigationTiming(transactionSpan, entry, 'domContentLoadedEvent'); - addPerformanceNavigationTiming(transactionSpan, entry, 'loadEvent'); - addPerformanceNavigationTiming(transactionSpan, entry, 'connect'); - addPerformanceNavigationTiming(transactionSpan, entry, 'domainLookup'); - addRequest(transactionSpan, entry); - break; - case 'mark': - case 'paint': - case 'measure': - const mark = transactionSpan.startChild({ - description: entry.name, - op: entry.entryType, - }); - mark.startTimestamp = timeOrigin + startTime; - mark.endTimestamp = mark.startTimestamp + duration; - if (tracingInitMarkStartTime === undefined && entry.name === 'sentry-tracing-init') { - tracingInitMarkStartTime = mark.startTimestamp; - } - break; - case 'resource': - const resourceName = entry.name.replace(window.location.origin, ''); - if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') { - // We need to update existing spans with new timing info - if (transactionSpan.spanRecorder) { - transactionSpan.spanRecorder.spans.map((finishedSpan: Span) => { - if (finishedSpan.description && finishedSpan.description.indexOf(resourceName) !== -1) { - finishedSpan.startTimestamp = timeOrigin + startTime; - finishedSpan.endTimestamp = finishedSpan.startTimestamp + duration; - } - }); - } - } else { - const resource = transactionSpan.startChild({ - description: `${entry.initiatorType} ${resourceName}`, - op: `resource`, - }); - resource.startTimestamp = timeOrigin + startTime; - resource.endTimestamp = resource.startTimestamp + duration; - // We remember the entry script end time to calculate the difference to the first init mark - if (entryScriptStartEndTime === undefined && (entryScriptSrc || '').indexOf(resourceName) > -1) { - entryScriptStartEndTime = resource.endTimestamp; - } - } - break; - default: - // Ignore other entry types. - } - }); - - if (entryScriptStartEndTime !== undefined && tracingInitMarkStartTime !== undefined) { - transactionSpan.startChild({ - description: 'evaluation', - endTimestamp: tracingInitMarkStartTime, - op: `script`, - startTimestamp: entryScriptStartEndTime, - }); - } - - Tracing._performanceCursor = Math.max(performance.getEntries().length - 1, 0); - // tslint:enable: no-unsafe-any - } - - /** - * Starts tracking the Largest Contentful Paint on the current page. - */ - private static _trackLCP(): void { - // Based on reference implementation from https://web.dev/lcp/#measure-lcp-in-javascript. - - // Use a try/catch instead of feature detecting `largest-contentful-paint` - // support, since some browsers throw when using the new `type` option. - // https://bugs.webkit.org/show_bug.cgi?id=209216 - try { - // Keep track of whether (and when) the page was first hidden, see: - // https://github.com/w3c/page-visibility/issues/29 - // NOTE: ideally this check would be performed in the document - // to avoid cases where the visibility state changes before this code runs. - let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity; - document.addEventListener( - 'visibilitychange', - event => { - firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp); - }, - { once: true }, - ); - - const updateLCP = (entry: PerformanceEntry) => { - // Only include an LCP entry if the page wasn't hidden prior to - // the entry being dispatched. This typically happens when a page is - // loaded in a background tab. - if (entry.startTime < firstHiddenTime) { - // NOTE: the `startTime` value is a getter that returns the entry's - // `renderTime` value, if available, or its `loadTime` value otherwise. - // The `renderTime` value may not be available if the element is an image - // that's loaded cross-origin without the `Timing-Allow-Origin` header. - Tracing._lcp = { - // @ts-ignore - ...(entry.id && { elementId: entry.id }), - // @ts-ignore - ...(entry.size && { elementSize: entry.size }), - value: entry.startTime, - }; - } - }; - - // Create a PerformanceObserver that calls `updateLCP` for each entry. - const po = new PerformanceObserver(entryList => { - entryList.getEntries().forEach(updateLCP); - }); - - // Observe entries of type `largest-contentful-paint`, including buffered entries, - // i.e. entries that occurred before calling `observe()` below. - po.observe({ - buffered: true, - // @ts-ignore - type: 'largest-contentful-paint', - }); - - Tracing._forceLCP = () => { - po.takeRecords().forEach(updateLCP); - }; - } catch (e) { - // Do nothing if the browser doesn't support this API. - } - } - - /** - * Sets the status of the current active transaction (if there is one) - */ - public static setTransactionStatus(status: SpanStatus): void { - const active = Tracing._activeTransaction; - if (active) { - Tracing._log('[Tracing] setTransactionStatus', status); - active.setStatus(status); - } - } - - /** - * Returns the current active idle transaction if there is one - */ - public static getTransaction(): Transaction | undefined { - return Tracing._activeTransaction; - } - - /** - * Converts from milliseconds to seconds - * @param time time in ms - */ - private static _msToSec(time: number): number { - return time / 1000; - } - - /** - * Adds debug data to the span - */ - private static _addSpanDebugInfo(span: Span): void { - // tslint:disable: no-unsafe-any - const debugData: any = {}; - if (global.performance) { - debugData.performance = true; - debugData['performance.timeOrigin'] = global.performance.timeOrigin; - debugData['performance.now'] = global.performance.now(); - // tslint:disable-next-line: deprecation - if (global.performance.timing) { - // tslint:disable-next-line: deprecation - debugData['performance.timing.navigationStart'] = performance.timing.navigationStart; - } - } else { - debugData.performance = false; - } - debugData['Date.now()'] = Date.now(); - span.setData('sentry_debug', debugData); - // tslint:enable: no-unsafe-any - } - - /** - * Starts tracking for a specifc activity - * - * @param name Name of the activity, can be any string (Only used internally to identify the activity) - * @param spanContext If provided a Span with the SpanContext will be created. - * @param options _autoPopAfter_ | Time in ms, if provided the activity will be popped automatically after this timeout. This can be helpful in cases where you cannot gurantee your application knows the state and calls `popActivity` for sure. - */ - public static pushActivity( - name: string, - spanContext?: SpanContext, - options?: { - autoPopAfter?: number; - }, - ): number { - const activeTransaction = Tracing._activeTransaction; - - if (!activeTransaction) { - Tracing._log(`[Tracing] Not pushing activity ${name} since there is no active transaction`); - return 0; - } - - const _getCurrentHub = Tracing._getCurrentHub; - if (spanContext && _getCurrentHub) { - const hub = _getCurrentHub(); - if (hub) { - const span = activeTransaction.startChild(spanContext); - Tracing._activities[Tracing._currentIndex] = { - name, - span, - }; - } - } else { - Tracing._activities[Tracing._currentIndex] = { - name, - }; - } - - Tracing._log(`[Tracing] pushActivity: ${name}#${Tracing._currentIndex}`); - Tracing._log('[Tracing] activies count', Object.keys(Tracing._activities).length); - if (options && typeof options.autoPopAfter === 'number') { - Tracing._log(`[Tracing] auto pop of: ${name}#${Tracing._currentIndex} in ${options.autoPopAfter}ms`); - const index = Tracing._currentIndex; - setTimeout(() => { - Tracing.popActivity(index, { - autoPop: true, - status: SpanStatus.DeadlineExceeded, - }); - }, options.autoPopAfter); - } - return Tracing._currentIndex++; - } - - /** - * Removes activity and finishes the span in case there is one - * @param id the id of the activity being removed - * @param spanData span data that can be updated - * - */ - public static popActivity(id: number, spanData?: { [key: string]: any }): void { - // The !id is on purpose to also fail with 0 - // Since 0 is returned by push activity in case there is no active transaction - if (!id) { - return; - } - - const activity = Tracing._activities[id]; - - if (activity) { - Tracing._log(`[Tracing] popActivity ${activity.name}#${id}`); - const span = activity.span; - if (span) { - if (spanData) { - Object.keys(spanData).forEach((key: string) => { - span.setData(key, spanData[key]); - if (key === 'status_code') { - span.setHttpStatus(spanData[key] as number); - } - if (key === 'status') { - span.setStatus(spanData[key] as SpanStatus); - } - }); - } - if (Tracing.options && Tracing.options.debug && Tracing.options.debug.spanDebugTimingInfo) { - Tracing._addSpanDebugInfo(span); - } - span.finish(); - } - // tslint:disable-next-line: no-dynamic-delete - delete Tracing._activities[id]; - } - - const count = Object.keys(Tracing._activities).length; - - Tracing._log('[Tracing] activies count', count); - - if (count === 0 && Tracing._activeTransaction) { - const timeout = Tracing.options && Tracing.options.idleTimeout; - Tracing._log(`[Tracing] Flushing Transaction in ${timeout}ms`); - // We need to add the timeout here to have the real endtimestamp of the transaction - // Remeber timestampWithMs is in seconds, timeout is in ms - const end = timestampWithMs() + timeout / 1000; - setTimeout(() => { - Tracing.finishIdleTransaction(end); - }, timeout); - } - } - - /** - * Get span based on activity id - */ - public static getActivitySpan(id: number): Span | undefined { - if (!id) { - return undefined; - } - const activity = Tracing._activities[id]; - if (activity) { - return activity.span; - } - return undefined; - } -} - -/** - * Creates breadcrumbs from XHR API calls - */ -function xhrCallback(handlerData: { [key: string]: any }): void { - if (!Tracing.options.traceXHR) { - return; - } - - // tslint:disable-next-line: no-unsafe-any - if (!handlerData || !handlerData.xhr || !handlerData.xhr.__sentry_xhr__) { - return; - } - - // tslint:disable: no-unsafe-any - const xhr = handlerData.xhr.__sentry_xhr__; - - if (!Tracing.options.shouldCreateSpanForRequest(xhr.url)) { - return; - } - - // We only capture complete, non-sentry requests - if (handlerData.xhr.__sentry_own_request__) { - return; - } - - if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_activity_id__) { - Tracing.popActivity(handlerData.xhr.__sentry_xhr_activity_id__, handlerData.xhr.__sentry_xhr__); - return; - } - - handlerData.xhr.__sentry_xhr_activity_id__ = Tracing.pushActivity('xhr', { - data: { - ...xhr.data, - type: 'xhr', - }, - description: `${xhr.method} ${xhr.url}`, - op: 'http', - }); - - // Adding the trace header to the span - const activity = Tracing._activities[handlerData.xhr.__sentry_xhr_activity_id__]; - if (activity) { - const span = activity.span; - if (span && handlerData.xhr.setRequestHeader) { - try { - handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent()); - } catch (_) { - // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. - } - } - } - // tslint:enable: no-unsafe-any -} - -/** - * Creates breadcrumbs from fetch API calls - */ -function fetchCallback(handlerData: { [key: string]: any }): void { - // tslint:disable: no-unsafe-any - if (!Tracing.options.traceFetch) { - return; - } - - if (!Tracing.options.shouldCreateSpanForRequest(handlerData.fetchData.url)) { - return; - } - - if (handlerData.endTimestamp && handlerData.fetchData.__activity) { - Tracing.popActivity(handlerData.fetchData.__activity, handlerData.fetchData); - } else { - handlerData.fetchData.__activity = Tracing.pushActivity('fetch', { - data: { - ...handlerData.fetchData, - type: 'fetch', - }, - description: `${handlerData.fetchData.method} ${handlerData.fetchData.url}`, - op: 'http', - }); - - const activity = Tracing._activities[handlerData.fetchData.__activity]; - if (activity) { - const span = activity.span; - if (span) { - const request = (handlerData.args[0] = handlerData.args[0] as string | Request); - const options = (handlerData.args[1] = (handlerData.args[1] as { [key: string]: any }) || {}); - let headers = options.headers; - if (isInstanceOf(request, Request)) { - headers = (request as Request).headers; - } - if (headers) { - if (typeof headers.append === 'function') { - headers.append('sentry-trace', span.toTraceparent()); - } else if (Array.isArray(headers)) { - headers = [...headers, ['sentry-trace', span.toTraceparent()]]; - } else { - headers = { ...headers, 'sentry-trace': span.toTraceparent() }; - } - } else { - headers = { 'sentry-trace': span.toTraceparent() }; - } - options.headers = headers; - } - } - } - // tslint:enable: no-unsafe-any -} - -/** - * Creates transaction from navigation changes - */ -function historyCallback(_: { [key: string]: any }): void { - if (Tracing.options.startTransactionOnLocationChange && global && global.location) { - Tracing.finishIdleTransaction(timestampWithMs()); - Tracing.startIdleTransaction({ - name: Tracing.options.beforeNavigate(window.location), - op: 'navigation', - }); - } -} diff --git a/packages/tracing/src/integrations/tracing/backgroundtab.ts b/packages/tracing/src/integrations/tracing/backgroundtab.ts new file mode 100644 index 000000000000..c14d5c1bb70a --- /dev/null +++ b/packages/tracing/src/integrations/tracing/backgroundtab.ts @@ -0,0 +1,30 @@ +import { getGlobalObject, isInstanceOf, logger, timestampWithMs } from '@sentry/utils'; + +import { IdleTransaction } from '../../idletransaction'; +import { SpanStatus } from '../../spanstatus'; + +import { getActiveTransaction } from './utils'; + +const global = getGlobalObject(); + +/** + * Add a listener that cancels and finishes a transaction when the global + * document is hidden. + */ +export function registerBackgroundTabDetection(): void { + if (global && global.document) { + document.addEventListener('visibilitychange', () => { + const activeTransaction = getActiveTransaction() as IdleTransaction; + if (document.hidden && activeTransaction) { + logger.log(`[Tracing] Transaction: ${SpanStatus.Cancelled} -> since tab moved to the background`); + activeTransaction.setStatus(SpanStatus.Cancelled); + activeTransaction.setTag('visibilitychange', 'document.hidden'); + if (isInstanceOf(activeTransaction, IdleTransaction)) { + activeTransaction.finishIdleTransaction(timestampWithMs()); + } else { + activeTransaction.finish(); + } + } + }); + } +} diff --git a/packages/tracing/src/integrations/tracing/errors.ts b/packages/tracing/src/integrations/tracing/errors.ts new file mode 100644 index 000000000000..6398758e8eb6 --- /dev/null +++ b/packages/tracing/src/integrations/tracing/errors.ts @@ -0,0 +1,29 @@ +import { addInstrumentationHandler } from '@sentry/utils'; + +import { SpanStatus } from '../../spanstatus'; + +import { getActiveTransaction } from './utils'; + +/** + * Configures global error listeners + */ +export function registerErrorHandlers(): void { + addInstrumentationHandler({ + callback: errorCallback, + type: 'error', + }); + addInstrumentationHandler({ + callback: errorCallback, + type: 'unhandledrejection', + }); +} + +/** + * If an error or unhandled promise occurs, we mark the active transaction as failed + */ +function errorCallback(): void { + const activeTransaction = getActiveTransaction(); + if (activeTransaction) { + activeTransaction.setStatus(SpanStatus.InternalError); + } +} diff --git a/packages/tracing/src/integrations/tracing/performance.ts b/packages/tracing/src/integrations/tracing/performance.ts new file mode 100644 index 000000000000..0f19e6f132d0 --- /dev/null +++ b/packages/tracing/src/integrations/tracing/performance.ts @@ -0,0 +1,251 @@ +import { getGlobalObject } from '@sentry/utils'; + +import { Span } from '../../span'; +import { Transaction } from '../../transaction'; +import { BrowserTracing } from '../browsertracing'; + +import { msToSec } from './utils'; + +const global = getGlobalObject(); + +/** + * Adds metrics to transactions. + */ +// tslint:disable-next-line: no-unnecessary-class +export class Metrics { + private static _lcp: Record; + + private static _performanceCursor: number = 0; + + private static _forceLCP = () => { + /* No-op, replaced later if LCP API is available. */ + return; + }; + + /** + * Starts tracking the Largest Contentful Paint on the current page. + */ + private static _trackLCP(): void { + // Based on reference implementation from https://web.dev/lcp/#measure-lcp-in-javascript. + + // Use a try/catch instead of feature detecting `largest-contentful-paint` + // support, since some browsers throw when using the new `type` option. + // https://bugs.webkit.org/show_bug.cgi?id=209216 + try { + // Keep track of whether (and when) the page was first hidden, see: + // https://github.com/w3c/page-visibility/issues/29 + // NOTE: ideally this check would be performed in the document + // to avoid cases where the visibility state changes before this code runs. + let firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity; + document.addEventListener( + 'visibilitychange', + event => { + firstHiddenTime = Math.min(firstHiddenTime, event.timeStamp); + }, + { once: true }, + ); + + const updateLCP = (entry: PerformanceEntry) => { + // Only include an LCP entry if the page wasn't hidden prior to + // the entry being dispatched. This typically happens when a page is + // loaded in a background tab. + if (entry.startTime < firstHiddenTime) { + // NOTE: the `startTime` value is a getter that returns the entry's + // `renderTime` value, if available, or its `loadTime` value otherwise. + // The `renderTime` value may not be available if the element is an image + // that's loaded cross-origin without the `Timing-Allow-Origin` header. + Metrics._lcp = { + // @ts-ignore + ...(entry.id && { elementId: entry.id }), + // @ts-ignore + ...(entry.size && { elementSize: entry.size }), + value: entry.startTime, + }; + } + }; + + // Create a PerformanceObserver that calls `updateLCP` for each entry. + const po = new PerformanceObserver(entryList => { + entryList.getEntries().forEach(updateLCP); + }); + + // Observe entries of type `largest-contentful-paint`, including buffered entries, + // i.e. entries that occurred before calling `observe()` below. + po.observe({ + buffered: true, + // @ts-ignore + type: 'largest-contentful-paint', + }); + + Metrics._forceLCP = () => { + po.takeRecords().forEach(updateLCP); + }; + } catch (e) { + // Do nothing if the browser doesn't support this API. + } + } + + /** + * Start tracking metrics + */ + public static init(): void { + if (global.performance) { + if (global.performance.mark) { + global.performance.mark('sentry-tracing-init'); + } + Metrics._trackLCP(); + } + } + + /** + * Adds performance related spans to a transaction + */ + public static addPerformanceEntries(transaction: Transaction): void { + if (!global.performance || !global.performance.getEntries) { + // Gatekeeper if performance API not available + return; + } + + BrowserTracing.log('[Tracing] Adding & adjusting spans using Performance API'); + // FIXME: depending on the 'op' directly is brittle. + if (transaction.op === 'pageload') { + // Force any pending records to be dispatched. + Metrics._forceLCP(); + if (Metrics._lcp) { + // Set the last observed LCP score. + transaction.setData('_sentry_web_vitals', { LCP: Metrics._lcp }); + } + } + + const timeOrigin = msToSec(performance.timeOrigin); + + let entryScriptSrc: string | undefined; + + if (global.document) { + // tslint:disable-next-line: prefer-for-of + for (let i = 0; i < document.scripts.length; i++) { + // We go through all scripts on the page and look for 'data-entry' + // We remember the name and measure the time between this script finished loading and + // our mark 'sentry-tracing-init' + if (document.scripts[i].dataset.entry === 'true') { + entryScriptSrc = document.scripts[i].src; + break; + } + } + } + + let entryScriptStartEndTime: number | undefined; + let tracingInitMarkStartTime: number | undefined; + + // tslint:disable-next-line: completed-docs + function addPerformanceNavigationTiming(parent: Span, entry: Record, event: string): void { + parent.startChild({ + description: event, + endTimestamp: timeOrigin + msToSec(entry[`${event}End`]), + op: 'browser', + startTimestamp: timeOrigin + msToSec(entry[`${event}Start`]), + }); + } + + // tslint:disable-next-line: completed-docs + function addRequest(parent: Span, entry: Record): void { + parent.startChild({ + description: 'request', + endTimestamp: timeOrigin + msToSec(entry.responseEnd), + op: 'browser', + startTimestamp: timeOrigin + msToSec(entry.requestStart), + }); + + parent.startChild({ + description: 'response', + endTimestamp: timeOrigin + msToSec(entry.responseEnd), + op: 'browser', + startTimestamp: timeOrigin + msToSec(entry.responseStart), + }); + } + + // tslint:disable: no-unsafe-any + performance + .getEntries() + .slice(Metrics._performanceCursor) + .forEach((entry: any) => { + const startTime = msToSec(entry.startTime as number); + const duration = msToSec(entry.duration as number); + + if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) { + return; + } + + switch (entry.entryType) { + case 'navigation': + addPerformanceNavigationTiming(transaction, entry, 'unloadEvent'); + addPerformanceNavigationTiming(transaction, entry, 'domContentLoadedEvent'); + addPerformanceNavigationTiming(transaction, entry, 'loadEvent'); + addPerformanceNavigationTiming(transaction, entry, 'connect'); + addPerformanceNavigationTiming(transaction, entry, 'domainLookup'); + addRequest(transaction, entry); + break; + case 'mark': + case 'paint': + case 'measure': + const measureStartTimestamp = timeOrigin + startTime; + const measureEndTimestamp = measureStartTimestamp + duration; + + if (tracingInitMarkStartTime === undefined && entry.name === 'sentry-tracing-init') { + tracingInitMarkStartTime = measureStartTimestamp; + } + + transaction.startChild({ + description: entry.name, + endTimestamp: measureEndTimestamp, + op: entry.entryType, + startTimestamp: measureStartTimestamp, + }); + break; + case 'resource': + const resourceName = entry.name.replace(window.location.origin, ''); + if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') { + // We need to update existing spans with new timing info + if (transaction.spanRecorder) { + transaction.spanRecorder.spans.map((finishedSpan: Span) => { + if (finishedSpan.description && finishedSpan.description.indexOf(resourceName) !== -1) { + finishedSpan.startTimestamp = timeOrigin + startTime; + finishedSpan.endTimestamp = finishedSpan.startTimestamp + duration; + } + }); + } + } else { + const startTimestamp = timeOrigin + startTime; + const endTimestamp = startTimestamp + duration; + + // We remember the entry script end time to calculate the difference to the first init mark + if (entryScriptStartEndTime === undefined && (entryScriptSrc || '').indexOf(resourceName) > -1) { + entryScriptStartEndTime = endTimestamp; + } + + transaction.startChild({ + description: `${entry.initiatorType} ${resourceName}`, + endTimestamp, + op: `resource`, + startTimestamp, + }); + } + break; + default: + // Ignore other entry types. + } + }); + if (entryScriptStartEndTime !== undefined && tracingInitMarkStartTime !== undefined) { + transaction.startChild({ + description: 'evaluation', + endTimestamp: tracingInitMarkStartTime, + op: `script`, + startTimestamp: entryScriptStartEndTime, + }); + } + + Metrics._performanceCursor = Math.max(performance.getEntries().length - 1, 0); + + // tslint:enable: no-unsafe-any + } +} diff --git a/packages/tracing/src/integrations/tracing/request.ts b/packages/tracing/src/integrations/tracing/request.ts new file mode 100644 index 000000000000..93c82f5df7b1 --- /dev/null +++ b/packages/tracing/src/integrations/tracing/request.ts @@ -0,0 +1,256 @@ +import { addInstrumentationHandler, isInstanceOf, isMatchingPattern } from '@sentry/utils'; + +import { Span } from '../../span'; + +import { getActiveTransaction } from './utils'; + +const defaultTracingOrigins = ['localhost', /^\//]; + +/** + * Options for RequestInstrumentation + */ +export interface RequestInstrumentationOptions { + /** + * List of strings / regex where the integration should create Spans out of. Additionally this will be used + * to define which outgoing requests the `sentry-trace` header will be attached to. + * + * Default: ['localhost', /^\//] + */ + tracingOrigins: Array; + + /** + * Flag to disable patching all together for fetch requests. + * + * Default: true + */ + traceFetch: boolean; + + /** + * Flag to disable patching all together for xhr requests. + * + * Default: true + */ + traceXHR: boolean; + + /** + * This function will be called before creating a span for a request with the given url. + * Return false if you don't want a span for the given url. + * + * By default it uses the `tracingOrigins` options as a url match. + */ + shouldCreateSpanForRequest?(url: string): boolean; +} + +export const defaultRequestInstrumentionOptions: RequestInstrumentationOptions = { + traceFetch: true, + traceXHR: true, + tracingOrigins: defaultTracingOrigins, +}; + +/** JSDOC */ +export interface RequestInstrumentation { + options: Partial; + + /** + * start tracking requests + */ + init(): void; +} + +export type RequestInstrumentationClass = new (_options?: RequestInstrumentationOptions) => RequestInstrumentation; + +/** + * Data returned from fetch callback + */ +interface FetchData { + args: any[]; + fetchData: { + method: string; + url: string; + // span_id + __span?: string; + }; + startTimestamp: number; + endTimestamp?: number; +} + +/** + * Data returned from XHR request + */ +interface XHRData { + xhr?: { + __sentry_xhr__?: { + method: string; + url: string; + status_code: number; + data: Record; + }; + __sentry_xhr_span_id__?: string; + __sentry_own_request__: boolean; + setRequestHeader?: Function; + }; + startTimestamp: number; + endTimestamp?: number; +} + +// tslint:disable-next-line: completed-docs +export class RequestTracing implements RequestInstrumentation { + public options: RequestInstrumentationOptions = defaultRequestInstrumentionOptions; + + public static spans: Record = {}; + + public constructor(_options?: Partial) { + this.options = { + ...this.options, + ..._options, + }; + } + + /** + * @inheritDoc + */ + public init(): void { + const { tracingOrigins, shouldCreateSpanForRequest } = this.options; + + const shouldCreateSpan = shouldCreateSpanForRequest + ? shouldCreateSpanForRequest + : (url: string) => { + const origins = tracingOrigins ? tracingOrigins : defaultTracingOrigins; + let currentOrigin = ''; + try { + currentOrigin = new URL(url).origin; + } catch (_) { + currentOrigin = url; + } + + return ( + origins.some((origin: string | RegExp) => isMatchingPattern(currentOrigin, origin)) && + !isMatchingPattern(url, 'sentry_key') + ); + }; + + // Register tracking for fetch requests; + if (this.options.traceFetch) { + addInstrumentationHandler({ + callback: (handlerData: FetchData) => { + fetchCallback(handlerData, shouldCreateSpan); + }, + type: 'fetch', + }); + } + + if (this.options.traceXHR) { + addInstrumentationHandler({ + callback: (handlerData: XHRData) => { + xhrCallback(handlerData, shouldCreateSpan); + }, + type: 'xhr', + }); + } + } +} + +/** + * Create and track fetch request spans + */ +function fetchCallback(handlerData: FetchData, shouldCreateSpan: (url: string) => boolean): void { + if (!shouldCreateSpan(handlerData.fetchData.url)) { + return; + } + + if (handlerData.endTimestamp && handlerData.fetchData.__span) { + const span = RequestTracing.spans[handlerData.fetchData.__span]; + if (span) { + span.finish(); + } + return; + } + + const activeTransaction = getActiveTransaction(); + if (activeTransaction) { + const span = activeTransaction.startChild({ + data: { + ...handlerData.fetchData, + type: 'fetch', + }, + description: `${handlerData.fetchData.method} ${handlerData.fetchData.url}`, + op: 'http', + }); + + RequestTracing.spans[span.spanId] = span; + + const request = (handlerData.args[0] = handlerData.args[0] as string | Request); + const options = (handlerData.args[1] = (handlerData.args[1] as { [key: string]: any }) || {}); + let headers = options.headers; + if (isInstanceOf(request, Request)) { + headers = (request as Request).headers; + } + if (headers) { + // tslint:disable-next-line: no-unsafe-any + if (typeof headers.append === 'function') { + // tslint:disable-next-line: no-unsafe-any + headers.append('sentry-trace', span.toTraceparent()); + } else if (Array.isArray(headers)) { + headers = [...headers, ['sentry-trace', span.toTraceparent()]]; + } else { + headers = { ...headers, 'sentry-trace': span.toTraceparent() }; + } + } else { + headers = { 'sentry-trace': span.toTraceparent() }; + } + options.headers = headers; + } +} + +/** + * Create and track xhr request spans + */ +function xhrCallback(handlerData: XHRData, shouldCreateSpan: (url: string) => boolean): void { + if (!handlerData || !handlerData.xhr || !handlerData.xhr.__sentry_xhr__) { + return; + } + + const xhr = handlerData.xhr.__sentry_xhr__; + if (!shouldCreateSpan(xhr.url)) { + return; + } + + // We only capture complete, non-sentry requests + if (handlerData.xhr.__sentry_own_request__) { + return; + } + + if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) { + const span = RequestTracing.spans[handlerData.xhr.__sentry_xhr_span_id__]; + if (span) { + span.setData('url', xhr.url); + span.setData('method', xhr.method); + span.setHttpStatus(xhr.status_code); + span.finish(); + } + return; + } + + const activeTransaction = getActiveTransaction(); + if (activeTransaction) { + const span = activeTransaction.startChild({ + data: { + ...xhr.data, + type: 'xhr', + }, + description: `${xhr.method} ${xhr.url}`, + op: 'http', + }); + + handlerData.xhr.__sentry_xhr_span_id__ = span.spanId; + RequestTracing.spans[handlerData.xhr.__sentry_xhr_span_id__] = span; + + if (handlerData.xhr.setRequestHeader) { + try { + handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent()); + } catch (_) { + // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. + } + } + } +} diff --git a/packages/tracing/src/integrations/tracing/router.ts b/packages/tracing/src/integrations/tracing/router.ts new file mode 100644 index 000000000000..48ae26dfa006 --- /dev/null +++ b/packages/tracing/src/integrations/tracing/router.ts @@ -0,0 +1,220 @@ +import { Hub } from '@sentry/hub'; +import { TransactionContext } from '@sentry/types'; +import { addInstrumentationHandler, getGlobalObject, logger, timestampWithMs } from '@sentry/utils'; + +import { IdleTransaction } from '../../idletransaction'; + +import { Location as LocationType } from './types'; + +const global = getGlobalObject(); + +/** + * Options for RoutingInstrumentation + */ +export interface RoutingInstrumentationOptions { + /** + * The time to wait in ms until the transaction will be finished. The transaction will use the end timestamp of + * the last finished span as the endtime for the transaction. + * Time is in ms. + * + * Default: 1000 + */ + idleTimeout: number; + + /** + * Flag to enable/disable creation of `navigation` transaction on history changes. Useful for react applications with + * a router. + * + * Default: true + */ + startTransactionOnLocationChange: boolean; + + /** + * Flag to enable/disable creation of `pageload` transaction on first pageload. + * + * Default: true + */ + startTransactionOnPageLoad: boolean; + + /** + * beforeNavigate is called before a pageload/navigation transaction is created and allows for users + * to set a custom navigation transaction name based on the current `window.location`. Defaults to returning + * `window.location.pathname`. + * + * If null is returned, a pageload/navigation transaction will not be created. + * + * @param name the current name of the pageload/navigation transaction + */ + beforeNavigate(location: LocationType): string | null; +} + +export const defaultRoutingInstrumentationOptions: RoutingInstrumentationOptions = { + beforeNavigate(location: LocationType): string | null { + return location.pathname; + }, + idleTimeout: 1000, + startTransactionOnLocationChange: true, + startTransactionOnPageLoad: true, +}; + +/** + * Defines how to instrument routing + */ +export interface RoutingInstrumentation { + options: Partial; + + /** + * Start recording pageload/navigation transactions + * @param hub The hub associated with the pageload/navigation transactions + * @param idleTimeout The timeout for the transactions + */ + init( + hub: Hub, + beforeFinish?: (transactionSpan: IdleTransaction) => void, + transactionContext?: Partial, + ): void; + + /** + * Start an idle transaction. Called by init(). + */ + startIdleTransaction( + hub: Hub, + op: string, + transactionContext?: Partial, + ): IdleTransaction | undefined; + + /** + * Start a pageload transaction + */ + startPageloadTransaction( + hub: Hub, + beforeFinish?: (transactionSpan: IdleTransaction) => void, + transactionContext?: TransactionContext, + ): void; + + /** + * Start a navigation transaction + */ + startNavigationTransaction( + hub: Hub, + beforeFinish?: (transactionSpan: IdleTransaction) => void, + transactionContext?: TransactionContext, + ): void; +} + +export type RoutingInstrumentationClass = new (_options?: RoutingInstrumentationOptions) => RoutingInstrumentation; + +/** JSDOC */ +export class RouterTracing implements RoutingInstrumentation { + /** JSDoc */ + public options: RoutingInstrumentationOptions = defaultRoutingInstrumentationOptions; + + private _activeTransaction?: IdleTransaction; + + public constructor(_options?: RoutingInstrumentationOptions) { + this.options = { + ...this.options, + ..._options, + }; + } + + /** + * @inheritDoc + */ + public startIdleTransaction( + hub: Hub, + op: string, + transactionContext?: Partial, + ): IdleTransaction | undefined { + if (!global || !global.location || !hub) { + return undefined; + } + + const name = this.options.beforeNavigate(global.location); + + // if beforeNavigate returns null, we should not start a transaction. + if (name === null) { + return undefined; + } + + this._activeTransaction = hub.startTransaction( + { + name, + op, + trimEnd: true, + ...transactionContext, + }, + this.options.idleTimeout, + ) as IdleTransaction; + + return this._activeTransaction; + } + + /** + * @inheritDoc + */ + public startPageloadTransaction( + hub: Hub, + beforeFinish?: (transactionSpan: IdleTransaction) => void, + transactionContext?: TransactionContext, + ): void { + logger.log(`[Tracing] starting pageload transaction`); + this._activeTransaction = this.startIdleTransaction(hub, 'pageload', transactionContext); + if (this._activeTransaction && beforeFinish) { + this._activeTransaction.beforeFinish(beforeFinish); + } + } + + /** + * @inheritDoc + */ + public startNavigationTransaction( + hub: Hub, + beforeFinish?: (transactionSpan: IdleTransaction) => void, + transactionContext?: TransactionContext, + ): void { + if (this._activeTransaction) { + logger.log(`[Tracing] force ending previous transaction`); + this._activeTransaction.finishIdleTransaction(timestampWithMs()); + } + logger.log(`[Tracing] starting navigation transaction`); + this._activeTransaction = this.startIdleTransaction(hub, 'navigation', transactionContext); + if (this._activeTransaction && beforeFinish) { + this._activeTransaction.beforeFinish(beforeFinish); + } + } + + /** + * @inheritDoc + */ + public init( + hub: Hub, + beforeFinish?: (transactionSpan: IdleTransaction) => void, + transactionContext?: TransactionContext, + ): void { + const { startTransactionOnPageLoad, startTransactionOnLocationChange } = this.options; + if (startTransactionOnPageLoad) { + this.startPageloadTransaction(hub, beforeFinish, transactionContext); + } + + let startingUrl: string | undefined; + if (global && global.location) { + startingUrl = global.location.href; + } + + addInstrumentationHandler({ + callback: ({ to, from }: { to: string; from?: string }) => { + // This is to account for some cases where navigation transaction + // starts right after long running pageload. + if (startingUrl && from === undefined && startingUrl.indexOf(to) !== -1) { + startingUrl = undefined; + return; + } + if (startTransactionOnLocationChange && from !== to) { + this.startNavigationTransaction(hub, beforeFinish, transactionContext); + } + }, + type: 'history', + }); + } +} diff --git a/packages/tracing/src/integrations/tracing/types.ts b/packages/tracing/src/integrations/tracing/types.ts new file mode 100644 index 000000000000..331cbee7ba57 --- /dev/null +++ b/packages/tracing/src/integrations/tracing/types.ts @@ -0,0 +1,109 @@ +/** + * A type returned by some APIs which contains a list of DOMString (strings). + * + * Copy DOMStringList interface so that user's dont have to include dom typings with Tracing integration + * Based on https://github.com/microsoft/TypeScript/blob/4cf0afe2662980ebcd8d444dbd13d8f47d06fcd5/lib/lib.dom.d.ts#L4051 + */ +interface DOMStringList { + /** + * Returns the number of strings in strings. + */ + readonly length: number; + /** + * Returns true if strings contains string, and false otherwise. + */ + contains(str: string): boolean; + /** + * Returns the string with index index from strings. + */ + item(index: number): string | null; + [index: number]: string; +} + +declare var DOMStringList: { + prototype: DOMStringList; + new (): DOMStringList; +}; + +/** + * The location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. + * Both the Document and Window interface have such a linked Location, accessible via Document.location and Window.location respectively. + * + * Copy Location interface so that user's dont have to include dom typings with Tracing integration + * Based on https://github.com/microsoft/TypeScript/blob/4cf0afe2662980ebcd8d444dbd13d8f47d06fcd5/lib/lib.dom.d.ts#L9691 + */ +export interface Location { + /** + * Returns a DOMStringList object listing the origins of the ancestor browsing contexts, from the parent browsing context to the top-level browsing context. + */ + readonly ancestorOrigins: DOMStringList; + /** + * Returns the Location object's URL's fragment (includes leading "#" if non-empty). + * + * Can be set, to navigate to the same URL with a changed fragment (ignores leading "#"). + */ + hash: string; + /** + * Returns the Location object's URL's host and port (if different from the default port for the scheme). + * + * Can be set, to navigate to the same URL with a changed host and port. + */ + host: string; + /** + * Returns the Location object's URL's host. + * + * Can be set, to navigate to the same URL with a changed host. + */ + hostname: string; + /** + * Returns the Location object's URL. + * + * Can be set, to navigate to the given URL. + */ + href: string; + // tslint:disable-next-line: completed-docs + toString(): string; + /** + * Returns the Location object's URL's origin. + */ + readonly origin: string; + /** + * Returns the Location object's URL's path. + * + * Can be set, to navigate to the same URL with a changed path. + */ + pathname: string; + /** + * Returns the Location object's URL's port. + * + * Can be set, to navigate to the same URL with a changed port. + */ + port: string; + /** + * Returns the Location object's URL's scheme. + * + * Can be set, to navigate to the same URL with a changed scheme. + */ + protocol: string; + /** + * Returns the Location object's URL's query (includes leading "?" if non-empty). + * + * Can be set, to navigate to the same URL with a changed query (ignores leading "?"). + */ + search: string; + /** + * Navigates to the given URL. + */ + assign(url: string): void; + /** + * Reloads the current page. + */ + reload(): void; + /** @deprecated */ + // tslint:disable-next-line: unified-signatures completed-docs + reload(forcedReload: boolean): void; + /** + * Removes the current page from the session history and navigates to the given URL. + */ + replace(url: string): void; +} diff --git a/packages/tracing/src/integrations/tracing/utils.ts b/packages/tracing/src/integrations/tracing/utils.ts new file mode 100644 index 000000000000..09b61fb0b572 --- /dev/null +++ b/packages/tracing/src/integrations/tracing/utils.ts @@ -0,0 +1,27 @@ +import { getCurrentHub } from '@sentry/hub'; + +import { IdleTransaction } from '../../idletransaction'; +import { Transaction } from '../../transaction'; + +/** + * Grabs active transaction off scope + */ +export function getActiveTransaction(): Transaction | IdleTransaction | undefined { + const hub = getCurrentHub(); + if (hub) { + const scope = hub.getScope(); + if (scope) { + return scope.getTransaction() as Transaction | IdleTransaction | undefined; + } + } + + return undefined; +} + +/** + * Converts from milliseconds to seconds + * @param time time in ms + */ +export function msToSec(time: number): number { + return time / 1000; +} diff --git a/packages/tracing/test/idletransaction.test.ts b/packages/tracing/test/idletransaction.test.ts new file mode 100644 index 000000000000..f38b7234eccd --- /dev/null +++ b/packages/tracing/test/idletransaction.test.ts @@ -0,0 +1,203 @@ +import { BrowserClient } from '@sentry/browser'; +import { Hub } from '@sentry/hub'; + +import { IdleTransaction, IdleTransactionSpanRecorder } from '../src/idletransaction'; +import { Span } from '../src/span'; + +describe('IdleTransaction', () => { + let hub: Hub; + beforeEach(() => { + jest.useFakeTimers(); + hub = new Hub(new BrowserClient({ tracesSampleRate: 1 })); + }); + + it('sets the transaction on the scope on creation', () => { + const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); + transaction.initSpanRecorder(10); + + hub.configureScope(s => { + expect(s.getTransaction()).toBe(transaction); + }); + }); + + it('removes transaction from scope on finish', () => { + const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); + transaction.initSpanRecorder(10); + + transaction.finish(); + jest.runAllTimers(); + + hub.configureScope(s => { + expect(s.getTransaction()).toBe(undefined); + }); + }); + + it('push and pops activities', () => { + const mockFinish = jest.fn(); + const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); + transaction.finish = mockFinish; + transaction.initSpanRecorder(10); + expect(transaction.activities).toMatchObject({}); + + const span = transaction.startChild(); + expect(transaction.activities).toMatchObject({ [span.spanId]: true }); + + expect(mockFinish).toHaveBeenCalledTimes(0); + + span.finish(); + expect(transaction.activities).toMatchObject({}); + + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(1); + + // After we run all timers, we still want to make sure that + // transaction.finish() is only called once. This tells us that the + // heartbeat was stopped and that the `_finished` class + // property was used properly. This allows us to know if the + // heartbeat was correctly shut down. + jest.runAllTimers(); + expect(mockFinish).toHaveBeenCalledTimes(1); + }); + + it('does not push activities if a span already has an end timestamp', () => { + const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); + transaction.initSpanRecorder(10); + expect(transaction.activities).toMatchObject({}); + + transaction.startChild({ startTimestamp: 1234, endTimestamp: 5678 }); + expect(transaction.activities).toMatchObject({}); + }); + + it('does not finish if there are still active activities', () => { + const mockFinish = jest.fn(); + const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); + + transaction.finish = mockFinish; + transaction.initSpanRecorder(10); + expect(transaction.activities).toMatchObject({}); + + const span = transaction.startChild(); + const childSpan = span.startChild(); + + expect(transaction.activities).toMatchObject({ [span.spanId]: true, [childSpan.spanId]: true }); + span.finish(); + jest.runOnlyPendingTimers(); + + expect(mockFinish).toHaveBeenCalledTimes(0); + expect(transaction.activities).toMatchObject({ [childSpan.spanId]: true }); + }); + + it('calls beforeFinish callback before finishing', () => { + const mockCallback = jest.fn(); + const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); + transaction.initSpanRecorder(10); + transaction.beforeFinish(mockCallback); + transaction.beforeFinish(mockCallback); + + expect(mockCallback).toHaveBeenCalledTimes(0); + + const span = transaction.startChild(); + span.finish(); + + jest.runOnlyPendingTimers(); + expect(mockCallback).toHaveBeenCalledTimes(1); + expect(mockCallback).toHaveBeenLastCalledWith(transaction); + }); + + describe('heartbeat', () => { + it('finishes a transaction after 3 beats', () => { + const mockFinish = jest.fn(); + const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); + transaction.finish = mockFinish; + transaction.initSpanRecorder(10); + + expect(mockFinish).toHaveBeenCalledTimes(0); + + // Beat 1 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(0); + + // Beat 2 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(0); + + // Beat 3 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(1); + }); + + it('resets after new activities are added', () => { + const mockFinish = jest.fn(); + const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); + transaction.finish = mockFinish; + transaction.initSpanRecorder(10); + + expect(mockFinish).toHaveBeenCalledTimes(0); + + // Beat 1 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(0); + + const span = transaction.startChild(); // push activity + + // Beat 1 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(0); + + // Beat 2 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(0); + + transaction.startChild(); // push activity + transaction.startChild(); // push activity + + // Beat 1 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(0); + + // Beat 2 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(0); + + span.finish(); // pop activity + + // Beat 1 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(0); + + // Beat 2 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(0); + + // Beat 3 + jest.runOnlyPendingTimers(); + expect(mockFinish).toHaveBeenCalledTimes(1); + }); + }); +}); + +describe('IdleTransactionSpanRecorder', () => { + it('pushes and pops activities', () => { + const mockPushActivity = jest.fn(); + const mockPopActivity = jest.fn(); + + const spanRecorder = new IdleTransactionSpanRecorder(10, mockPushActivity, mockPopActivity); + expect(mockPushActivity).toHaveBeenCalledTimes(0); + expect(mockPopActivity).toHaveBeenCalledTimes(0); + + const span = new Span({ sampled: true }); + + expect(spanRecorder.spans).toHaveLength(0); + spanRecorder.add(span); + expect(spanRecorder.spans).toHaveLength(1); + + expect(mockPushActivity).toHaveBeenCalledTimes(1); + expect(mockPushActivity).toHaveBeenLastCalledWith(span.spanId); + expect(mockPopActivity).toHaveBeenCalledTimes(0); + + span.finish(); + expect(mockPushActivity).toHaveBeenCalledTimes(1); + expect(mockPopActivity).toHaveBeenCalledTimes(1); + expect(mockPushActivity).toHaveBeenLastCalledWith(span.spanId); + }); +}); diff --git a/packages/types/src/hub.ts b/packages/types/src/hub.ts index 694e531c4d87..c77092da93fd 100644 --- a/packages/types/src/hub.ts +++ b/packages/types/src/hub.ts @@ -198,5 +198,5 @@ export interface Hub { * * @param context Properties of the new `Transaction`. */ - startTransaction(context: TransactionContext): Transaction; + startTransaction(context: TransactionContext, idleTimeout?: number): Transaction; }