diff --git a/packages/tracing/src/hubextensions.ts b/packages/tracing/src/hubextensions.ts deleted file mode 100644 index 445225ab6622..000000000000 --- a/packages/tracing/src/hubextensions.ts +++ /dev/null @@ -1,103 +0,0 @@ -import { getMainCarrier, Hub } from '@sentry/hub'; -import { SpanContext, TransactionContext } from '@sentry/types'; -import { logger } from '@sentry/utils'; - -import { Span } from './span'; -import { Transaction } from './transaction'; - -/** Returns all trace headers that are currently on the top scope. */ -function traceHeaders(this: Hub): { [key: string]: string } { - const scope = this.getScope(); - if (scope) { - const span = scope.getSpan(); - if (span) { - return { - 'sentry-trace': span.toTraceparent(), - }; - } - } - return {}; -} - -/** - * {@see Hub.startTransaction} - */ -function startTransaction(this: Hub, context: TransactionContext): Transaction { - const transaction = new Transaction(context, this); - - const client = this.getClient(); - // Roll the dice for sampling transaction, all child spans inherit the sampling decision. - if (transaction.sampled === undefined) { - const sampleRate = (client && client.getOptions().tracesSampleRate) || 0; - // if true = we want to have the transaction - // if false = we don't want to have it - // Math.random (inclusive of 0, but not 1) - transaction.sampled = Math.random() < sampleRate; - } - - // We only want to create a span list if we sampled the transaction - // If sampled == false, we will discard the span anyway, so we can save memory by not storing child spans - if (transaction.sampled) { - const experimentsOptions = (client && client.getOptions()._experiments) || {}; - transaction.initSpanRecorder(experimentsOptions.maxSpans as number); - } - - return transaction; -} - -/** - * {@see Hub.startSpan} - */ -function startSpan(this: Hub, context: SpanContext): Transaction | Span { - /** - * @deprecated - * TODO: consider removing this in a future release. - * - * This is for backwards compatibility with releases before startTransaction - * existed, to allow for a smoother transition. - */ - { - // The `TransactionContext.name` field used to be called `transaction`. - const transactionContext = context as Partial; - if (transactionContext.transaction !== undefined) { - transactionContext.name = transactionContext.transaction; - } - // Check for not undefined since we defined it's ok to start a transaction - // with an empty name. - if (transactionContext.name !== undefined) { - logger.warn('Deprecated: Use startTransaction to start transactions and Transaction.startChild to start spans.'); - return this.startTransaction(transactionContext as TransactionContext); - } - } - - const scope = this.getScope(); - if (scope) { - // If there is a Span on the Scope we start a child and return that instead - const parentSpan = scope.getSpan(); - if (parentSpan) { - return parentSpan.startChild(context); - } - } - - // Otherwise we return a new Span - return new Span(context); -} - -/** - * This patches the global object and injects the APM extensions methods - */ -export function addExtensionMethods(): void { - const carrier = getMainCarrier(); - if (carrier.__SENTRY__) { - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - if (!carrier.__SENTRY__.extensions.startTransaction) { - carrier.__SENTRY__.extensions.startTransaction = startTransaction; - } - if (!carrier.__SENTRY__.extensions.startSpan) { - carrier.__SENTRY__.extensions.startSpan = startSpan; - } - if (!carrier.__SENTRY__.extensions.traceHeaders) { - carrier.__SENTRY__.extensions.traceHeaders = traceHeaders; - } - } -} diff --git a/packages/tracing/src/index.bundle.ts b/packages/tracing/src/index.bundle.ts deleted file mode 100644 index 0d39253e7980..000000000000 --- a/packages/tracing/src/index.bundle.ts +++ /dev/null @@ -1,79 +0,0 @@ -export { - Breadcrumb, - Request, - SdkInfo, - Event, - Exception, - Response, - Severity, - StackFrame, - Stacktrace, - Status, - Thread, - User, -} from '@sentry/types'; - -export { - addGlobalEventProcessor, - addBreadcrumb, - captureException, - captureEvent, - captureMessage, - configureScope, - getHubFromCarrier, - getCurrentHub, - Hub, - Scope, - setContext, - setExtra, - setExtras, - setTag, - setTags, - setUser, - Transports, - withScope, -} from '@sentry/browser'; - -export { BrowserOptions } from '@sentry/browser'; -export { BrowserClient, ReportDialogOptions } from '@sentry/browser'; -export { - defaultIntegrations, - forceLoad, - init, - lastEventId, - onLoad, - showReportDialog, - flush, - close, - wrap, -} from '@sentry/browser'; -export { SDK_NAME, SDK_VERSION } from '@sentry/browser'; - -import { Integrations as BrowserIntegrations } from '@sentry/browser'; -import { getGlobalObject } from '@sentry/utils'; - -import { addExtensionMethods } from './hubextensions'; -import * as ApmIntegrations from './integrations'; - -export { Span, TRACEPARENT_REGEXP } from './span'; - -let windowIntegrations = {}; - -// This block is needed to add compatibility with the integrations packages when used with a CDN -// tslint:disable: no-unsafe-any -const _window = getGlobalObject(); -if (_window.Sentry && _window.Sentry.Integrations) { - windowIntegrations = _window.Sentry.Integrations; -} -// tslint:enable: no-unsafe-any - -const INTEGRATIONS = { - ...windowIntegrations, - ...BrowserIntegrations, - Tracing: ApmIntegrations.Tracing, -}; - -export { INTEGRATIONS as Integrations }; - -// We are patching the global object with our hub extension methods -addExtensionMethods(); diff --git a/packages/tracing/src/index.ts b/packages/tracing/src/index.ts deleted file mode 100644 index 9f59e3515f40..000000000000 --- a/packages/tracing/src/index.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { addExtensionMethods } from './hubextensions'; -import * as ApmIntegrations from './integrations'; - -export { ApmIntegrations as Integrations }; -export { Span, TRACEPARENT_REGEXP } from './span'; -export { Transaction } from './transaction'; - -export { SpanStatus } from './spanstatus'; - -// We are patching the global object with our hub extension methods -addExtensionMethods(); diff --git a/packages/tracing/src/integrations/express.ts b/packages/tracing/src/integrations/express.ts deleted file mode 100644 index 113d41423dcd..000000000000 --- a/packages/tracing/src/integrations/express.ts +++ /dev/null @@ -1,175 +0,0 @@ -import { Integration, Transaction } from '@sentry/types'; -import { logger } from '@sentry/utils'; -// tslint:disable-next-line:no-implicit-dependencies -import { Application, ErrorRequestHandler, NextFunction, Request, RequestHandler, Response } from 'express'; - -/** - * Internal helper for `__sentry_transaction` - * @hidden - */ -interface SentryTracingResponse { - __sentry_transaction?: Transaction; -} - -/** - * Express integration - * - * Provides an request and error handler for Express framework - * as well as tracing capabilities - */ -export class Express implements Integration { - /** - * @inheritDoc - */ - public name: string = Express.id; - - /** - * @inheritDoc - */ - public static id: string = 'Express'; - - /** - * Express App instance - */ - private readonly _app?: Application; - - /** - * @inheritDoc - */ - public constructor(options: { app?: Application } = {}) { - this._app = options.app; - } - - /** - * @inheritDoc - */ - public setupOnce(): void { - if (!this._app) { - logger.error('ExpressIntegration is missing an Express instance'); - return; - } - instrumentMiddlewares(this._app); - } -} - -/** - * Wraps original middleware function in a tracing call, which stores the info about the call as a span, - * and finishes it once the middleware is done invoking. - * - * Express middlewares have 3 various forms, thus we have to take care of all of them: - * // sync - * app.use(function (req, res) { ... }) - * // async - * app.use(function (req, res, next) { ... }) - * // error handler - * app.use(function (err, req, res, next) { ... }) - */ -function wrap(fn: Function): RequestHandler | ErrorRequestHandler { - const arrity = fn.length; - - switch (arrity) { - case 2: { - return function(this: NodeJS.Global, _req: Request, res: Response & SentryTracingResponse): any { - const transaction = res.__sentry_transaction; - if (transaction) { - const span = transaction.startChild({ - description: fn.name, - op: 'middleware', - }); - res.once('finish', () => { - span.finish(); - }); - } - return fn.apply(this, arguments); - }; - } - case 3: { - return function( - this: NodeJS.Global, - req: Request, - res: Response & SentryTracingResponse, - next: NextFunction, - ): any { - const transaction = res.__sentry_transaction; - const span = - transaction && - transaction.startChild({ - description: fn.name, - op: 'middleware', - }); - fn.call(this, req, res, function(this: NodeJS.Global): any { - if (span) { - span.finish(); - } - return next.apply(this, arguments); - }); - }; - } - case 4: { - return function( - this: NodeJS.Global, - err: any, - req: Request, - res: Response & SentryTracingResponse, - next: NextFunction, - ): any { - const transaction = res.__sentry_transaction; - const span = - transaction && - transaction.startChild({ - description: fn.name, - op: 'middleware', - }); - fn.call(this, err, req, res, function(this: NodeJS.Global): any { - if (span) { - span.finish(); - } - return next.apply(this, arguments); - }); - }; - } - default: { - throw new Error(`Express middleware takes 2-4 arguments. Got: ${arrity}`); - } - } -} - -/** - * Takes all the function arguments passed to the original `app.use` call - * and wraps every function, as well as array of functions with a call to our `wrap` method. - * We have to take care of the arrays as well as iterate over all of the arguments, - * as `app.use` can accept middlewares in few various forms. - * - * app.use([], ) - * app.use([], , ...) - * app.use([], ...[]) - */ -function wrapUseArgs(args: IArguments): unknown[] { - return Array.from(args).map((arg: unknown) => { - if (typeof arg === 'function') { - return wrap(arg); - } - - if (Array.isArray(arg)) { - return arg.map((a: unknown) => { - if (typeof a === 'function') { - return wrap(a); - } - return a; - }); - } - - return arg; - }); -} - -/** - * Patches original app.use to utilize our tracing functionality - */ -function instrumentMiddlewares(app: Application): Application { - const originalAppUse = app.use; - app.use = function(): any { - return originalAppUse.apply(this, wrapUseArgs(arguments)); - }; - return app; -} diff --git a/packages/tracing/src/integrations/index.ts b/packages/tracing/src/integrations/index.ts deleted file mode 100644 index 8833c8cd301c..000000000000 --- a/packages/tracing/src/integrations/index.ts +++ /dev/null @@ -1,2 +0,0 @@ -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 5226f2a3b34b..000000000000 --- a/packages/tracing/src/integrations/tracing.ts +++ /dev/null @@ -1,1052 +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, - 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 options = (handlerData.args[1] = (handlerData.args[1] as { [key: string]: any }) || {}); - if (options.headers) { - if (Array.isArray(options.headers)) { - options.headers = [...options.headers, { 'sentry-trace': span.toTraceparent() }]; - } else { - options.headers = { - ...options.headers, - 'sentry-trace': span.toTraceparent(), - }; - } - } else { - options.headers = { 'sentry-trace': span.toTraceparent() }; - } - } - } - } - // tslint:enable: no-unsafe-any -} - -/** - * Creates transaction from navigation changes - */ -function historyCallback(_: { [key: string]: any }): void { - if (Tracing.options.startTransactionOnLocationChange && global && global.location) { - Tracing.finishIdleTransaction(timestampWithMs()); - Tracing.startIdleTransaction({ - name: Tracing.options.beforeNavigate(window.location), - op: 'navigation', - }); - } -} diff --git a/packages/tracing/src/integrations/types.ts b/packages/tracing/src/integrations/types.ts deleted file mode 100644 index 69984a264383..000000000000 --- a/packages/tracing/src/integrations/types.ts +++ /dev/null @@ -1,82 +0,0 @@ -/** - * The location (URL) of the object it is linked to. Changes done on it are reflected on the object it relates to. - * Both the Document and Window interface have such a linked Location, accessible via Document.location and Window.location respectively. - * - * Copy Location interface so that user's dont have to include dom typings with Tracing integration - * Based on https://github.com/microsoft/TypeScript/blob/4cf0afe2662980ebcd8d444dbd13d8f47d06fcd5/lib/lib.dom.d.ts#L9691 - */ -export interface Location { - /** - * Returns a DOMStringList object listing the origins of the ancestor browsing contexts, from the parent browsing context to the top-level browsing context. - */ - readonly ancestorOrigins: DOMStringList; - /** - * Returns the Location object's URL's fragment (includes leading "#" if non-empty). - * - * Can be set, to navigate to the same URL with a changed fragment (ignores leading "#"). - */ - hash: string; - /** - * Returns the Location object's URL's host and port (if different from the default port for the scheme). - * - * Can be set, to navigate to the same URL with a changed host and port. - */ - host: string; - /** - * Returns the Location object's URL's host. - * - * Can be set, to navigate to the same URL with a changed host. - */ - hostname: string; - /** - * Returns the Location object's URL. - * - * Can be set, to navigate to the given URL. - */ - href: string; - // tslint:disable-next-line: completed-docs - toString(): string; - /** - * Returns the Location object's URL's origin. - */ - readonly origin: string; - /** - * Returns the Location object's URL's path. - * - * Can be set, to navigate to the same URL with a changed path. - */ - pathname: string; - /** - * Returns the Location object's URL's port. - * - * Can be set, to navigate to the same URL with a changed port. - */ - port: string; - /** - * Returns the Location object's URL's scheme. - * - * Can be set, to navigate to the same URL with a changed scheme. - */ - protocol: string; - /** - * Returns the Location object's URL's query (includes leading "?" if non-empty). - * - * Can be set, to navigate to the same URL with a changed query (ignores leading "?"). - */ - search: string; - /** - * Navigates to the given URL. - */ - assign(url: string): void; - /** - * Reloads the current page. - */ - reload(): void; - /** @deprecated */ - // tslint:disable-next-line: unified-signatures completed-docs - reload(forcedReload: boolean): void; - /** - * Removes the current page from the session history and navigates to the given URL. - */ - replace(url: string): void; -} diff --git a/packages/tracing/src/span.ts b/packages/tracing/src/span.ts deleted file mode 100644 index eb6c49d42bab..000000000000 --- a/packages/tracing/src/span.ts +++ /dev/null @@ -1,296 +0,0 @@ -import { Span as SpanInterface, SpanContext } from '@sentry/types'; -import { dropUndefinedKeys, timestampWithMs, uuid4 } from '@sentry/utils'; - -import { SpanStatus } from './spanstatus'; -import { SpanRecorder } from './transaction'; - -export const TRACEPARENT_REGEXP = new RegExp( - '^[ \\t]*' + // whitespace - '([0-9a-f]{32})?' + // trace_id - '-?([0-9a-f]{16})?' + // span_id - '-?([01])?' + // sampled - '[ \\t]*$', // whitespace -); - -/** - * Span contains all data about a span - */ -export class Span implements SpanInterface, SpanContext { - /** - * @inheritDoc - */ - public traceId: string = uuid4(); - - /** - * @inheritDoc - */ - public spanId: string = uuid4().substring(16); - - /** - * @inheritDoc - */ - public parentSpanId?: string; - - /** - * Internal keeper of the status - */ - public status?: SpanStatus | string; - - /** - * @inheritDoc - */ - public sampled?: boolean; - - /** - * Timestamp in seconds when the span was created. - */ - public startTimestamp: number = timestampWithMs(); - - /** - * Timestamp in seconds when the span ended. - */ - public endTimestamp?: number; - - /** - * @inheritDoc - */ - public op?: string; - - /** - * @inheritDoc - */ - public description?: string; - - /** - * @inheritDoc - */ - public tags: { [key: string]: string } = {}; - - /** - * @inheritDoc - */ - public data: { [key: string]: any } = {}; - - /** - * List of spans that were finalized - */ - public spanRecorder?: SpanRecorder; - - /** - * You should never call the constructor manually, always use `hub.startSpan()`. - * @internal - * @hideconstructor - * @hidden - */ - public constructor(spanContext?: SpanContext) { - if (!spanContext) { - return this; - } - if (spanContext.traceId) { - this.traceId = spanContext.traceId; - } - if (spanContext.spanId) { - this.spanId = spanContext.spanId; - } - if (spanContext.parentSpanId) { - this.parentSpanId = spanContext.parentSpanId; - } - // We want to include booleans as well here - if ('sampled' in spanContext) { - this.sampled = spanContext.sampled; - } - if (spanContext.op) { - this.op = spanContext.op; - } - if (spanContext.description) { - this.description = spanContext.description; - } - if (spanContext.data) { - this.data = spanContext.data; - } - if (spanContext.tags) { - this.tags = spanContext.tags; - } - if (spanContext.status) { - this.status = spanContext.status; - } - if (spanContext.startTimestamp) { - this.startTimestamp = spanContext.startTimestamp; - } - if (spanContext.endTimestamp) { - this.endTimestamp = spanContext.endTimestamp; - } - } - - /** - * @inheritDoc - * @deprecated - */ - public child( - spanContext?: Pick>, - ): Span { - return this.startChild(spanContext); - } - - /** - * @inheritDoc - */ - public startChild( - spanContext?: Pick>, - ): Span { - const span = new Span({ - ...spanContext, - parentSpanId: this.spanId, - sampled: this.sampled, - traceId: this.traceId, - }); - - span.spanRecorder = this.spanRecorder; - if (span.spanRecorder) { - span.spanRecorder.add(span); - } - - return span; - } - - /** - * Continues a trace from a string (usually the header). - * @param traceparent Traceparent string - */ - public static fromTraceparent( - traceparent: string, - spanContext?: Pick>, - ): Span | undefined { - const matches = traceparent.match(TRACEPARENT_REGEXP); - if (matches) { - let sampled: boolean | undefined; - if (matches[3] === '1') { - sampled = true; - } else if (matches[3] === '0') { - sampled = false; - } - return new Span({ - ...spanContext, - parentSpanId: matches[2], - sampled, - traceId: matches[1], - }); - } - return undefined; - } - - /** - * @inheritDoc - */ - public setTag(key: string, value: string): this { - this.tags = { ...this.tags, [key]: value }; - return this; - } - - /** - * @inheritDoc - */ - public setData(key: string, value: any): this { - this.data = { ...this.data, [key]: value }; - return this; - } - - /** - * @inheritDoc - */ - public setStatus(value: SpanStatus): this { - this.status = value; - return this; - } - - /** - * @inheritDoc - */ - public setHttpStatus(httpStatus: number): this { - this.setTag('http.status_code', String(httpStatus)); - const spanStatus = SpanStatus.fromHttpCode(httpStatus); - if (spanStatus !== SpanStatus.UnknownError) { - this.setStatus(spanStatus); - } - return this; - } - - /** - * @inheritDoc - */ - public isSuccess(): boolean { - return this.status === SpanStatus.Ok; - } - - /** - * @inheritDoc - */ - public finish(endTimestamp?: number): void { - this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : timestampWithMs(); - } - - /** - * @inheritDoc - */ - public toTraceparent(): string { - let sampledString = ''; - if (this.sampled !== undefined) { - sampledString = this.sampled ? '-1' : '-0'; - } - return `${this.traceId}-${this.spanId}${sampledString}`; - } - - /** - * @inheritDoc - */ - public getTraceContext(): { - data?: { [key: string]: any }; - description?: string; - op?: string; - parent_span_id?: string; - span_id: string; - status?: string; - tags?: { [key: string]: string }; - trace_id: string; - } { - return dropUndefinedKeys({ - data: Object.keys(this.data).length > 0 ? this.data : undefined, - description: this.description, - op: this.op, - parent_span_id: this.parentSpanId, - span_id: this.spanId, - status: this.status, - tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, - trace_id: this.traceId, - }); - } - - /** - * @inheritDoc - */ - public toJSON(): { - data?: { [key: string]: any }; - description?: string; - op?: string; - parent_span_id?: string; - sampled?: boolean; - span_id: string; - start_timestamp: number; - tags?: { [key: string]: string }; - timestamp?: number; - trace_id: string; - } { - return dropUndefinedKeys({ - data: Object.keys(this.data).length > 0 ? this.data : undefined, - description: this.description, - op: this.op, - parent_span_id: this.parentSpanId, - span_id: this.spanId, - start_timestamp: this.startTimestamp, - status: this.status, - tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, - timestamp: this.endTimestamp, - trace_id: this.traceId, - }); - } -} diff --git a/packages/tracing/src/spanstatus.ts b/packages/tracing/src/spanstatus.ts deleted file mode 100644 index 6aa87a4dc833..000000000000 --- a/packages/tracing/src/spanstatus.ts +++ /dev/null @@ -1,87 +0,0 @@ -/** The status of an Span. */ -export enum SpanStatus { - /** The operation completed successfully. */ - Ok = 'ok', - /** Deadline expired before operation could complete. */ - DeadlineExceeded = 'deadline_exceeded', - /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */ - Unauthenticated = 'unauthenticated', - /** 403 Forbidden */ - PermissionDenied = 'permission_denied', - /** 404 Not Found. Some requested entity (file or directory) was not found. */ - NotFound = 'not_found', - /** 429 Too Many Requests */ - ResourceExhausted = 'resource_exhausted', - /** Client specified an invalid argument. 4xx. */ - InvalidArgument = 'invalid_argument', - /** 501 Not Implemented */ - Unimplemented = 'unimplemented', - /** 503 Service Unavailable */ - Unavailable = 'unavailable', - /** Other/generic 5xx. */ - InternalError = 'internal_error', - /** Unknown. Any non-standard HTTP status code. */ - UnknownError = 'unknown_error', - /** The operation was cancelled (typically by the user). */ - Cancelled = 'cancelled', - /** Already exists (409) */ - AlreadyExists = 'already_exists', - /** Operation was rejected because the system is not in a state required for the operation's */ - FailedPrecondition = 'failed_precondition', - /** The operation was aborted, typically due to a concurrency issue. */ - Aborted = 'aborted', - /** Operation was attempted past the valid range. */ - OutOfRange = 'out_of_range', - /** Unrecoverable data loss or corruption */ - DataLoss = 'data_loss', -} - -// tslint:disable:no-unnecessary-qualifier no-namespace -export namespace SpanStatus { - /** - * Converts a HTTP status code into a {@link SpanStatus}. - * - * @param httpStatus The HTTP response status code. - * @returns The span status or {@link SpanStatus.UnknownError}. - */ - // tslint:disable-next-line:completed-docs - export function fromHttpCode(httpStatus: number): SpanStatus { - if (httpStatus < 400) { - return SpanStatus.Ok; - } - - if (httpStatus >= 400 && httpStatus < 500) { - switch (httpStatus) { - case 401: - return SpanStatus.Unauthenticated; - case 403: - return SpanStatus.PermissionDenied; - case 404: - return SpanStatus.NotFound; - case 409: - return SpanStatus.AlreadyExists; - case 413: - return SpanStatus.FailedPrecondition; - case 429: - return SpanStatus.ResourceExhausted; - default: - return SpanStatus.InvalidArgument; - } - } - - if (httpStatus >= 500 && httpStatus < 600) { - switch (httpStatus) { - case 501: - return SpanStatus.Unimplemented; - case 503: - return SpanStatus.Unavailable; - case 504: - return SpanStatus.DeadlineExceeded; - default: - return SpanStatus.InternalError; - } - } - - return SpanStatus.UnknownError; - } -} diff --git a/packages/tracing/src/transaction.ts b/packages/tracing/src/transaction.ts deleted file mode 100644 index 9366fca34613..000000000000 --- a/packages/tracing/src/transaction.ts +++ /dev/null @@ -1,132 +0,0 @@ -// tslint:disable:max-classes-per-file -import { getCurrentHub, Hub } from '@sentry/hub'; -import { TransactionContext } from '@sentry/types'; -import { isInstanceOf, logger } from '@sentry/utils'; - -import { Span as SpanClass } from './span'; - -/** - * Keeps track of finished spans for a given transaction - * @internal - * @hideconstructor - * @hidden - */ -export class SpanRecorder { - private readonly _maxlen: number; - public spans: SpanClass[] = []; - - public constructor(maxlen: number = 1000) { - this._maxlen = maxlen; - } - - /** - * This is just so that we don't run out of memory while recording a lot - * of spans. At some point we just stop and flush out the start of the - * trace tree (i.e.the first n spans with the smallest - * start_timestamp). - */ - public add(span: SpanClass): void { - if (this.spans.length > this._maxlen) { - span.spanRecorder = undefined; - } else { - this.spans.push(span); - } - } -} - -/** JSDoc */ -export class Transaction extends SpanClass { - /** - * The reference to the current hub. - */ - private readonly _hub: Hub = (getCurrentHub() as unknown) as Hub; - - public name?: string; - - private readonly _trimEnd?: boolean; - - /** - * This constructor should never be called manually. Those instrumenting tracing should use - * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`. - * @internal - * @hideconstructor - * @hidden - */ - public constructor(transactionContext: TransactionContext, hub?: Hub) { - super(transactionContext); - - if (isInstanceOf(hub, Hub)) { - this._hub = hub as Hub; - } - - if (transactionContext.name) { - this.name = transactionContext.name; - } - - this._trimEnd = transactionContext.trimEnd; - } - - /** - * JSDoc - */ - public setName(name: string): void { - this.name = name; - } - - /** - * Attaches SpanRecorder to the span itself - * @param maxlen maximum number of spans that can be recorded - */ - public initSpanRecorder(maxlen: number = 1000): void { - if (!this.spanRecorder) { - this.spanRecorder = new SpanRecorder(maxlen); - } - this.spanRecorder.add(this); - } - - /** - * @inheritDoc - */ - public finish(endTimestamp?: number): string | undefined { - // This transaction is already finished, so we should not flush it again. - if (this.endTimestamp !== undefined) { - return undefined; - } - - if (!this.name) { - logger.warn('Transaction has no name, falling back to ``.'); - this.name = ''; - } - - super.finish(endTimestamp); - - if (this.sampled !== true) { - // At this point if `sampled !== true` we want to discard the transaction. - logger.warn('Discarding transaction because it was not chosen to be sampled.'); - return undefined; - } - - const finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(s => s !== this && s.endTimestamp) : []; - - if (this._trimEnd && finishedSpans.length > 0) { - this.endTimestamp = finishedSpans.reduce((prev: SpanClass, current: SpanClass) => { - if (prev.endTimestamp && current.endTimestamp) { - return prev.endTimestamp > current.endTimestamp ? prev : current; - } - return prev; - }).endTimestamp; - } - - return this._hub.captureEvent({ - contexts: { - trace: this.getTraceContext(), - }, - spans: finishedSpans, - start_timestamp: this.startTimestamp, - tags: this.tags, - timestamp: this.endTimestamp, - transaction: this.name, - type: 'transaction', - }); - } -}