From 467c8463b90c6449b2f3864087d9875f7b619b54 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Mon, 6 Jul 2020 09:22:41 -0400 Subject: [PATCH 1/7] test: remove hub.startSpan test --- packages/tracing/test/span.test.ts | 44 ------------------------------ 1 file changed, 44 deletions(-) diff --git a/packages/tracing/test/span.test.ts b/packages/tracing/test/span.test.ts index 0fb373174259..5fed6cfbf9d4 100644 --- a/packages/tracing/test/span.test.ts +++ b/packages/tracing/test/span.test.ts @@ -320,50 +320,6 @@ describe('Span', () => { expect(spanTwo.toJSON().parent_span_id).toEqual(transaction.toJSON().span_id); }); }); - - describe('hub.startSpan', () => { - test('finish a transaction', () => { - const spy = jest.spyOn(hub as any, 'captureEvent') as any; - // @ts-ignore - const transaction = hub.startSpan({ name: 'test' }); - transaction.finish(); - expect(spy).toHaveBeenCalled(); - expect(spy.mock.calls[0][0].spans).toHaveLength(0); - expect(spy.mock.calls[0][0].timestamp).toBeTruthy(); - expect(spy.mock.calls[0][0].start_timestamp).toBeTruthy(); - expect(spy.mock.calls[0][0].contexts.trace).toEqual(transaction.getTraceContext()); - }); - - test('finish a transaction (deprecated way)', () => { - const spy = jest.spyOn(hub as any, 'captureEvent') as any; - // @ts-ignore - const transaction = hub.startSpan({ transaction: 'test' }); - transaction.finish(); - expect(spy).toHaveBeenCalled(); - expect(spy.mock.calls[0][0].spans).toHaveLength(0); - expect(spy.mock.calls[0][0].timestamp).toBeTruthy(); - expect(spy.mock.calls[0][0].start_timestamp).toBeTruthy(); - expect(spy.mock.calls[0][0].contexts.trace).toEqual(transaction.getTraceContext()); - }); - - test('startSpan with Span on the Scope should be a child', () => { - const spy = jest.spyOn(hub as any, 'captureEvent') as any; - const transaction = hub.startTransaction({ name: 'test' }); - const child1 = transaction.startChild(); - hub.configureScope(scope => { - scope.setSpan(child1); - }); - - const child2 = hub.startSpan({}); - child1.finish(); - child2.finish(); - transaction.finish(); - - expect(spy).toHaveBeenCalled(); - expect(spy.mock.calls[0][0].spans).toHaveLength(2); - expect(child2.parentSpanId).toEqual(child1.spanId); - }); - }); }); describe('getTraceContext', () => { From 5717c152927c1c3b0158bb4e8d2350df979bd7f2 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Mon, 6 Jul 2020 16:31:59 -0400 Subject: [PATCH 2/7] feat(tracing): Add BrowserTracing integration and tests --- packages/tracing/package.json | 2 + .../tracing/src/browser/browsertracing.ts | 241 ++++++++++++++++++ packages/tracing/src/hubextensions.ts | 6 +- packages/tracing/src/idletransaction.ts | 4 +- packages/tracing/src/index.ts | 6 +- packages/tracing/src/integrations/tracing.ts | 3 +- .../tracing/src/{integrations => }/types.ts | 0 .../test/browser/browsertracing.test.ts | 231 +++++++++++++++++ yarn.lock | 49 +++- 9 files changed, 533 insertions(+), 9 deletions(-) create mode 100644 packages/tracing/src/browser/browsertracing.ts rename packages/tracing/src/{integrations => }/types.ts (100%) create mode 100644 packages/tracing/test/browser/browsertracing.test.ts diff --git a/packages/tracing/package.json b/packages/tracing/package.json index 821d237b0a7f..e0f5355edb74 100644 --- a/packages/tracing/package.json +++ b/packages/tracing/package.json @@ -25,7 +25,9 @@ }, "devDependencies": { "@types/express": "^4.17.1", + "@types/jsdom": "^16.2.3", "jest": "^24.7.1", + "jsdom": "^16.2.2", "npm-run-all": "^4.1.2", "prettier": "^1.17.0", "prettier-check": "^2.0.0", diff --git a/packages/tracing/src/browser/browsertracing.ts b/packages/tracing/src/browser/browsertracing.ts new file mode 100644 index 000000000000..66f630c7dd87 --- /dev/null +++ b/packages/tracing/src/browser/browsertracing.ts @@ -0,0 +1,241 @@ +import { Hub } from '@sentry/hub'; +import { EventProcessor, Integration, Severity, TransactionContext } from '@sentry/types'; +import { addInstrumentationHandler, getGlobalObject, logger, safeJoin } from '@sentry/utils'; + +import { startIdleTransaction } from '../hubextensions'; +import { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../idletransaction'; +import { Span } from '../span'; +import { Location as LocationType } from '../types'; + +const global = getGlobalObject(); + +type routingInstrumentationProcessor = (context: TransactionContext) => TransactionContext; + +/** + * Gets transaction context from a sentry-trace meta. + */ +const setHeaderContext: routingInstrumentationProcessor = ctx => { + const header = getMetaContent('sentry-trace'); + if (header) { + const span = Span.fromTraceparent(header); + if (span) { + return { + ...ctx, + parentSpanId: span.parentSpanId, + sampled: span.sampled, + traceId: span.traceId, + }; + } + } + + return ctx; +}; + +/** Options for Browser Tracing integration */ +export interface BrowserTracingOptions { + /** + * 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. + * + * Default: { + * writeAsBreadcrumbs: false; + * } + */ + debug: { + writeAsBreadcrumbs: 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: 1000 + */ + idleTimeout: number; + + /** + * Flag to enable/disable creation of `navigation` transaction on history changes. + * + * 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. Defaults behaviour is to return `window.location.pathname`. + * + * If undefined is returned, a pageload/navigation transaction will not be created. + */ + beforeNavigate(location: LocationType): string | undefined; + + /** + * Set to adjust transaction context before creation of transaction. Useful to set name/data/tags before + * a transaction is sent. This option should be used by routing libraries to set context on transactions. + */ + // TODO: Should this be an option, or a static class variable and passed + // in and we use something like `BrowserTracing.addRoutingProcessor()` + routingInstrumentationProcessors: routingInstrumentationProcessor[]; +} + +/** + * The Browser Tracing integration automatically instruments browser pageload/navigation + * actions as transactions, and captures requests, metrics and errors as spans. + * + * The integration can be configured with a variety of options, and can be extended to use + * any routing library. This integration uses {@see IdleTransaction} to create transactions. + */ +export class BrowserTracing implements Integration { + /** + * @inheritDoc + */ + public static id: string = 'BrowserTracing'; + + /** Browser Tracing integration options */ + public static options: BrowserTracingOptions; + + /** + * @inheritDoc + */ + public name: string = BrowserTracing.id; + + private static _activeTransaction?: IdleTransaction; + + private static _getCurrentHub?: () => Hub; + + public constructor(_options?: Partial) { + const defaults: BrowserTracingOptions = { + beforeNavigate(location: LocationType): string | undefined { + return location.pathname; + }, + debug: { + writeAsBreadcrumbs: false, + }, + idleTimeout: DEFAULT_IDLE_TIMEOUT, + routingInstrumentationProcessors: [], + startTransactionOnLocationChange: true, + startTransactionOnPageLoad: true, + }; + BrowserTracing.options = { + ...defaults, + ..._options, + }; + } + + /** + * @inheritDoc + */ + public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { + BrowserTracing._getCurrentHub = getCurrentHub; + + if (!global || !global.location) { + return; + } + + // TODO: is it fine that this is mutable operation? Could also do = [...routingInstr, setHeaderContext]? + BrowserTracing.options.routingInstrumentationProcessors.push(setHeaderContext); + BrowserTracing._initRoutingInstrumentation(); + } + + /** Start routing instrumentation */ + private static _initRoutingInstrumentation(): void { + const { startTransactionOnPageLoad, startTransactionOnLocationChange } = BrowserTracing.options; + + if (startTransactionOnPageLoad) { + BrowserTracing._activeTransaction = BrowserTracing._createRouteTransaction('pageload'); + } + + let startingUrl: string | undefined = global.location.href; + + addInstrumentationHandler({ + callback: ({ to, from }: { to: string; from?: string }) => { + /** + * This early return is there to account for some cases where navigation transaction + * starts right after long running pageload. We make sure that if from is undefined + * and that a valid startingURL exists, we don't uncessarily create a navigation transaction. + * + * This was hard to duplicate, but this behaviour stopped as soon as this fix + * was applied. This issue might also only be caused in certain development environments + * where the usage of a hot module reloader is causing errors. + */ + if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) { + startingUrl = undefined; + return; + } + if (startTransactionOnLocationChange && from !== to) { + startingUrl = undefined; + if (BrowserTracing._activeTransaction) { + // We want to finish all current ongoing idle transactions as we + // are navigating to a new page. + BrowserTracing._activeTransaction.finishIdleTransaction(); + } + BrowserTracing._activeTransaction = BrowserTracing._createRouteTransaction('navigation'); + } + }, + type: 'history', + }); + } + + /** Create pageload/navigation idle transaction. */ + private static _createRouteTransaction(op: 'pageload' | 'navigation'): IdleTransaction | undefined { + if (!BrowserTracing._getCurrentHub) { + return undefined; + } + + const { beforeNavigate, idleTimeout, routingInstrumentationProcessors } = BrowserTracing.options; + + // if beforeNavigate returns undefined, we should not start a transaction. + const name = beforeNavigate(global.location); + if (name === undefined) { + return undefined; + } + + let context: TransactionContext = { name, op }; + if (routingInstrumentationProcessors) { + for (const processor of routingInstrumentationProcessors) { + context = processor(context); + } + } + + const hub = BrowserTracing._getCurrentHub(); + BrowserTracing._log(`[Tracing] starting ${op} idleTransaction on scope with context:`, context); + const activeTransaction = startIdleTransaction(hub, context, idleTimeout, true); + + return activeTransaction; + } + + /** + * Uses logger.log to log things in the SDK or as breadcrumbs if defined in options + */ + private 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 + */ +export function getMetaContent(metaName: string): string | null { + const el = document.querySelector(`meta[name=${metaName}]`); + return el ? el.getAttribute('content') : null; +} diff --git a/packages/tracing/src/hubextensions.ts b/packages/tracing/src/hubextensions.ts index 313ee8c81119..dfc5ebe5e4a5 100644 --- a/packages/tracing/src/hubextensions.ts +++ b/packages/tracing/src/hubextensions.ts @@ -53,13 +53,13 @@ function startTransaction(this: Hub, context: TransactionContext): Transaction { * Create new idle transaction. */ export function startIdleTransaction( - this: Hub, + hub: Hub, context: TransactionContext, idleTimeout?: number, onScope?: boolean, ): IdleTransaction { - const transaction = new IdleTransaction(context, this, idleTimeout, onScope); - return sample(this, transaction); + const transaction = new IdleTransaction(context, hub, idleTimeout, onScope); + return sample(hub, transaction); } /** diff --git a/packages/tracing/src/idletransaction.ts b/packages/tracing/src/idletransaction.ts index 5ba230f5a12d..6e31b140aca6 100644 --- a/packages/tracing/src/idletransaction.ts +++ b/packages/tracing/src/idletransaction.ts @@ -7,7 +7,7 @@ import { Span } from './span'; import { SpanStatus } from './spanstatus'; import { SpanRecorder, Transaction } from './transaction'; -const DEFAULT_IDLE_TIMEOUT = 1000; +export const DEFAULT_IDLE_TIMEOUT = 1000; /** * @inheritDoc @@ -138,7 +138,7 @@ export class IdleTransaction extends Transaction { /** * Finish the current active idle transaction */ - public finishIdleTransaction(endTimestamp: number): void { + public finishIdleTransaction(endTimestamp: number = timestampWithMs()): void { if (this.spanRecorder) { logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); diff --git a/packages/tracing/src/index.ts b/packages/tracing/src/index.ts index 9f59e3515f40..c47c25f1520b 100644 --- a/packages/tracing/src/index.ts +++ b/packages/tracing/src/index.ts @@ -1,7 +1,11 @@ +import { BrowserTracing } from './browser/browsertracing'; import { addExtensionMethods } from './hubextensions'; import * as ApmIntegrations from './integrations'; -export { ApmIntegrations as Integrations }; +// tslint:disable-next-line: variable-name +const Integrations = { ...ApmIntegrations, BrowserTracing }; + +export { Integrations }; export { Span, TRACEPARENT_REGEXP } from './span'; export { Transaction } from './transaction'; diff --git a/packages/tracing/src/integrations/tracing.ts b/packages/tracing/src/integrations/tracing.ts index 59451647569f..d4496e53e108 100644 --- a/packages/tracing/src/integrations/tracing.ts +++ b/packages/tracing/src/integrations/tracing.ts @@ -15,8 +15,7 @@ import { import { Span as SpanClass } from '../span'; import { SpanStatus } from '../spanstatus'; import { Transaction } from '../transaction'; - -import { Location } from './types'; +import { Location } from '../types'; /** * Options for Tracing integration diff --git a/packages/tracing/src/integrations/types.ts b/packages/tracing/src/types.ts similarity index 100% rename from packages/tracing/src/integrations/types.ts rename to packages/tracing/src/types.ts diff --git a/packages/tracing/test/browser/browsertracing.test.ts b/packages/tracing/test/browser/browsertracing.test.ts new file mode 100644 index 000000000000..50856df16330 --- /dev/null +++ b/packages/tracing/test/browser/browsertracing.test.ts @@ -0,0 +1,231 @@ +import { BrowserClient } from '@sentry/browser'; +import { Hub } from '@sentry/hub'; +// tslint:disable-next-line: no-implicit-dependencies +import { JSDOM } from 'jsdom'; + +import { BrowserTracing, BrowserTracingOptions, getMetaContent } from '../../src/browser/browsertracing'; +import { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../../src/idletransaction'; + +let mockChangeHistory: ({ to, from }: { to: string; from?: string }) => void = () => undefined; +let addInstrumentationHandlerType: string = ''; + +jest.mock('@sentry/utils', () => { + const actual = jest.requireActual('@sentry/utils'); + return { + ...actual, + addInstrumentationHandler: ({ callback, type }: any): void => { + addInstrumentationHandlerType = type; + mockChangeHistory = callback; + }, + }; +}); + +beforeAll(() => { + const dom = new JSDOM(); + // @ts-ignore + global.document = dom.window.document; + // @ts-ignore + global.window = dom.window; + // @ts-ignore + global.location = dom.window.location; +}); + +describe('BrowserTracing', () => { + let hub: Hub; + beforeEach(() => { + jest.useFakeTimers(); + hub = new Hub(new BrowserClient({ tracesSampleRate: 1 })); + }); + + afterEach(() => { + const transaction = getActiveTransaction(hub); + if (transaction) { + transaction.finishIdleTransaction(); + } + }); + + // tslint:disable-next-line: completed-docs + function createBrowserTracing(setup?: boolean, _options?: Partial): BrowserTracing { + const inst = new BrowserTracing(_options); + if (setup) { + const processor = () => undefined; + inst.setupOnce(processor, () => hub); + } + + return inst; + } + + // These are important enough to check with a test as incorrect defaults could + // break a lot of users configurations. + it('is created with default settings', () => { + createBrowserTracing(); + + expect(BrowserTracing.options).toEqual({ + beforeNavigate: expect.any(Function), + debug: { + writeAsBreadcrumbs: false, + }, + idleTimeout: DEFAULT_IDLE_TIMEOUT, + routingInstrumentationProcessors: [], + startTransactionOnLocationChange: true, + startTransactionOnPageLoad: true, + }); + }); + + describe('routing instrumentation', () => { + it('is setup with default processors', () => { + createBrowserTracing(true); + expect(BrowserTracing.options.routingInstrumentationProcessors).toHaveLength(1); + }); + + // We can test creating a route transaction with either navigation + // or pageload, but for simplicities case, we check by creating a + // pageload transaction. + // Testing `BrowserTracing._createRouteTransaction()` functionality + describe('route transaction', () => { + it('calls beforeNavigate on transaction creation', () => { + const mockBeforeNavigation = jest.fn().mockReturnValue('here/is/my/path'); + createBrowserTracing(true, { beforeNavigate: mockBeforeNavigation }); + const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(transaction).toBeDefined(); + + expect(mockBeforeNavigation).toHaveBeenCalledTimes(1); + }); + + it('is not created if beforeNavigate returns undefined', () => { + const mockBeforeNavigation = jest.fn().mockReturnValue(undefined); + createBrowserTracing(true, { beforeNavigate: mockBeforeNavigation }); + const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(transaction).not.toBeDefined(); + + expect(mockBeforeNavigation).toHaveBeenCalledTimes(1); + }); + + it('sets transaction context from sentry-trace header', () => { + const name = 'sentry-trace'; + const content = '126de09502ae4e0fb26c6967190756a4-b6e54397b12a2a0f-1'; + document.head.innerHTML = ``; + createBrowserTracing(true); + const transaction = getActiveTransaction(hub) as IdleTransaction; + + expect(transaction.traceId).toBe('126de09502ae4e0fb26c6967190756a4'); + expect(transaction.parentSpanId).toBe('b6e54397b12a2a0f'); + expect(transaction.sampled).toBe(true); + }); + + it('is created with a default idleTimeout', () => { + createBrowserTracing(true); + const mockFinish = jest.fn(); + const transaction = getActiveTransaction(hub) as IdleTransaction; + transaction.finish = mockFinish; + + const span = transaction.startChild(); // activities = 1 + span.finish(); // activities = 0 + + expect(mockFinish).toHaveBeenCalledTimes(0); + jest.advanceTimersByTime(DEFAULT_IDLE_TIMEOUT); + expect(mockFinish).toHaveBeenCalledTimes(1); + }); + + it('can be created with a custom idleTimeout', () => { + createBrowserTracing(true, { idleTimeout: 2000 }); + const mockFinish = jest.fn(); + const transaction = getActiveTransaction(hub) as IdleTransaction; + transaction.finish = mockFinish; + + const span = transaction.startChild(); // activities = 1 + span.finish(); // activities = 0 + + expect(mockFinish).toHaveBeenCalledTimes(0); + jest.advanceTimersByTime(2000); + expect(mockFinish).toHaveBeenCalledTimes(1); + }); + }); + + describe('pageload transaction', () => { + it('is created on setup on scope', () => { + createBrowserTracing(true); + const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(transaction).toBeDefined(); + + expect(transaction.op).toBe('pageload'); + }); + + it('is not created if the option is false', () => { + createBrowserTracing(true, { startTransactionOnPageLoad: false }); + const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(transaction).not.toBeDefined(); + }); + }); + + // TODO: This needs integration testing + describe('navigation transaction', () => { + beforeEach(() => { + mockChangeHistory = () => undefined; + addInstrumentationHandlerType = ''; + }); + + it('it is not created automatically', () => { + createBrowserTracing(true); + jest.runAllTimers(); + + const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(transaction).not.toBeDefined(); + }); + + it('is created on location change', () => { + createBrowserTracing(true); + const transaction1 = getActiveTransaction(hub) as IdleTransaction; + expect(transaction1.op).toBe('pageload'); + expect(transaction1.endTimestamp).not.toBeDefined(); + + mockChangeHistory({ to: 'here', from: 'there' }); + expect(addInstrumentationHandlerType).toBe('history'); + const transaction2 = getActiveTransaction(hub) as IdleTransaction; + expect(transaction2.op).toBe('navigation'); + + expect(transaction1.endTimestamp).toBeDefined(); + }); + + it('is not created if startTransactionOnLocationChange is false', () => { + createBrowserTracing(true, { startTransactionOnLocationChange: false }); + const transaction1 = getActiveTransaction(hub) as IdleTransaction; + expect(transaction1.op).toBe('pageload'); + expect(transaction1.endTimestamp).not.toBeDefined(); + + mockChangeHistory({ to: 'here', from: 'there' }); + expect(addInstrumentationHandlerType).toBe('history'); + const transaction2 = getActiveTransaction(hub) as IdleTransaction; + expect(transaction2.op).toBe('pageload'); + }); + }); + }); +}); + +describe('getMeta', () => { + it('returns a found meta tag contents', () => { + const name = 'sentry-trace'; + const content = '126de09502ae4e0fb26c6967190756a4-b6e54397b12a2a0f-1'; + document.head.innerHTML = ``; + + const meta = getMetaContent(name); + expect(meta).toBe(content); + }); + + it('only returns meta tags queried for', () => { + document.head.innerHTML = ``; + + const meta = getMetaContent('test'); + expect(meta).toBe(null); + }); +}); + +/** Get active transaction from scope */ +function getActiveTransaction(hub: Hub): IdleTransaction | undefined { + const scope = hub.getScope(); + if (scope) { + return scope.getTransaction() as IdleTransaction; + } + + return undefined; +} diff --git a/yarn.lock b/yarn.lock index 817f8fc23dc6..e5e78067be6f 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1397,6 +1397,15 @@ dependencies: "@types/jest-diff" "*" +"@types/jsdom@^16.2.3": + version "16.2.3" + resolved "https://registry.yarnpkg.com/@types/jsdom/-/jsdom-16.2.3.tgz#c6feadfe0836389b27f9c911cde82cd32e91c537" + integrity sha512-BREatezSn74rmLIDksuqGNFUTi9HNAWWQXYpFBFLK9U6wlMCO4M0QCa8CMpDsZQuqxSO9XifVLT5Q1P0vgKLqw== + dependencies: + "@types/node" "*" + "@types/parse5" "*" + "@types/tough-cookie" "*" + "@types/lodash@^4.14.110": version "4.14.121" resolved "https://registry.yarnpkg.com/@types/lodash/-/lodash-4.14.121.tgz#9327e20d49b95fc2bf983fc2f045b2c6effc80b9" @@ -1444,6 +1453,11 @@ resolved "https://registry.yarnpkg.com/@types/node/-/node-11.13.7.tgz#85dbb71c510442d00c0631f99dae957ce44fd104" integrity sha512-suFHr6hcA9mp8vFrZTgrmqW2ZU3mbWsryQtQlY/QvwTISCw7nw/j+bCQPPohqmskhmqa5wLNuMHTTsc+xf1MQg== +"@types/parse5@*": + version "5.0.3" + resolved "https://registry.yarnpkg.com/@types/parse5/-/parse5-5.0.3.tgz#e7b5aebbac150f8b5fdd4a46e7f0bd8e65e19109" + integrity sha512-kUNnecmtkunAoQ3CnjmMkzNU/gtxG8guhi+Fk2U/kOpIKjIMKnXGp4IJCgQJrXSgMsWYimYG4TGjz/UzbGEBTw== + "@types/prop-types@*": version "15.7.3" resolved "https://registry.yarnpkg.com/@types/prop-types/-/prop-types-15.7.3.tgz#2ab0d5da2e5815f94b0b9d4b95d1e5f243ab2ca7" @@ -1833,11 +1847,32 @@ after@0.8.2: version "0.8.2" resolved "https://registry.yarnpkg.com/after/-/after-0.8.2.tgz#fedb394f9f0e02aa9768e702bda23b505fae7e1f" -agent-base@4, agent-base@5, agent-base@6, agent-base@^4.3.0, agent-base@~4.2.0: +agent-base@4, agent-base@^4.3.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-4.3.0.tgz#8165f01c436009bccad0b1d122f05ed770efc6ee" + integrity sha512-salcGninV0nPrwpGNn4VTXBb1SOuXQBiqbrNXoeizJsHrsL6ERFM2Ne3JUSBWRE6aeNJI2ROP/WEEIDUiDe3cg== + dependencies: + es6-promisify "^5.0.0" + +agent-base@5: version "5.1.1" resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-5.1.1.tgz#e8fb3f242959db44d63be665db7a8e739537a32c" integrity sha512-TMeqbNl2fMW0nMjTEPOwe3J/PRFP4vqeoNuQMG0HlMrtm5QxKqdvAkZ1pRBQ/ulIyDD5Yq0nJ7YbdD8ey0TO3g== +agent-base@6: + version "6.0.1" + resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-6.0.1.tgz#808007e4e5867decb0ab6ab2f928fbdb5a596db4" + integrity sha512-01q25QQDwLSsyfhrKbn8yuur+JNw0H+0Y4JiGIKd3z9aYk/w/2kxD/Upc+t2ZBBSUNff50VjPsSW2YxM8QYKVg== + dependencies: + debug "4" + +agent-base@~4.2.0: + version "4.2.1" + resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-4.2.1.tgz#d89e5999f797875674c07d87f260fc41e83e8ca9" + integrity sha512-JVwXMr9nHYTUXsBFKUqhJwvlcYU/blreOEUkhNR2eXZIvwd+c+o5V4MgDPKWnMS/56awN3TRzIP+KoPn+roQtg== + dependencies: + es6-promisify "^5.0.0" + agentkeepalive@^3.4.1: version "3.5.2" resolved "https://registry.yarnpkg.com/agentkeepalive/-/agentkeepalive-3.5.2.tgz#a113924dd3fa24a0bc3b78108c450c2abee00f67" @@ -4598,6 +4633,18 @@ es-to-primitive@^1.1.1, es-to-primitive@^1.2.0: is-date-object "^1.0.1" is-symbol "^1.0.2" +es6-promise@^4.0.3: + version "4.2.8" + resolved "https://registry.yarnpkg.com/es6-promise/-/es6-promise-4.2.8.tgz#4eb21594c972bc40553d276e510539143db53e0a" + integrity sha512-HJDGx5daxeIvxdBxvG2cb9g4tEvwIk3i8+nhX0yGrYmZUzbkdg8QbDevheDB8gd0//uPj4c1EQua8Q+MViT0/w== + +es6-promisify@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/es6-promisify/-/es6-promisify-5.0.0.tgz#5109d62f3e56ea967c4b63505aef08291c8a5203" + integrity sha1-UQnWLz5W6pZ8S2NQWu8IKRyKUgM= + dependencies: + es6-promise "^4.0.3" + escape-html@~1.0.3: version "1.0.3" resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" From 9418bf010732fe973a393cf7d8736f02237dd579 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Mon, 6 Jul 2020 20:19:17 -0400 Subject: [PATCH 3/7] fix: defaultRoutingInstrumentation --- .../tracing/src/browser/browsertracing.ts | 23 +++++++++++++++---- 1 file changed, 18 insertions(+), 5 deletions(-) diff --git a/packages/tracing/src/browser/browsertracing.ts b/packages/tracing/src/browser/browsertracing.ts index 66f630c7dd87..129915cdc763 100644 --- a/packages/tracing/src/browser/browsertracing.ts +++ b/packages/tracing/src/browser/browsertracing.ts @@ -85,6 +85,13 @@ export interface BrowserTracingOptions { // TODO: Should this be an option, or a static class variable and passed // in and we use something like `BrowserTracing.addRoutingProcessor()` routingInstrumentationProcessors: routingInstrumentationProcessor[]; + + /** + * Flag to enable default routing instrumentation. + * + * Default: true + */ + defaultRoutingInstrumentation: boolean; } /** @@ -120,6 +127,7 @@ export class BrowserTracing implements Integration { debug: { writeAsBreadcrumbs: false, }, + defaultRoutingInstrumentation: true, idleTimeout: DEFAULT_IDLE_TIMEOUT, routingInstrumentationProcessors: [], startTransactionOnLocationChange: true, @@ -143,7 +151,9 @@ export class BrowserTracing implements Integration { // TODO: is it fine that this is mutable operation? Could also do = [...routingInstr, setHeaderContext]? BrowserTracing.options.routingInstrumentationProcessors.push(setHeaderContext); - BrowserTracing._initRoutingInstrumentation(); + if (BrowserTracing.options.defaultRoutingInstrumentation) { + BrowserTracing._initRoutingInstrumentation(); + } } /** Start routing instrumentation */ @@ -151,7 +161,7 @@ export class BrowserTracing implements Integration { const { startTransactionOnPageLoad, startTransactionOnLocationChange } = BrowserTracing.options; if (startTransactionOnPageLoad) { - BrowserTracing._activeTransaction = BrowserTracing._createRouteTransaction('pageload'); + BrowserTracing._activeTransaction = BrowserTracing.createRouteTransaction('pageload'); } let startingUrl: string | undefined = global.location.href; @@ -178,7 +188,7 @@ export class BrowserTracing implements Integration { // are navigating to a new page. BrowserTracing._activeTransaction.finishIdleTransaction(); } - BrowserTracing._activeTransaction = BrowserTracing._createRouteTransaction('navigation'); + BrowserTracing._activeTransaction = BrowserTracing.createRouteTransaction('navigation'); } }, type: 'history', @@ -186,7 +196,10 @@ export class BrowserTracing implements Integration { } /** Create pageload/navigation idle transaction. */ - private static _createRouteTransaction(op: 'pageload' | 'navigation'): IdleTransaction | undefined { + public static createRouteTransaction( + op: 'pageload' | 'navigation', + ctx?: TransactionContext, + ): IdleTransaction | undefined { if (!BrowserTracing._getCurrentHub) { return undefined; } @@ -199,7 +212,7 @@ export class BrowserTracing implements Integration { return undefined; } - let context: TransactionContext = { name, op }; + let context: TransactionContext = { name, op, ...ctx }; if (routingInstrumentationProcessors) { for (const processor of routingInstrumentationProcessors) { context = processor(context); From 68ee001a25236a9bd9ce9bb9d488acd3e46f70c0 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Tue, 7 Jul 2020 11:40:09 -0400 Subject: [PATCH 4/7] ref: Remove static methods --- .../tracing/src/browser/browsertracing.ts | 116 +++++++++--------- .../test/browser/browsertracing.test.ts | 9 ++ packages/tracing/test/hub.test.ts | 49 +------- 3 files changed, 68 insertions(+), 106 deletions(-) diff --git a/packages/tracing/src/browser/browsertracing.ts b/packages/tracing/src/browser/browsertracing.ts index 129915cdc763..3d1536124e92 100644 --- a/packages/tracing/src/browser/browsertracing.ts +++ b/packages/tracing/src/browser/browsertracing.ts @@ -85,13 +85,6 @@ export interface BrowserTracingOptions { // TODO: Should this be an option, or a static class variable and passed // in and we use something like `BrowserTracing.addRoutingProcessor()` routingInstrumentationProcessors: routingInstrumentationProcessor[]; - - /** - * Flag to enable default routing instrumentation. - * - * Default: true - */ - defaultRoutingInstrumentation: boolean; } /** @@ -108,33 +101,31 @@ export class BrowserTracing implements Integration { public static id: string = 'BrowserTracing'; /** Browser Tracing integration options */ - public static options: BrowserTracingOptions; + public options: BrowserTracingOptions = { + beforeNavigate(location: LocationType): string | undefined { + return location.pathname; + }, + debug: { + writeAsBreadcrumbs: false, + }, + idleTimeout: DEFAULT_IDLE_TIMEOUT, + routingInstrumentationProcessors: [], + startTransactionOnLocationChange: true, + startTransactionOnPageLoad: true, + }; /** * @inheritDoc */ public name: string = BrowserTracing.id; - private static _activeTransaction?: IdleTransaction; + private _activeTransaction?: IdleTransaction; - private static _getCurrentHub?: () => Hub; + private _getCurrentHub?: () => Hub; public constructor(_options?: Partial) { - const defaults: BrowserTracingOptions = { - beforeNavigate(location: LocationType): string | undefined { - return location.pathname; - }, - debug: { - writeAsBreadcrumbs: false, - }, - defaultRoutingInstrumentation: true, - idleTimeout: DEFAULT_IDLE_TIMEOUT, - routingInstrumentationProcessors: [], - startTransactionOnLocationChange: true, - startTransactionOnPageLoad: true, - }; - BrowserTracing.options = { - ...defaults, + this.options = { + ...this.options, ..._options, }; } @@ -143,25 +134,24 @@ export class BrowserTracing implements Integration { * @inheritDoc */ public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { - BrowserTracing._getCurrentHub = getCurrentHub; + this._getCurrentHub = getCurrentHub; if (!global || !global.location) { return; } - // TODO: is it fine that this is mutable operation? Could also do = [...routingInstr, setHeaderContext]? - BrowserTracing.options.routingInstrumentationProcessors.push(setHeaderContext); - if (BrowserTracing.options.defaultRoutingInstrumentation) { - BrowserTracing._initRoutingInstrumentation(); - } + this._initRoutingInstrumentation(); } /** Start routing instrumentation */ - private static _initRoutingInstrumentation(): void { - const { startTransactionOnPageLoad, startTransactionOnLocationChange } = BrowserTracing.options; + private _initRoutingInstrumentation(): void { + const { startTransactionOnPageLoad, startTransactionOnLocationChange } = this.options; + + // TODO: is it fine that this is mutable operation? Could also do = [...routingInstr, setHeaderContext]? + this.options.routingInstrumentationProcessors.push(setHeaderContext); if (startTransactionOnPageLoad) { - BrowserTracing._activeTransaction = BrowserTracing.createRouteTransaction('pageload'); + this._activeTransaction = this._createRouteTransaction('pageload'); } let startingUrl: string | undefined = global.location.href; @@ -170,8 +160,8 @@ export class BrowserTracing implements Integration { callback: ({ to, from }: { to: string; from?: string }) => { /** * This early return is there to account for some cases where navigation transaction - * starts right after long running pageload. We make sure that if from is undefined - * and that a valid startingURL exists, we don't uncessarily create a navigation transaction. + * starts right after long running pageload. We make sure that if `from` is undefined + * and that a valid `startingURL` exists, we don't uncessarily create a navigation transaction. * * This was hard to duplicate, but this behaviour stopped as soon as this fix * was applied. This issue might also only be caused in certain development environments @@ -183,12 +173,12 @@ export class BrowserTracing implements Integration { } if (startTransactionOnLocationChange && from !== to) { startingUrl = undefined; - if (BrowserTracing._activeTransaction) { + if (this._activeTransaction) { // We want to finish all current ongoing idle transactions as we // are navigating to a new page. - BrowserTracing._activeTransaction.finishIdleTransaction(); + this._activeTransaction.finishIdleTransaction(); } - BrowserTracing._activeTransaction = BrowserTracing.createRouteTransaction('navigation'); + this._activeTransaction = this._createRouteTransaction('navigation'); } }, type: 'history', @@ -196,32 +186,28 @@ export class BrowserTracing implements Integration { } /** Create pageload/navigation idle transaction. */ - public static createRouteTransaction( + private _createRouteTransaction( op: 'pageload' | 'navigation', - ctx?: TransactionContext, + context?: TransactionContext, ): IdleTransaction | undefined { - if (!BrowserTracing._getCurrentHub) { + if (!this._getCurrentHub) { return undefined; } - const { beforeNavigate, idleTimeout, routingInstrumentationProcessors } = BrowserTracing.options; + const { beforeNavigate, idleTimeout, routingInstrumentationProcessors } = this.options; // if beforeNavigate returns undefined, we should not start a transaction. const name = beforeNavigate(global.location); if (name === undefined) { + this._log(`[Tracing] Cancelling ${op} idleTransaction due to beforeNavigate:`); return undefined; } - let context: TransactionContext = { name, op, ...ctx }; - if (routingInstrumentationProcessors) { - for (const processor of routingInstrumentationProcessors) { - context = processor(context); - } - } + const ctx = createContextFromProcessors({ name, op, ...context }, routingInstrumentationProcessors); - const hub = BrowserTracing._getCurrentHub(); - BrowserTracing._log(`[Tracing] starting ${op} idleTransaction on scope with context:`, context); - const activeTransaction = startIdleTransaction(hub, context, idleTimeout, true); + const hub = this._getCurrentHub(); + this._log(`[Tracing] starting ${op} idleTransaction on scope with context:`, ctx); + const activeTransaction = startIdleTransaction(hub, ctx, idleTimeout, true); return activeTransaction; } @@ -229,9 +215,9 @@ export class BrowserTracing implements Integration { /** * Uses logger.log to log things in the SDK or as breadcrumbs if defined in options */ - private static _log(...args: any[]): void { - if (BrowserTracing.options && BrowserTracing.options.debug && BrowserTracing.options.debug.writeAsBreadcrumbs) { - const _getCurrentHub = BrowserTracing._getCurrentHub; + private _log(...args: any[]): void { + if (this.options && this.options.debug && this.options.debug.writeAsBreadcrumbs) { + const _getCurrentHub = this._getCurrentHub; if (_getCurrentHub) { _getCurrentHub().addBreadcrumb({ category: 'tracing', @@ -245,9 +231,23 @@ export class BrowserTracing implements Integration { } } -/** - * Returns the value of a meta tag - */ +/** Creates transaction context from a set of processors */ +export function createContextFromProcessors( + context: TransactionContext, + processors: routingInstrumentationProcessor[], +): TransactionContext { + let ctx = context; + for (const processor of processors) { + const newContext = processor(context); + if (newContext && newContext.name && newContext.op) { + ctx = newContext; + } + } + + return ctx; +} + +/** Returns the value of a meta tag */ export function getMetaContent(metaName: string): string | null { const el = document.querySelector(`meta[name=${metaName}]`); return el ? el.getAttribute('content') : null; diff --git a/packages/tracing/test/browser/browsertracing.test.ts b/packages/tracing/test/browser/browsertracing.test.ts index 50856df16330..0ec93aaa5bd5 100644 --- a/packages/tracing/test/browser/browsertracing.test.ts +++ b/packages/tracing/test/browser/browsertracing.test.ts @@ -113,6 +113,15 @@ describe('BrowserTracing', () => { expect(transaction.sampled).toBe(true); }); + it('uses a custom routing instrumentation processor', () => { + createBrowserTracing(true, { routingInstrumentationProcessors: [] }); + const transaction = getActiveTransaction(hub) as IdleTransaction; + + expect(transaction.traceId).toBe('126de09502ae4e0fb26c6967190756a4'); + expect(transaction.parentSpanId).toBe('b6e54397b12a2a0f'); + expect(transaction.sampled).toBe(true); + }); + it('is created with a default idleTimeout', () => { createBrowserTracing(true); const mockFinish = jest.fn(); diff --git a/packages/tracing/test/hub.test.ts b/packages/tracing/test/hub.test.ts index e24f1fc6638d..a1c06b789380 100644 --- a/packages/tracing/test/hub.test.ts +++ b/packages/tracing/test/hub.test.ts @@ -1,5 +1,5 @@ import { BrowserClient } from '@sentry/browser'; -import { Hub, Scope } from '@sentry/hub'; +import { Hub } from '@sentry/hub'; import { addExtensionMethods } from '../src/hubextensions'; @@ -57,51 +57,4 @@ describe('Hub', () => { expect(child.sampled).toBeFalsy(); }); }); - - describe('startSpan', () => { - test('simple standalone Span', () => { - const hub = new Hub(new BrowserClient()); - const span = hub.startSpan({}) as any; - expect(span.spanId).toBeTruthy(); - }); - - test('simple standalone Transaction', () => { - const hub = new Hub(new BrowserClient({ tracesSampleRate: 1 })); - const transaction = hub.startTransaction({ name: 'transaction' }); - expect(transaction.spanId).toBeTruthy(); - // tslint:disable-next-line: no-unbound-method - expect(transaction.setName).toBeTruthy(); - }); - - test('Transaction inherits trace_id from span on scope', () => { - const myScope = new Scope(); - const hub = new Hub(new BrowserClient(), myScope); - const parentSpan = hub.startSpan({}) as any; - hub.configureScope(scope => { - scope.setSpan(parentSpan); - }); - // @ts-ignore - const span = hub.startSpan({ name: 'test' }) as any; - expect(span.trace_id).toEqual(parentSpan.trace_id); - }); - - test('create a child if there is a Span already on the scope', () => { - const myScope = new Scope(); - const hub = new Hub(new BrowserClient({ tracesSampleRate: 1 }), myScope); - const transaction = hub.startTransaction({ name: 'transaction' }); - hub.configureScope(scope => { - scope.setSpan(transaction); - }); - const span = hub.startSpan({}); - expect(span.traceId).toEqual(transaction.traceId); - expect(span.parentSpanId).toEqual(transaction.spanId); - hub.configureScope(scope => { - scope.setSpan(span); - }); - const span2 = hub.startSpan({}); - expect(span2.traceId).toEqual(span.traceId); - expect(span2.parentSpanId).toEqual(span.spanId); - }); - }); - }); }); From 27f9d0a5515915b7e9c2d16caecac22795ff1444 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Wed, 8 Jul 2020 08:17:34 -0400 Subject: [PATCH 5/7] multiple before finishes --- packages/tracing/src/browser/browsertracing.ts | 3 +++ packages/tracing/src/idletransaction.ts | 12 +++++++----- packages/tracing/test/hub.test.ts | 1 + packages/tracing/test/idletransaction.test.ts | 15 ++++++++++----- 4 files changed, 21 insertions(+), 10 deletions(-) diff --git a/packages/tracing/src/browser/browsertracing.ts b/packages/tracing/src/browser/browsertracing.ts index 3d1536124e92..5c5f4529c4ab 100644 --- a/packages/tracing/src/browser/browsertracing.ts +++ b/packages/tracing/src/browser/browsertracing.ts @@ -123,6 +123,8 @@ export class BrowserTracing implements Integration { private _getCurrentHub?: () => Hub; + // navigationTransactionInvoker() -> Uses history API NavigationTransaction[] + public constructor(_options?: Partial) { this.options = { ...this.options, @@ -156,6 +158,7 @@ export class BrowserTracing implements Integration { let startingUrl: string | undefined = global.location.href; + // Could this be the one that changes? addInstrumentationHandler({ callback: ({ to, from }: { to: string; from?: string }) => { /** diff --git a/packages/tracing/src/idletransaction.ts b/packages/tracing/src/idletransaction.ts index 6e31b140aca6..c05127bb555a 100644 --- a/packages/tracing/src/idletransaction.ts +++ b/packages/tracing/src/idletransaction.ts @@ -45,6 +45,8 @@ export class IdleTransactionSpanRecorder extends SpanRecorder { } } +export type BeforeFinishCallback = (transactionSpan: IdleTransaction) => void; + /** * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities. * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will @@ -66,7 +68,7 @@ export class IdleTransaction extends Transaction { // We should not use heartbeat if we finished a transaction private _finished: boolean = false; - private _finishCallback?: (transactionSpan: IdleTransaction) => void; + private readonly _beforeFinishCallbacks: BeforeFinishCallback[] = []; public constructor( transactionContext: TransactionContext, @@ -142,8 +144,8 @@ export class IdleTransaction extends Transaction { if (this.spanRecorder) { logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); - if (this._finishCallback) { - this._finishCallback(this); + for (const callback of this._beforeFinishCallbacks) { + callback(this); } this.spanRecorder.spans = this.spanRecorder.spans.filter((span: Span) => { @@ -224,8 +226,8 @@ export class IdleTransaction extends Transaction { * This is exposed because users have no other way of running something before an idle transaction * finishes. */ - public beforeFinish(callback: (transactionSpan: IdleTransaction) => void): void { - this._finishCallback = callback; + public registerBeforeFinishCallback(callback: BeforeFinishCallback): void { + this._beforeFinishCallbacks.push(callback); } /** diff --git a/packages/tracing/test/hub.test.ts b/packages/tracing/test/hub.test.ts index a1c06b789380..2672bbf03c27 100644 --- a/packages/tracing/test/hub.test.ts +++ b/packages/tracing/test/hub.test.ts @@ -57,4 +57,5 @@ describe('Hub', () => { expect(child.sampled).toBeFalsy(); }); }); + }); }); diff --git a/packages/tracing/test/idletransaction.test.ts b/packages/tracing/test/idletransaction.test.ts index 72b2418b7f29..8d045576c0b2 100644 --- a/packages/tracing/test/idletransaction.test.ts +++ b/packages/tracing/test/idletransaction.test.ts @@ -95,19 +95,24 @@ describe('IdleTransaction', () => { }); it('calls beforeFinish callback before finishing', () => { - const mockCallback = jest.fn(); + const mockCallback1 = jest.fn(); + const mockCallback2 = jest.fn(); const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); transaction.initSpanRecorder(10); - transaction.beforeFinish(mockCallback); + transaction.registerBeforeFinishCallback(mockCallback1); + transaction.registerBeforeFinishCallback(mockCallback2); - expect(mockCallback).toHaveBeenCalledTimes(0); + expect(mockCallback1).toHaveBeenCalledTimes(0); + expect(mockCallback2).toHaveBeenCalledTimes(0); const span = transaction.startChild(); span.finish(); jest.runOnlyPendingTimers(); - expect(mockCallback).toHaveBeenCalledTimes(1); - expect(mockCallback).toHaveBeenLastCalledWith(transaction); + expect(mockCallback1).toHaveBeenCalledTimes(1); + expect(mockCallback1).toHaveBeenLastCalledWith(transaction); + expect(mockCallback2).toHaveBeenCalledTimes(1); + expect(mockCallback2).toHaveBeenLastCalledWith(transaction); }); it('filters spans on finish', () => { From c8612c190cc6da8e86334ff1351b9981723481e7 Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Wed, 8 Jul 2020 12:55:51 -0400 Subject: [PATCH 6/7] ref: Routing Instrumentation --- .../tracing/src/browser/browsertracing.ts | 194 +++++------------- packages/tracing/src/browser/router.ts | 61 ++++++ packages/tracing/src/idletransaction.ts | 13 +- packages/tracing/src/types.ts | 109 ---------- .../test/browser/browsertracing.test.ts | 162 ++++++++------- packages/tracing/test/browser/router.test.ts | 117 +++++++++++ packages/tracing/test/hub.test.ts | 5 - packages/tracing/test/idletransaction.test.ts | 18 +- 8 files changed, 324 insertions(+), 355 deletions(-) create mode 100644 packages/tracing/src/browser/router.ts delete mode 100644 packages/tracing/src/types.ts create mode 100644 packages/tracing/test/browser/router.test.ts diff --git a/packages/tracing/src/browser/browsertracing.ts b/packages/tracing/src/browser/browsertracing.ts index 5c5f4529c4ab..7df8900a6d23 100644 --- a/packages/tracing/src/browser/browsertracing.ts +++ b/packages/tracing/src/browser/browsertracing.ts @@ -1,52 +1,15 @@ import { Hub } from '@sentry/hub'; -import { EventProcessor, Integration, Severity, TransactionContext } from '@sentry/types'; -import { addInstrumentationHandler, getGlobalObject, logger, safeJoin } from '@sentry/utils'; +import { EventProcessor, Integration, Transaction as TransactionType, TransactionContext } from '@sentry/types'; +import { logger } from '@sentry/utils'; import { startIdleTransaction } from '../hubextensions'; -import { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../idletransaction'; +import { DEFAULT_IDLE_TIMEOUT } from '../idletransaction'; import { Span } from '../span'; -import { Location as LocationType } from '../types'; -const global = getGlobalObject(); - -type routingInstrumentationProcessor = (context: TransactionContext) => TransactionContext; - -/** - * Gets transaction context from a sentry-trace meta. - */ -const setHeaderContext: routingInstrumentationProcessor = ctx => { - const header = getMetaContent('sentry-trace'); - if (header) { - const span = Span.fromTraceparent(header); - if (span) { - return { - ...ctx, - parentSpanId: span.parentSpanId, - sampled: span.sampled, - traceId: span.traceId, - }; - } - } - - return ctx; -}; +import { defaultRoutingInstrumentation, defaultBeforeNavigate } from './router'; /** Options for Browser Tracing integration */ export interface BrowserTracingOptions { - /** - * 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. - * - * Default: { - * writeAsBreadcrumbs: false; - * } - */ - debug: { - writeAsBreadcrumbs: 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. @@ -76,15 +39,17 @@ export interface BrowserTracingOptions { * * If undefined is returned, a pageload/navigation transaction will not be created. */ - beforeNavigate(location: LocationType): string | undefined; + beforeNavigate(context: TransactionContext): TransactionContext | undefined; /** - * Set to adjust transaction context before creation of transaction. Useful to set name/data/tags before - * a transaction is sent. This option should be used by routing libraries to set context on transactions. + * Instrumentation that creates routing change transactions. By default creates + * pageload and navigation transactions. */ - // TODO: Should this be an option, or a static class variable and passed - // in and we use something like `BrowserTracing.addRoutingProcessor()` - routingInstrumentationProcessors: routingInstrumentationProcessor[]; + routingInstrumentation( + startTransaction: (context: TransactionContext) => T | undefined, + startTransactionOnPageLoad?: boolean, + startTransactionOnLocationChange?: boolean, + ): void; } /** @@ -102,14 +67,9 @@ export class BrowserTracing implements Integration { /** Browser Tracing integration options */ public options: BrowserTracingOptions = { - beforeNavigate(location: LocationType): string | undefined { - return location.pathname; - }, - debug: { - writeAsBreadcrumbs: false, - }, + beforeNavigate: defaultBeforeNavigate, idleTimeout: DEFAULT_IDLE_TIMEOUT, - routingInstrumentationProcessors: [], + routingInstrumentation: defaultRoutingInstrumentation, startTransactionOnLocationChange: true, startTransactionOnPageLoad: true, }; @@ -119,8 +79,6 @@ export class BrowserTracing implements Integration { */ public name: string = BrowserTracing.id; - private _activeTransaction?: IdleTransaction; - private _getCurrentHub?: () => Hub; // navigationTransactionInvoker() -> Uses history API NavigationTransaction[] @@ -138,116 +96,58 @@ export class BrowserTracing implements Integration { public setupOnce(_: (callback: EventProcessor) => void, getCurrentHub: () => Hub): void { this._getCurrentHub = getCurrentHub; - if (!global || !global.location) { - return; - } + const { routingInstrumentation, startTransactionOnLocationChange, startTransactionOnPageLoad } = this.options; - this._initRoutingInstrumentation(); + routingInstrumentation( + (context: TransactionContext) => this._createRouteTransaction(context), + startTransactionOnPageLoad, + startTransactionOnLocationChange, + ); } - /** Start routing instrumentation */ - private _initRoutingInstrumentation(): void { - const { startTransactionOnPageLoad, startTransactionOnLocationChange } = this.options; - - // TODO: is it fine that this is mutable operation? Could also do = [...routingInstr, setHeaderContext]? - this.options.routingInstrumentationProcessors.push(setHeaderContext); - - if (startTransactionOnPageLoad) { - this._activeTransaction = this._createRouteTransaction('pageload'); - } - - let startingUrl: string | undefined = global.location.href; - - // Could this be the one that changes? - addInstrumentationHandler({ - callback: ({ to, from }: { to: string; from?: string }) => { - /** - * This early return is there to account for some cases where navigation transaction - * starts right after long running pageload. We make sure that if `from` is undefined - * and that a valid `startingURL` exists, we don't uncessarily create a navigation transaction. - * - * This was hard to duplicate, but this behaviour stopped as soon as this fix - * was applied. This issue might also only be caused in certain development environments - * where the usage of a hot module reloader is causing errors. - */ - if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) { - startingUrl = undefined; - return; - } - if (startTransactionOnLocationChange && from !== to) { - startingUrl = undefined; - if (this._activeTransaction) { - // We want to finish all current ongoing idle transactions as we - // are navigating to a new page. - this._activeTransaction.finishIdleTransaction(); - } - this._activeTransaction = this._createRouteTransaction('navigation'); - } - }, - type: 'history', - }); - } - - /** Create pageload/navigation idle transaction. */ - private _createRouteTransaction( - op: 'pageload' | 'navigation', - context?: TransactionContext, - ): IdleTransaction | undefined { + /** Create routing idle transaction. */ + private _createRouteTransaction(context: TransactionContext): TransactionType | undefined { if (!this._getCurrentHub) { + logger.warn(`[Tracing] Did not creeate ${context.op} idleTransaction due to invalid _getCurrentHub`); return undefined; } - const { beforeNavigate, idleTimeout, routingInstrumentationProcessors } = this.options; + const { beforeNavigate, idleTimeout } = this.options; // if beforeNavigate returns undefined, we should not start a transaction. - const name = beforeNavigate(global.location); - if (name === undefined) { - this._log(`[Tracing] Cancelling ${op} idleTransaction due to beforeNavigate:`); + const ctx = beforeNavigate({ + ...context, + ...getHeaderContext(), + }); + + if (ctx === undefined) { + logger.log(`[Tracing] Did not create ${context.op} idleTransaction due to beforeNavigate`); return undefined; } - const ctx = createContextFromProcessors({ name, op, ...context }, routingInstrumentationProcessors); - const hub = this._getCurrentHub(); - this._log(`[Tracing] starting ${op} idleTransaction on scope with context:`, ctx); - const activeTransaction = startIdleTransaction(hub, ctx, idleTimeout, true); - - return activeTransaction; - } - - /** - * Uses logger.log to log things in the SDK or as breadcrumbs if defined in options - */ - private _log(...args: any[]): void { - if (this.options && this.options.debug && this.options.debug.writeAsBreadcrumbs) { - const _getCurrentHub = this._getCurrentHub; - if (_getCurrentHub) { - _getCurrentHub().addBreadcrumb({ - category: 'tracing', - level: Severity.Debug, - message: safeJoin(args, ' '), - type: 'debug', - }); - } - } - logger.log(...args); + logger.log(`[Tracing] starting ${ctx.op} idleTransaction on scope with context:`, ctx); + return startIdleTransaction(hub, ctx, idleTimeout, true) as TransactionType; } } -/** Creates transaction context from a set of processors */ -export function createContextFromProcessors( - context: TransactionContext, - processors: routingInstrumentationProcessor[], -): TransactionContext { - let ctx = context; - for (const processor of processors) { - const newContext = processor(context); - if (newContext && newContext.name && newContext.op) { - ctx = newContext; +/** + * Gets transaction context from a sentry-trace meta. + */ +function getHeaderContext(): Partial { + const header = getMetaContent('sentry-trace'); + if (header) { + const span = Span.fromTraceparent(header); + if (span) { + return { + parentSpanId: span.parentSpanId, + sampled: span.sampled, + traceId: span.traceId, + }; } } - return ctx; + return {}; } /** Returns the value of a meta tag */ diff --git a/packages/tracing/src/browser/router.ts b/packages/tracing/src/browser/router.ts new file mode 100644 index 000000000000..6ce36eef5bd5 --- /dev/null +++ b/packages/tracing/src/browser/router.ts @@ -0,0 +1,61 @@ +import { Transaction as TransactionType, TransactionContext } from '@sentry/types'; +import { addInstrumentationHandler, getGlobalObject, logger } from '@sentry/utils'; + +// type StartTransaction +const global = getGlobalObject(); + +/** + * Creates a default router based on + */ +export function defaultRoutingInstrumentation( + startTransaction: (context: TransactionContext) => T | undefined, + startTransactionOnPageLoad: boolean = true, + startTransactionOnLocationChange: boolean = true, +): void { + if (!global || !global.location) { + logger.warn('Could not initialize routing instrumentation due to invalid location'); + return; + } + + let startingUrl: string | undefined = global.location.href; + + let activeTransaction: T | undefined; + if (startTransactionOnPageLoad) { + activeTransaction = startTransaction({ name: global.location.pathname, op: 'pageload' }); + } + + if (startTransactionOnLocationChange) { + addInstrumentationHandler({ + callback: ({ to, from }: { to: string; from?: string }) => { + /** + * This early return is there to account for some cases where navigation transaction + * starts right after long running pageload. We make sure that if `from` is undefined + * and that a valid `startingURL` exists, we don't uncessarily create a navigation transaction. + * + * This was hard to duplicate, but this behaviour stopped as soon as this fix + * was applied. This issue might also only be caused in certain development environments + * where the usage of a hot module reloader is causing errors. + */ + if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) { + startingUrl = undefined; + return; + } + if (from !== to) { + startingUrl = undefined; + if (activeTransaction) { + // We want to finish all current ongoing idle transactions as we + // are navigating to a new page. + activeTransaction.finish(); + } + activeTransaction = startTransaction({ name: global.location.pathname, op: 'navigation' }); + } + }, + type: 'history', + }); + } +} + +/** default implementation of Browser Tracing before navigate */ +export function defaultBeforeNavigate(context: TransactionContext): TransactionContext | undefined { + return context; +} diff --git a/packages/tracing/src/idletransaction.ts b/packages/tracing/src/idletransaction.ts index c05127bb555a..2b24549ddefe 100644 --- a/packages/tracing/src/idletransaction.ts +++ b/packages/tracing/src/idletransaction.ts @@ -121,7 +121,7 @@ export class IdleTransaction extends Transaction { ); this.setStatus(SpanStatus.DeadlineExceeded); this.setTag('heartbeat', 'failed'); - this.finishIdleTransaction(timestampWithMs()); + this.finish(); } else { this._pingHeartbeat(); } @@ -137,10 +137,8 @@ export class IdleTransaction extends Transaction { }, 5000) as any) as number; } - /** - * Finish the current active idle transaction - */ - public finishIdleTransaction(endTimestamp: number = timestampWithMs()): void { + /** {@inheritDoc} */ + public finish(endTimestamp: number = timestampWithMs()): string | undefined { if (this.spanRecorder) { logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); @@ -179,10 +177,11 @@ export class IdleTransaction extends Transaction { } logger.log('[Tracing] flushing IdleTransaction'); - this.finish(endTimestamp); } else { logger.log('[Tracing] No active IdleTransaction'); } + + return super.finish(endTimestamp); } /** @@ -214,7 +213,7 @@ export class IdleTransaction extends Transaction { const end = timestampWithMs() + timeout / 1000; setTimeout(() => { - this.finishIdleTransaction(end); + this.finish(end); }, timeout); } } diff --git a/packages/tracing/src/types.ts b/packages/tracing/src/types.ts deleted file mode 100644 index 331cbee7ba57..000000000000 --- a/packages/tracing/src/types.ts +++ /dev/null @@ -1,109 +0,0 @@ -/** - * 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/test/browser/browsertracing.test.ts b/packages/tracing/test/browser/browsertracing.test.ts index 0ec93aaa5bd5..effc6dcf8b5e 100644 --- a/packages/tracing/test/browser/browsertracing.test.ts +++ b/packages/tracing/test/browser/browsertracing.test.ts @@ -4,17 +4,15 @@ import { Hub } from '@sentry/hub'; import { JSDOM } from 'jsdom'; import { BrowserTracing, BrowserTracingOptions, getMetaContent } from '../../src/browser/browsertracing'; +import { defaultRoutingInstrumentation } from '../../src/browser/router'; import { DEFAULT_IDLE_TIMEOUT, IdleTransaction } from '../../src/idletransaction'; let mockChangeHistory: ({ to, from }: { to: string; from?: string }) => void = () => undefined; -let addInstrumentationHandlerType: string = ''; - jest.mock('@sentry/utils', () => { const actual = jest.requireActual('@sentry/utils'); return { ...actual, - addInstrumentationHandler: ({ callback, type }: any): void => { - addInstrumentationHandlerType = type; + addInstrumentationHandler: ({ callback }: any): void => { mockChangeHistory = callback; }, }; @@ -35,12 +33,13 @@ describe('BrowserTracing', () => { beforeEach(() => { jest.useFakeTimers(); hub = new Hub(new BrowserClient({ tracesSampleRate: 1 })); + document.head.innerHTML = ''; }); afterEach(() => { const transaction = getActiveTransaction(hub); if (transaction) { - transaction.finishIdleTransaction(); + transaction.finish(); } }); @@ -58,99 +57,116 @@ describe('BrowserTracing', () => { // These are important enough to check with a test as incorrect defaults could // break a lot of users configurations. it('is created with default settings', () => { - createBrowserTracing(); + const browserTracing = createBrowserTracing(); - expect(BrowserTracing.options).toEqual({ + expect(browserTracing.options).toEqual({ beforeNavigate: expect.any(Function), - debug: { - writeAsBreadcrumbs: false, - }, idleTimeout: DEFAULT_IDLE_TIMEOUT, - routingInstrumentationProcessors: [], + routingInstrumentation: defaultRoutingInstrumentation, startTransactionOnLocationChange: true, startTransactionOnPageLoad: true, }); }); - describe('routing instrumentation', () => { - it('is setup with default processors', () => { - createBrowserTracing(true); - expect(BrowserTracing.options.routingInstrumentationProcessors).toHaveLength(1); - }); + describe('route transaction', () => { + const customRoutingInstrumentation = (startTransaction: Function) => { + startTransaction({ name: 'a/path', op: 'pageload' }); + }; - // We can test creating a route transaction with either navigation - // or pageload, but for simplicities case, we check by creating a - // pageload transaction. - // Testing `BrowserTracing._createRouteTransaction()` functionality - describe('route transaction', () => { - it('calls beforeNavigate on transaction creation', () => { - const mockBeforeNavigation = jest.fn().mockReturnValue('here/is/my/path'); - createBrowserTracing(true, { beforeNavigate: mockBeforeNavigation }); - const transaction = getActiveTransaction(hub) as IdleTransaction; - expect(transaction).toBeDefined(); - - expect(mockBeforeNavigation).toHaveBeenCalledTimes(1); + it('calls custom routing instrumenation', () => { + createBrowserTracing(true, { + routingInstrumentation: customRoutingInstrumentation, }); - it('is not created if beforeNavigate returns undefined', () => { - const mockBeforeNavigation = jest.fn().mockReturnValue(undefined); - createBrowserTracing(true, { beforeNavigate: mockBeforeNavigation }); - const transaction = getActiveTransaction(hub) as IdleTransaction; - expect(transaction).not.toBeDefined(); + const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(transaction).toBeDefined(); + expect(transaction.name).toBe('a/path'); + expect(transaction.op).toBe('pageload'); + }); - expect(mockBeforeNavigation).toHaveBeenCalledTimes(1); + it('calls beforeNavigate on transaction creation', () => { + const mockBeforeNavigation = jest.fn().mockReturnValue({ name: 'here/is/my/path' }); + createBrowserTracing(true, { + beforeNavigate: mockBeforeNavigation, + routingInstrumentation: customRoutingInstrumentation, }); + const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(transaction).toBeDefined(); - it('sets transaction context from sentry-trace header', () => { - const name = 'sentry-trace'; - const content = '126de09502ae4e0fb26c6967190756a4-b6e54397b12a2a0f-1'; - document.head.innerHTML = ``; - createBrowserTracing(true); - const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(mockBeforeNavigation).toHaveBeenCalledTimes(1); + }); - expect(transaction.traceId).toBe('126de09502ae4e0fb26c6967190756a4'); - expect(transaction.parentSpanId).toBe('b6e54397b12a2a0f'); - expect(transaction.sampled).toBe(true); + it('is not created if beforeNavigate returns undefined', () => { + const mockBeforeNavigation = jest.fn().mockReturnValue(undefined); + createBrowserTracing(true, { + beforeNavigate: mockBeforeNavigation, + routingInstrumentation: customRoutingInstrumentation, }); + const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(transaction).not.toBeDefined(); - it('uses a custom routing instrumentation processor', () => { - createBrowserTracing(true, { routingInstrumentationProcessors: [] }); - const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(mockBeforeNavigation).toHaveBeenCalledTimes(1); + }); - expect(transaction.traceId).toBe('126de09502ae4e0fb26c6967190756a4'); - expect(transaction.parentSpanId).toBe('b6e54397b12a2a0f'); - expect(transaction.sampled).toBe(true); + it('can use a custom beforeNavigate', () => { + const mockBeforeNavigation = jest.fn(ctx => ({ + ...ctx, + op: 'something-else', + })); + createBrowserTracing(true, { + beforeNavigate: mockBeforeNavigation, + routingInstrumentation: customRoutingInstrumentation, }); + const transaction = getActiveTransaction(hub) as IdleTransaction; + expect(transaction).toBeDefined(); + expect(transaction.op).toBe('something-else'); - it('is created with a default idleTimeout', () => { - createBrowserTracing(true); - const mockFinish = jest.fn(); - const transaction = getActiveTransaction(hub) as IdleTransaction; - transaction.finish = mockFinish; + expect(mockBeforeNavigation).toHaveBeenCalledTimes(1); + }); - const span = transaction.startChild(); // activities = 1 - span.finish(); // activities = 0 + it('sets transaction context from sentry-trace header', () => { + const name = 'sentry-trace'; + const content = '126de09502ae4e0fb26c6967190756a4-b6e54397b12a2a0f-1'; + document.head.innerHTML = ``; + createBrowserTracing(true, { routingInstrumentation: customRoutingInstrumentation }); + const transaction = getActiveTransaction(hub) as IdleTransaction; - expect(mockFinish).toHaveBeenCalledTimes(0); - jest.advanceTimersByTime(DEFAULT_IDLE_TIMEOUT); - expect(mockFinish).toHaveBeenCalledTimes(1); - }); + expect(transaction.traceId).toBe('126de09502ae4e0fb26c6967190756a4'); + expect(transaction.parentSpanId).toBe('b6e54397b12a2a0f'); + expect(transaction.sampled).toBe(true); + }); - it('can be created with a custom idleTimeout', () => { - createBrowserTracing(true, { idleTimeout: 2000 }); - const mockFinish = jest.fn(); - const transaction = getActiveTransaction(hub) as IdleTransaction; - transaction.finish = mockFinish; + it('is created with a default idleTimeout', () => { + createBrowserTracing(true, { routingInstrumentation: customRoutingInstrumentation }); + const mockFinish = jest.fn(); + const transaction = getActiveTransaction(hub) as IdleTransaction; + transaction.finish = mockFinish; - const span = transaction.startChild(); // activities = 1 - span.finish(); // activities = 0 + const span = transaction.startChild(); // activities = 1 + span.finish(); // activities = 0 - expect(mockFinish).toHaveBeenCalledTimes(0); - jest.advanceTimersByTime(2000); - expect(mockFinish).toHaveBeenCalledTimes(1); - }); + expect(mockFinish).toHaveBeenCalledTimes(0); + jest.advanceTimersByTime(DEFAULT_IDLE_TIMEOUT); + expect(mockFinish).toHaveBeenCalledTimes(1); + }); + + it('can be created with a custom idleTimeout', () => { + createBrowserTracing(true, { idleTimeout: 2000, routingInstrumentation: customRoutingInstrumentation }); + const mockFinish = jest.fn(); + const transaction = getActiveTransaction(hub) as IdleTransaction; + transaction.finish = mockFinish; + + const span = transaction.startChild(); // activities = 1 + span.finish(); // activities = 0 + + expect(mockFinish).toHaveBeenCalledTimes(0); + jest.advanceTimersByTime(2000); + expect(mockFinish).toHaveBeenCalledTimes(1); }); + }); + // Integration tests for the default routing instrumentation + describe('default routing instrumentation', () => { describe('pageload transaction', () => { it('is created on setup on scope', () => { createBrowserTracing(true); @@ -167,11 +183,9 @@ describe('BrowserTracing', () => { }); }); - // TODO: This needs integration testing describe('navigation transaction', () => { beforeEach(() => { mockChangeHistory = () => undefined; - addInstrumentationHandlerType = ''; }); it('it is not created automatically', () => { @@ -189,7 +203,6 @@ describe('BrowserTracing', () => { expect(transaction1.endTimestamp).not.toBeDefined(); mockChangeHistory({ to: 'here', from: 'there' }); - expect(addInstrumentationHandlerType).toBe('history'); const transaction2 = getActiveTransaction(hub) as IdleTransaction; expect(transaction2.op).toBe('navigation'); @@ -203,7 +216,6 @@ describe('BrowserTracing', () => { expect(transaction1.endTimestamp).not.toBeDefined(); mockChangeHistory({ to: 'here', from: 'there' }); - expect(addInstrumentationHandlerType).toBe('history'); const transaction2 = getActiveTransaction(hub) as IdleTransaction; expect(transaction2.op).toBe('pageload'); }); diff --git a/packages/tracing/test/browser/router.test.ts b/packages/tracing/test/browser/router.test.ts new file mode 100644 index 000000000000..ab83366c9f86 --- /dev/null +++ b/packages/tracing/test/browser/router.test.ts @@ -0,0 +1,117 @@ +// tslint:disable-next-line: no-implicit-dependencies +import { JSDOM } from 'jsdom'; + +import { defaultBeforeNavigate, defaultRoutingInstrumentation } from '../../src/browser/router'; + +let mockChangeHistory: ({ to, from }: { to: string; from?: string }) => void = () => undefined; +let addInstrumentationHandlerType: string = ''; +jest.mock('@sentry/utils', () => { + const actual = jest.requireActual('@sentry/utils'); + return { + ...actual, + addInstrumentationHandler: ({ callback, type }: any): void => { + addInstrumentationHandlerType = type; + mockChangeHistory = callback; + }, + }; +}); + +describe('defaultBeforeNavigate()', () => { + it('returns a context', () => { + const ctx = { name: 'testing', status: 'ok' }; + expect(defaultBeforeNavigate(ctx)).toBe(ctx); + }); +}); + +describe('defaultRoutingInstrumentation', () => { + const mockFinish = jest.fn(); + const startTransaction = jest.fn().mockReturnValue({ finish: mockFinish }); + beforeEach(() => { + const dom = new JSDOM(); + // @ts-ignore + global.document = dom.window.document; + // @ts-ignore + global.window = dom.window; + // @ts-ignore + global.location = dom.window.location; + + startTransaction.mockClear(); + mockFinish.mockClear(); + }); + + it('does not start transactions if global location is undefined', () => { + // @ts-ignore + global.location = undefined; + defaultRoutingInstrumentation(startTransaction); + expect(startTransaction).toHaveBeenCalledTimes(0); + }); + + it('starts a pageload transaction', () => { + defaultRoutingInstrumentation(startTransaction); + expect(startTransaction).toHaveBeenCalledTimes(1); + expect(startTransaction).toHaveBeenLastCalledWith({ name: 'blank', op: 'pageload' }); + }); + + it('does not start a pageload transaction if startTransactionOnPageLoad is false', () => { + defaultRoutingInstrumentation(startTransaction, false); + expect(startTransaction).toHaveBeenCalledTimes(0); + }); + + describe('navigation transaction', () => { + beforeEach(() => { + mockChangeHistory = () => undefined; + addInstrumentationHandlerType = ''; + }); + + it('it is not created automatically', () => { + defaultRoutingInstrumentation(startTransaction); + expect(startTransaction).not.toHaveBeenLastCalledWith({ name: 'blank', op: 'navigation' }); + }); + + it('is created on location change', () => { + defaultRoutingInstrumentation(startTransaction); + mockChangeHistory({ to: 'here', from: 'there' }); + expect(addInstrumentationHandlerType).toBe('history'); + + expect(startTransaction).toHaveBeenCalledTimes(2); + expect(startTransaction).toHaveBeenLastCalledWith({ name: 'blank', op: 'navigation' }); + }); + + it('is not created if startTransactionOnLocationChange is false', () => { + defaultRoutingInstrumentation(startTransaction, true, false); + mockChangeHistory({ to: 'here', from: 'there' }); + expect(addInstrumentationHandlerType).toBe(''); + + expect(startTransaction).toHaveBeenCalledTimes(1); + }); + + it('finishes the last active transaction', () => { + defaultRoutingInstrumentation(startTransaction); + + expect(mockFinish).toHaveBeenCalledTimes(0); + mockChangeHistory({ to: 'here', from: 'there' }); + expect(mockFinish).toHaveBeenCalledTimes(1); + }); + + it('will finish active transaction multiple times', () => { + defaultRoutingInstrumentation(startTransaction); + + expect(mockFinish).toHaveBeenCalledTimes(0); + mockChangeHistory({ to: 'here', from: 'there' }); + expect(mockFinish).toHaveBeenCalledTimes(1); + mockChangeHistory({ to: 'over/there', from: 'here' }); + expect(mockFinish).toHaveBeenCalledTimes(2); + mockChangeHistory({ to: 'nowhere', from: 'over/there' }); + expect(mockFinish).toHaveBeenCalledTimes(3); + }); + + it('not created if `from` is equal to `to`', () => { + defaultRoutingInstrumentation(startTransaction); + mockChangeHistory({ to: 'first/path', from: 'first/path' }); + expect(addInstrumentationHandlerType).toBe('history'); + + expect(startTransaction).toHaveBeenCalledTimes(1); + expect(startTransaction).not.toHaveBeenLastCalledWith('navigation'); + }); + }); +}); diff --git a/packages/tracing/test/hub.test.ts b/packages/tracing/test/hub.test.ts index 2672bbf03c27..017be5a5b898 100644 --- a/packages/tracing/test/hub.test.ts +++ b/packages/tracing/test/hub.test.ts @@ -35,11 +35,6 @@ describe('Hub', () => { describe('spans', () => { describe('sampling', () => { - test('set tracesSampleRate 0 on span', () => { - const hub = new Hub(new BrowserClient({ tracesSampleRate: 0 })); - const span = hub.startSpan({}) as any; - expect(span.sampled).toBeUndefined(); - }); test('set tracesSampleRate 0 on transaction', () => { const hub = new Hub(new BrowserClient({ tracesSampleRate: 0 })); const transaction = hub.startTransaction({ name: 'foo' }); diff --git a/packages/tracing/test/idletransaction.test.ts b/packages/tracing/test/idletransaction.test.ts index 8d045576c0b2..563cfbd0a1b8 100644 --- a/packages/tracing/test/idletransaction.test.ts +++ b/packages/tracing/test/idletransaction.test.ts @@ -48,9 +48,8 @@ describe('IdleTransaction', () => { }); it('push and pops activities', () => { - const mockFinish = jest.fn(); const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); - transaction.finishIdleTransaction = mockFinish; + const mockFinish = jest.spyOn(transaction, 'finish'); transaction.initSpanRecorder(10); expect(transaction.activities).toMatchObject({}); @@ -76,10 +75,8 @@ describe('IdleTransaction', () => { }); 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; + const mockFinish = jest.spyOn(transaction, 'finish'); transaction.initSpanRecorder(10); expect(transaction.activities).toMatchObject({}); @@ -129,7 +126,7 @@ describe('IdleTransaction', () => { const cancelledSpan = transaction.startChild({ startTimestamp: transaction.startTimestamp + 4 }); regularSpan.finish(regularSpan.startTimestamp + 4); - transaction.finishIdleTransaction(transaction.startTimestamp + 10); + transaction.finish(transaction.startTimestamp + 10); expect(transaction.spanRecorder).toBeDefined(); if (transaction.spanRecorder) { @@ -150,9 +147,8 @@ describe('IdleTransaction', () => { describe('heartbeat', () => { it('does not start heartbeat if there is no span recorder', () => { - const mockFinish = jest.fn(); const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); - transaction.finish = mockFinish; + const mockFinish = jest.spyOn(transaction, 'finish'); expect(mockFinish).toHaveBeenCalledTimes(0); @@ -169,9 +165,8 @@ describe('IdleTransaction', () => { expect(mockFinish).toHaveBeenCalledTimes(0); }); it('finishes a transaction after 3 beats', () => { - const mockFinish = jest.fn(); const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); - transaction.finish = mockFinish; + const mockFinish = jest.spyOn(transaction, 'finish'); transaction.initSpanRecorder(10); expect(mockFinish).toHaveBeenCalledTimes(0); @@ -190,9 +185,8 @@ describe('IdleTransaction', () => { }); it('resets after new activities are added', () => { - const mockFinish = jest.fn(); const transaction = new IdleTransaction({ name: 'foo' }, hub, 1000); - transaction.finish = mockFinish; + const mockFinish = jest.spyOn(transaction, 'finish'); transaction.initSpanRecorder(10); expect(mockFinish).toHaveBeenCalledTimes(0); From 6dd069c60b9ff374d396011d0c2907867618d80d Mon Sep 17 00:00:00 2001 From: Abhijeet Prasad Date: Wed, 8 Jul 2020 14:38:22 -0400 Subject: [PATCH 7/7] remove tracing --- .../tracing/src/browser/browsertracing.ts | 2 +- packages/tracing/src/browser/index.ts | 1 + packages/tracing/src/index.bundle.ts | 4 +- packages/tracing/src/index.ts | 2 +- packages/tracing/src/integrations/index.ts | 1 - packages/tracing/src/integrations/tracing.ts | 1057 ----------------- 6 files changed, 5 insertions(+), 1062 deletions(-) create mode 100644 packages/tracing/src/browser/index.ts delete mode 100644 packages/tracing/src/integrations/tracing.ts diff --git a/packages/tracing/src/browser/browsertracing.ts b/packages/tracing/src/browser/browsertracing.ts index 7df8900a6d23..1b07ebac3206 100644 --- a/packages/tracing/src/browser/browsertracing.ts +++ b/packages/tracing/src/browser/browsertracing.ts @@ -6,7 +6,7 @@ import { startIdleTransaction } from '../hubextensions'; import { DEFAULT_IDLE_TIMEOUT } from '../idletransaction'; import { Span } from '../span'; -import { defaultRoutingInstrumentation, defaultBeforeNavigate } from './router'; +import { defaultBeforeNavigate, defaultRoutingInstrumentation } from './router'; /** Options for Browser Tracing integration */ export interface BrowserTracingOptions { diff --git a/packages/tracing/src/browser/index.ts b/packages/tracing/src/browser/index.ts new file mode 100644 index 000000000000..b06f3288bd7c --- /dev/null +++ b/packages/tracing/src/browser/index.ts @@ -0,0 +1 @@ +export { BrowserTracing } from './browsertracing'; diff --git a/packages/tracing/src/index.bundle.ts b/packages/tracing/src/index.bundle.ts index 0d39253e7980..e509bbee51c9 100644 --- a/packages/tracing/src/index.bundle.ts +++ b/packages/tracing/src/index.bundle.ts @@ -52,8 +52,8 @@ export { SDK_NAME, SDK_VERSION } from '@sentry/browser'; import { Integrations as BrowserIntegrations } from '@sentry/browser'; import { getGlobalObject } from '@sentry/utils'; +import { BrowserTracing } from './browser'; import { addExtensionMethods } from './hubextensions'; -import * as ApmIntegrations 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, + ...BrowserTracing, }; export { INTEGRATIONS as Integrations }; diff --git a/packages/tracing/src/index.ts b/packages/tracing/src/index.ts index c47c25f1520b..9a976e53bcac 100644 --- a/packages/tracing/src/index.ts +++ b/packages/tracing/src/index.ts @@ -1,4 +1,4 @@ -import { BrowserTracing } from './browser/browsertracing'; +import { BrowserTracing } from './browser'; import { addExtensionMethods } from './hubextensions'; import * as ApmIntegrations from './integrations'; diff --git a/packages/tracing/src/integrations/index.ts b/packages/tracing/src/integrations/index.ts index 8833c8cd301c..abe1faf43c27 100644 --- a/packages/tracing/src/integrations/index.ts +++ b/packages/tracing/src/integrations/index.ts @@ -1,2 +1 @@ export { Express } from './express'; -export { Tracing } from './tracing'; diff --git a/packages/tracing/src/integrations/tracing.ts b/packages/tracing/src/integrations/tracing.ts deleted file mode 100644 index d4496e53e108..000000000000 --- a/packages/tracing/src/integrations/tracing.ts +++ /dev/null @@ -1,1057 +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', - }); - } -}