Skip to content

feat(core): Add trace envelope header to span envelope #11699

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 4 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
Expand Up @@ -38,9 +38,16 @@ sentryTest(
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),
trace: {
environment: 'production',
public_key: 'public',
sample_rate: '1',
sampled: 'true',
trace_id: traceId,
transaction: 'outer',
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So just to point this out: In a hyptothetical scenario, where a standalone span is created during an active transaction, it's DSC/trace header will be inherited from the active span tree's DSC. I think this is okay for now at least, since it guarantees DS and trace stability as long as one trace is active. Also this scenario is not going to happen in the SDK for how we plan on using standalone for http.client and INP spans.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

makes sense still for it to be this way! 👍

},
});

expect(transactionEnvelopeHeader).toEqual({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,18 @@ sentryTest('sends a segment span envelope', async ({ getLocalTestPath, page }) =
const itemHeader = item[0];
const spanJson = item[1];

const traceId = spanJson.trace_id;

expect(headers).toEqual({
sent_at: expect.any(String),
trace: {
environment: 'production',
public_key: 'public',
sample_rate: '1',
sampled: 'true',
trace_id: traceId,
transaction: 'standalone_segment_span',
},
});

expect(itemHeader).toEqual({
Expand Down
14 changes: 12 additions & 2 deletions packages/core/src/envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type {
Attachment,
AttachmentItem,
DsnComponents,
DynamicSamplingContext,
Event,
EventEnvelope,
EventItem,
Expand All @@ -21,7 +22,7 @@ import {
getSdkMetadataForEnvelopeHeader,
} from '@sentry/utils';
import { createSpanEnvelopeItem } from '@sentry/utils';
import type { SentrySpan } from './tracing';
import { type SentrySpan, getDynamicSamplingContextFromSpan } from './tracing';
import { spanToJSON } from './utils/spanUtils';

/**
Expand Down Expand Up @@ -126,10 +127,19 @@ export function createAttachmentEnvelope(
* Create envelope from Span item.
*/
export function createSpanEnvelope(spans: SentrySpan[]): SpanEnvelope {
function dscHasRequiredProps(dsc: Partial<DynamicSamplingContext>): dsc is DynamicSamplingContext {
return !!dsc.trace_id && !!dsc.public_key;
}

// For the moment we'll obtain the DSC from the first span in the array
// This might need to be changed if we permit sending multiple spans from
// different segments in one envelope
const dsc = getDynamicSamplingContextFromSpan(spans[0]);

const headers: SpanEnvelope[0] = {
sent_at: new Date().toISOString(),
...(dscHasRequiredProps(dsc) && { trace: dsc }),
};

const items = spans.map(span => createSpanEnvelopeItem(spanToJSON(span)));
return createEnvelope<SpanEnvelope>(headers, items);
}
87 changes: 85 additions & 2 deletions packages/core/test/lib/envelope.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import type { DsnComponents, DynamicSamplingContext, Event } from '@sentry/types';
import type { Client, DsnComponents, DynamicSamplingContext, Event } from '@sentry/types';

import { createEventEnvelope } from '../../src/envelope';
import {
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
SentrySpan,
getCurrentScope,
getIsolationScope,
setAsyncContextStrategy,
setCurrentClient,
} from '../../src';
import { createEventEnvelope, createSpanEnvelope } from '../../src/envelope';
import { TestClient, getDefaultTestClientOptions } from '../mocks/client';

const testDsn: DsnComponents = { protocol: 'https', projectId: 'abc', host: 'testry.io', publicKey: 'pubKey123' };

Expand Down Expand Up @@ -75,3 +84,77 @@ describe('createEventEnvelope', () => {
});
});
});

describe('createSpanEnvelope', () => {
let client: Client | undefined;
beforeEach(() => {
getCurrentScope().clear();
getIsolationScope().clear();
setAsyncContextStrategy(undefined);
const options = getDefaultTestClientOptions({ tracesSampleRate: 1, dsn: 'https://username@domain/123' });
client = new TestClient(options);
setCurrentClient(client);
client.init();
});

it('creates a span envelope', () => {
const span = new SentrySpan({
name: 'test',
isStandalone: true,
startTimestamp: 1,
endTimestamp: 2,
sampled: true,
attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom' },
});

const spanEnvelope = createSpanEnvelope([span]);

const spanItem = spanEnvelope[1][0][1];
expect(spanItem).toEqual({
data: {
'sentry.origin': 'manual',
'sentry.source': 'custom',
},
description: 'test',
is_segment: true,
origin: 'manual',
span_id: expect.stringMatching(/^[0-9a-f]{16}$/),
segment_id: spanItem.segment_id,
start_timestamp: 1,
timestamp: 2,
trace_id: expect.stringMatching(/^[0-9a-f]{32}$/),
});
});

it('adds `trace` and `sent_at` envelope headers', () => {
const spanEnvelope = createSpanEnvelope([
new SentrySpan({ name: 'test', attributes: { [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom' } }),
]);

const spanEnvelopeHeaders = spanEnvelope[0];
expect(spanEnvelopeHeaders).toEqual({
sent_at: expect.any(String),
trace: {
environment: 'production',
public_key: 'username',
sampled: 'false',
trace_id: expect.stringMatching(/^[0-9a-f]{32}$/),
transaction: 'test',
},
});
});

it("doesn't add a `trace` envelope header if there's no public key", () => {
const options = getDefaultTestClientOptions({ tracesSampleRate: 1, dsn: 'https://domain/123' });
client = new TestClient(options);
setCurrentClient(client);
client.init();

const spanEnvelope = createSpanEnvelope([new SentrySpan()]);

const spanEnvelopeHeaders = spanEnvelope[0];
expect(spanEnvelopeHeaders).toEqual({
sent_at: expect.any(String),
});
});
});
Loading