Skip to content

feat(core): Add options to start standalone (segment) spans via start*Span APIs #11696

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 8 commits into from
Apr 25, 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,8 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

Sentry.init({
dsn: 'https://[email protected]/1337',
tracesSampleRate: 1.0,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Sentry.startSpan({ name: 'outer' }, () => {
Sentry.startSpan({ name: 'inner' }, () => {});
Sentry.startSpan({ name: 'standalone', experimental: { standalone: true } }, () => {});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
import { expect } from '@playwright/test';
import type { Envelope, EventEnvelope, SpanEnvelope, TransactionEvent } from '@sentry/types';

import { sentryTest } from '../../../../utils/fixtures';
import {
getMultipleSentryEnvelopeRequests,
properFullEnvelopeRequestParser,
shouldSkipTracingTest,
} from '../../../../utils/helpers';

sentryTest(
'sends a transaction and a span envelope if a standalone span is created as a child of an ongoing span tree',
async ({ getLocalTestPath, page }) => {
if (shouldSkipTracingTest()) {
sentryTest.skip();
}

const url = await getLocalTestPath({ testDir: __dirname });
const envelopes = await getMultipleSentryEnvelopeRequests<Envelope>(
page,
2,
{ url, envelopeType: ['transaction', 'span'] },
properFullEnvelopeRequestParser,
);

const spanEnvelope = envelopes.find(envelope => envelope[1][0][0].type === 'span') as SpanEnvelope;
const transactionEnvelope = envelopes.find(envelope => envelope[1][0][0].type === 'transaction') as EventEnvelope;

const spanEnvelopeHeader = spanEnvelope[0];
const spanEnvelopeItem = spanEnvelope[1][0][1];

const transactionEnvelopeHeader = transactionEnvelope[0];
const transactionEnvelopeItem = transactionEnvelope[1][0][1] as TransactionEvent;

const traceId = transactionEnvelopeHeader.trace!.trace_id!;
const parentSpanId = transactionEnvelopeItem.contexts?.trace?.span_id;

expect(traceId).toMatch(/[a-f0-9]{32}/);
expect(parentSpanId).toMatch(/[a-f0-9]{16}/);

// TODO: the span envelope also needs to contain the `trace` header (follow-up PR)
expect(spanEnvelopeHeader).toEqual({
sent_at: expect.any(String),
});

expect(transactionEnvelopeHeader).toEqual({
event_id: expect.any(String),
sdk: {
name: 'sentry.javascript.browser',
version: expect.any(String),
},
sent_at: expect.any(String),
trace: {
environment: 'production',
public_key: 'public',
sample_rate: '1',
sampled: 'true',
trace_id: traceId,
transaction: 'outer',
},
});

expect(spanEnvelopeItem).toEqual({
data: {
'sentry.origin': 'manual',
},
description: 'standalone',
segment_id: transactionEnvelopeItem.contexts?.trace?.span_id,
parent_span_id: parentSpanId,
origin: 'manual',
span_id: expect.stringMatching(/[a-f0-9]{16}/),
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
trace_id: traceId,
});

expect(transactionEnvelopeItem).toEqual({
contexts: {
trace: {
data: {
'sentry.origin': 'manual',
'sentry.sample_rate': 1,
'sentry.source': 'custom',
},
origin: 'manual',
span_id: parentSpanId,
trace_id: traceId,
},
},
environment: 'production',
event_id: expect.any(String),
platform: 'javascript',
request: {
headers: expect.any(Object),
url: expect.any(String),
},
sdk: expect.any(Object),
spans: [
{
data: {
'sentry.origin': 'manual',
},
description: 'inner',
origin: 'manual',
parent_span_id: parentSpanId,
span_id: expect.stringMatching(/[a-f0-9]{16}/),
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
trace_id: traceId,
},
],
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
transaction: 'outer',
transaction_info: {
source: 'custom',
},
type: 'transaction',
});
},
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;

Sentry.init({
dsn: 'https://[email protected]/1337',
tracesSampleRate: 1.0,
});
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Sentry.startSpan({ name: 'standalone_segment_span', experimental: { standalone: true } }, () => {});
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { expect } from '@playwright/test';
import type { SpanEnvelope } from '@sentry/types';

import { sentryTest } from '../../../../utils/fixtures';
import {
getFirstSentryEnvelopeRequest,
properFullEnvelopeRequestParser,
shouldSkipTracingTest,
} from '../../../../utils/helpers';

sentryTest('sends a segment span envelope', async ({ getLocalTestPath, page }) => {
if (shouldSkipTracingTest()) {
sentryTest.skip();
}

const url = await getLocalTestPath({ testDir: __dirname });
const spanEnvelope = await getFirstSentryEnvelopeRequest<SpanEnvelope>(page, url, properFullEnvelopeRequestParser);

const headers = spanEnvelope[0];
const item = spanEnvelope[1][0];

const itemHeader = item[0];
const spanJson = item[1];

expect(headers).toEqual({
sent_at: expect.any(String),
});

expect(itemHeader).toEqual({
type: 'span',
});

expect(spanJson).toEqual({
data: {
'sentry.origin': 'manual',
'sentry.sample_rate': 1,
'sentry.source': 'custom',
},
description: 'standalone_segment_span',
origin: 'manual',
span_id: expect.stringMatching(/^[0-9a-f]{16}$/),
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
trace_id: expect.stringMatching(/^[0-9a-f]{32}$/),
is_segment: true,
segment_id: spanJson.span_id,
});
});
7 changes: 7 additions & 0 deletions dev-packages/browser-integration-tests/utils/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,13 @@ export const properEnvelopeRequestParser = <T = Event>(request: Request | null,
return properEnvelopeParser(request)[0][envelopeIndex] as T;
};

export const properFullEnvelopeRequestParser = <T extends Envelope>(request: Request | null): T => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';

return parseEnvelope(envelope) as T;
};

export const envelopeHeaderRequestParser = (request: Request | null): EventEnvelopeHeaders => {
// https://develop.sentry.dev/sdk/envelopes/
const envelope = request?.postData() || '';
Expand Down
70 changes: 61 additions & 9 deletions packages/core/src/tracing/sentrySpan.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
SpanAttributeValue,
SpanAttributes,
SpanContextData,
SpanEnvelope,
SpanJSON,
SpanOrigin,
SpanStatus,
Expand All @@ -16,6 +17,7 @@ import { dropUndefinedKeys, logger, timestampInSeconds, uuid4 } from '@sentry/ut
import { getClient, getCurrentScope } from '../currentScopes';
import { DEBUG_BUILD } from '../debug-build';

import { createSpanEnvelope } from '../envelope';
import { getMetricSummaryJsonForSpan } from '../metrics/metric-summary';
import {
SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME,
Expand Down Expand Up @@ -58,6 +60,9 @@ export class SentrySpan implements Span {
/** The timed events added to this span. */
protected _events: TimedEvent[];

/** if true, treat span as a standalone span (not part of a transaction) */
private _isStandaloneSpan?: boolean;

/**
* You should never call the constructor manually, always use `Sentry.startSpan()`
* or other span methods.
Expand Down Expand Up @@ -96,6 +101,8 @@ export class SentrySpan implements Span {
if (this._endTime) {
this._onSpanEnded();
}

this._isStandaloneSpan = spanContext.isStandalone;
}

/** @inheritdoc */
Expand Down Expand Up @@ -188,6 +195,8 @@ export class SentrySpan implements Span {
profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] as string | undefined,
exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] as number | undefined,
measurements: timedEventsToMeasurements(this._events),
is_segment: (this._isStandaloneSpan && getRootSpan(this) === this) || undefined,
segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : undefined,
});
}

Expand Down Expand Up @@ -220,20 +229,44 @@ export class SentrySpan implements Span {
return this;
}

/**
* This method should generally not be used,
* but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set.
* USE THIS WITH CAUTION!
* @internal
* @hidden
* @experimental
*/
public isStandaloneSpan(): boolean {
return !!this._isStandaloneSpan;
}

/** Emit `spanEnd` when the span is ended. */
private _onSpanEnded(): void {
const client = getClient();
if (client) {
client.emit('spanEnd', this);
}

// If this is a root span, send it when it is endedf
if (this === getRootSpan(this)) {
const transactionEvent = this._convertSpanToTransaction();
if (transactionEvent) {
const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();
scope.captureEvent(transactionEvent);
}
// A segment span is basically the root span of a local span tree.
// So for now, this is either what we previously refer to as the root span,
// or a standalone span.
const isSegmentSpan = this._isStandaloneSpan || this === getRootSpan(this);

if (!isSegmentSpan) {
return;
}

// if this is a standalone span, we send it immediately
if (this._isStandaloneSpan) {
sendSpanEnvelope(createSpanEnvelope([this]));
return;
}

const transactionEvent = this._convertSpanToTransaction();
if (transactionEvent) {
const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();
scope.captureEvent(transactionEvent);
}
}

Expand Down Expand Up @@ -266,8 +299,8 @@ export class SentrySpan implements Span {
return undefined;
}

// The transaction span itself should be filtered out
const finishedSpans = getSpanDescendants(this).filter(span => span !== this);
// The transaction span itself as well as any potential standalone spans should be filtered out
const finishedSpans = getSpanDescendants(this).filter(span => span !== this && !isStandaloneSpan(span));

const spans = finishedSpans.map(span => spanToJSON(span)).filter(isFullFinishedSpan);

Expand Down Expand Up @@ -318,3 +351,22 @@ function isSpanTimeInput(value: undefined | SpanAttributes | SpanTimeInput): val
function isFullFinishedSpan(input: Partial<SpanJSON>): input is SpanJSON {
return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id;
}

/** `SentrySpan`s can be sent as a standalone span rather than belonging to a transaction */
function isStandaloneSpan(span: Span): boolean {
return span instanceof SentrySpan && span.isStandaloneSpan();
}

function sendSpanEnvelope(envelope: SpanEnvelope): void {
const client = getClient();
if (!client) {
return;
}

const transport = client.getTransport();
if (transport) {
transport.send(envelope).then(null, reason => {
DEBUG_BUILD && logger.error('Error while sending span:', reason);
});
}
}
18 changes: 12 additions & 6 deletions packages/core/src/tracing/trace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ export function startSpan<T>(context: StartSpanOptions, callback: (span: Span) =
const shouldSkipSpan = context.onlyIfParent && !parentSpan;
const activeSpan = shouldSkipSpan
? new SentryNonRecordingSpan()
: createChildSpanOrTransaction({
: createChildOrRootSpan({
parentSpan,
spanContext,
forceTransaction: context.forceTransaction,
Expand Down Expand Up @@ -92,7 +92,7 @@ export function startSpanManual<T>(context: StartSpanOptions, callback: (span: S
const shouldSkipSpan = context.onlyIfParent && !parentSpan;
const activeSpan = shouldSkipSpan
? new SentryNonRecordingSpan()
: createChildSpanOrTransaction({
: createChildOrRootSpan({
parentSpan,
spanContext,
forceTransaction: context.forceTransaction,
Expand Down Expand Up @@ -144,7 +144,7 @@ export function startInactiveSpan(context: StartSpanOptions): Span {
return new SentryNonRecordingSpan();
}

return createChildSpanOrTransaction({
return createChildOrRootSpan({
parentSpan,
spanContext,
forceTransaction: context.forceTransaction,
Expand Down Expand Up @@ -212,7 +212,7 @@ export function suppressTracing<T>(callback: () => T): T {
});
}

function createChildSpanOrTransaction({
function createChildOrRootSpan({
parentSpan,
spanContext,
forceTransaction,
Expand Down Expand Up @@ -291,14 +291,20 @@ function createChildSpanOrTransaction({
* Eventually the StartSpanOptions will be more aligned with OpenTelemetry.
*/
function normalizeContext(context: StartSpanOptions): SentrySpanArguments {
const exp = context.experimental || {};
const initialCtx: SentrySpanArguments = {
isStandalone: exp.standalone,
...context,
};

if (context.startTime) {
const ctx: SentrySpanArguments & { startTime?: SpanTimeInput } = { ...context };
const ctx: SentrySpanArguments & { startTime?: SpanTimeInput } = { ...initialCtx };
ctx.startTimestamp = spanTimeInputToSeconds(context.startTime);
delete ctx.startTime;
return ctx;
}

return context;
return initialCtx;
}

function getAcs(): AsyncContextStrategy {
Expand Down
Loading
Loading