Skip to content

feat(browser): Use idle span for browser tracing #10957

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Mar 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

Sentry.init({
dsn: 'https://[email protected]/1337',
integrations: [
Sentry.browserTracingIntegration({
// To avoid having this test run for 15s
childSpanTimeout: 4000,
}),
],
defaultIntegrations: false,
tracesSampleRate: 1,
});

const activeSpan = Sentry.getActiveSpan();
if (activeSpan) {
Sentry.startInactiveSpan({ name: 'pageload-child-span' });
} else {
setTimeout(() => {
Sentry.startInactiveSpan({ name: 'pageload-child-span' });
}, 200);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { expect } from '@playwright/test';

import { sentryTest } from '../../../../utils/fixtures';
import {
envelopeRequestParser,
shouldSkipTracingTest,
waitForTransactionRequestOnUrl,
} from '../../../../utils/helpers';

// This tests asserts that the pageload span will finish itself after the child span timeout if it
// has a child span without adding any additional ones or finishing any of them finishing. All of the child spans that
// are still running should have the status "cancelled".
sentryTest('should send a pageload span terminated via child span timeout', async ({ getLocalTestUrl, page }) => {
if (shouldSkipTracingTest()) {
sentryTest.skip();
}

const url = await getLocalTestUrl({ testDir: __dirname });
const req = await waitForTransactionRequestOnUrl(page, url);

const eventData = envelopeRequestParser(req);

expect(eventData.contexts?.trace?.op).toBe('pageload');
expect(eventData.spans?.length).toBeGreaterThanOrEqual(1);
const testSpan = eventData.spans?.find(span => span.description === 'pageload-child-span');
expect(testSpan).toBeDefined();
expect(testSpan?.status).toBe('cancelled');
});

This file was deleted.

This file was deleted.

3 changes: 3 additions & 0 deletions packages/core/src/semanticAttributes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,3 +19,6 @@ export const SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';
* Use this attribute to represent the origin of a span.
*/
export const SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';

/** The reason why an idle span finished. */
export const SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = 'sentry.idle_span_finish_reason';
49 changes: 0 additions & 49 deletions packages/core/src/tracing/hubextensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import type { ClientOptions, CustomSamplingContext, Hub, TransactionContext } fr
import { getMainCarrier } from '../asyncContext';

import { registerErrorInstrumentation } from './errors';
import { IdleTransaction } from './idletransaction';
import { sampleTransaction } from './sampling';
import { Transaction } from './transaction';

Expand Down Expand Up @@ -53,54 +52,6 @@ function _startTransaction(
return transaction;
}

/**
* Create new idle transaction.
*/
export function startIdleTransaction(
hub: Hub,
transactionContext: TransactionContext,
idleTimeout: number,
finalTimeout: number,
onScope?: boolean,
customSamplingContext?: CustomSamplingContext,
heartbeatInterval?: number,
delayAutoFinishUntilSignal: boolean = false,
): IdleTransaction {
// eslint-disable-next-line deprecation/deprecation
const client = hub.getClient();
const options: Partial<ClientOptions> = (client && client.getOptions()) || {};

// eslint-disable-next-line deprecation/deprecation
let transaction = new IdleTransaction(
transactionContext,
hub,
idleTimeout,
finalTimeout,
heartbeatInterval,
onScope,
delayAutoFinishUntilSignal,
);
transaction = sampleTransaction(transaction, options, {
name: transactionContext.name,
parentSampled: transactionContext.parentSampled,
transactionContext,
attributes: {
// eslint-disable-next-line deprecation/deprecation
...transactionContext.data,
...transactionContext.attributes,
},
...customSamplingContext,
});
if (transaction.isRecording()) {
transaction.initSpanRecorder();
}
if (client) {
client.emit('startTransaction', transaction);
client.emit('spanStart', transaction);
}
return transaction;
}

/**
* Adds tracing extensions to the global hub.
*/
Expand Down
53 changes: 41 additions & 12 deletions packages/core/src/tracing/idleSpan.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import type { Span, StartSpanOptions } from '@sentry/types';
import type { Span, SpanAttributes, StartSpanOptions } from '@sentry/types';
import { logger, timestampInSeconds } from '@sentry/utils';
import { getClient, getCurrentScope } from '../currentScopes';

import { DEBUG_BUILD } from '../debug-build';
import { SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '../semanticAttributes';
import { hasTracingEnabled } from '../utils/hasTracingEnabled';
import { getSpanDescendants, removeChildSpanFromSpan, spanToJSON } from '../utils/spanUtils';
import { getSpanDescendants, removeChildSpanFromSpan, spanTimeInputToSeconds, spanToJSON } from '../utils/spanUtils';
import { SentryNonRecordingSpan } from './sentryNonRecordingSpan';
import { SPAN_STATUS_ERROR } from './spanstatus';
import { startInactiveSpan } from './trace';
Expand All @@ -16,8 +17,6 @@ export const TRACING_DEFAULTS = {
childSpanTimeout: 15_000,
};

const FINISH_REASON_TAG = 'finishReason';

const FINISH_REASON_HEARTBEAT_FAILED = 'heartbeatFailed';
const FINISH_REASON_IDLE_TIMEOUT = 'idleTimeout';
const FINISH_REASON_FINAL_TIMEOUT = 'finalTimeout';
Expand Down Expand Up @@ -108,6 +107,36 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti
const previousActiveSpan = getActiveSpan();
const span = _startIdleSpan(startSpanOptions);

function _endSpan(timestamp: number = timestampInSeconds()): void {
// Ensure we end with the last span timestamp, if possible
const spans = getSpanDescendants(span).filter(child => child !== span);

// If we have no spans, we just end, nothing else to do here
if (!spans.length) {
span.end(timestamp);
return;
}

const childEndTimestamps = spans
.map(span => spanToJSON(span).timestamp)
.filter(timestamp => !!timestamp) as number[];
const latestSpanEndTimestamp = childEndTimestamps.length ? Math.max(...childEndTimestamps) : undefined;

const spanEndTimestamp = spanTimeInputToSeconds(timestamp);
const spanStartTimestamp = spanToJSON(span).start_timestamp;

// The final endTimestamp should:
// * Never be before the span start timestamp
// * Be the latestSpanEndTimestamp, if there is one, and it is smaller than the passed span end timestamp
// * Otherwise be the passed end timestamp
const endTimestamp = Math.max(
spanStartTimestamp || -Infinity,
Math.min(spanEndTimestamp, latestSpanEndTimestamp || Infinity),
);

span.end(endTimestamp);
}

/**
* Cancels the existing idle timeout, if there is one.
*/
Expand Down Expand Up @@ -136,7 +165,7 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti
_idleTimeoutID = setTimeout(() => {
if (!_finished && activities.size === 0 && _autoFinishAllowed) {
_finishReason = FINISH_REASON_IDLE_TIMEOUT;
span.end(endTimestamp);
_endSpan(endTimestamp);
}
}, idleTimeout);
}
Expand All @@ -149,7 +178,7 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti
_idleTimeoutID = setTimeout(() => {
if (!_finished && _autoFinishAllowed) {
_finishReason = FINISH_REASON_HEARTBEAT_FAILED;
span.end(endTimestamp);
_endSpan(endTimestamp);
}
}, childSpanTimeout);
}
Expand Down Expand Up @@ -190,7 +219,7 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti
}
}

function endIdleSpan(): void {
function onIdleSpanEnded(): void {
_finished = true;
activities.clear();

Expand All @@ -209,9 +238,9 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti
return;
}

const attributes = spanJSON.data || {};
if (spanJSON.op === 'ui.action.click' && !attributes[FINISH_REASON_TAG]) {
span.setAttribute(FINISH_REASON_TAG, _finishReason);
const attributes: SpanAttributes = spanJSON.data || {};
if (spanJSON.op === 'ui.action.click' && !attributes[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]) {
span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason);
}

DEBUG_BUILD &&
Expand Down Expand Up @@ -279,7 +308,7 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti
_popActivity(endedSpan.spanContext().spanId);

if (endedSpan === span) {
endIdleSpan();
onIdleSpanEnded();
}
});

Expand All @@ -303,7 +332,7 @@ export function startIdleSpan(startSpanOptions: StartSpanOptions, options: Parti
if (!_finished) {
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' });
_finishReason = FINISH_REASON_FINAL_TIMEOUT;
span.end();
_endSpan();
}
}, finalTimeout);

Expand Down
Loading