Skip to content
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

feat(replay): Add replay_id to transaction DSC #7571

Merged
merged 6 commits into from
Mar 23, 2023
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
23 changes: 23 additions & 0 deletions packages/browser-integration-tests/suites/replay/dsc/init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import * as Sentry from '@sentry/browser';
import { Integrations } from '@sentry/tracing';

window.Sentry = Sentry;
window.Replay = new Sentry.Replay({
flushMinDelay: 200,
flushMaxDelay: 200,
useCompression: false,
});

Sentry.init({
dsn: 'https://[email protected]/1337',
integrations: [new Integrations.BrowserTracing({ tracingOrigins: [/.*/] }), window.Replay],
environment: 'production',
tracesSampleRate: 1,
replaysSessionSampleRate: 0.0,
replaysOnErrorSampleRate: 1.0,
});

Sentry.configureScope(scope => {
scope.setUser({ id: 'user123', segment: 'segmentB' });
scope.setTransactionName('testTransactionDSC');
});
33 changes: 33 additions & 0 deletions packages/browser-integration-tests/suites/replay/dsc/test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { expect } from '@playwright/test';
import type { EventEnvelopeHeaders } from '@sentry/types';

import { sentryTest } from '../../../utils/fixtures';
import { envelopeHeaderRequestParser, getFirstSentryEnvelopeRequest } from '../../../utils/helpers';
import { getReplaySnapshot, shouldSkipReplayTest, waitForReplayRunning } from '../../../utils/replayHelpers';

sentryTest('should add replay_id to dsc of transactions', async ({ getLocalTestPath, page, browserName }) => {
// This is flaky on webkit, so skipping there...
if (shouldSkipReplayTest() || browserName === 'webkit') {
sentryTest.skip();
}

const url = await getLocalTestPath({ testDir: __dirname });
await page.goto(url);

const envHeader = await getFirstSentryEnvelopeRequest<EventEnvelopeHeaders>(page, url, envelopeHeaderRequestParser);

await waitForReplayRunning(page);
const replay = await getReplaySnapshot(page);

expect(replay.session?.id).toBeDefined();

expect(envHeader.trace).toBeDefined();
expect(envHeader.trace).toEqual({
environment: 'production',
user_segment: 'segmentB',
sample_rate: '1',
trace_id: expect.any(String),
public_key: 'public',
replay_id: replay.session?.id,
});
});
10 changes: 10 additions & 0 deletions packages/browser-integration-tests/utils/replayHelpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,16 @@ function isCustomSnapshot(event: RecordingEvent): event is RecordingEvent & { da
return event.type === EventType.Custom;
}

/** Wait for replay to be running & available. */
export async function waitForReplayRunning(page: Page): Promise<void> {
await page.waitForFunction(() => {
const replayIntegration = (window as unknown as Window & { Replay: { _replay: ReplayContainer } }).Replay;
const replay = replayIntegration._replay;

return replay.isEnabled() && replay.session?.id !== undefined;
});
}

/**
* This returns the replay container (assuming it exists).
* Note that due to how this works with playwright, this is a POJO copy of replay.
Expand Down
7 changes: 7 additions & 0 deletions packages/core/src/baseclient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type {
ClientOptions,
DataCategory,
DsnComponents,
DynamicSamplingContext,
Envelope,
ErrorEvent,
Event,
Expand Down Expand Up @@ -378,6 +379,9 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
/** @inheritdoc */
public on(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;

/** @inheritdoc */
public on(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;

/** @inheritdoc */
public on(hook: string, callback: unknown): void {
if (!this._hooks[hook]) {
Expand All @@ -400,6 +404,9 @@ export abstract class BaseClient<O extends ClientOptions> implements Client<O> {
/** @inheritdoc */
public emit(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;

/** @inheritdoc */
public emit(hook: 'createDsc', dsc: DynamicSamplingContext): void;

/** @inheritdoc */
public emit(hook: string, ...rest: unknown[]): void {
if (this._hooks[hook]) {
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/tracing/transaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,8 @@ export class Transaction extends SpanClass implements TransactionInterface {
// Uncomment if we want to make DSC immutable
// this._frozenDynamicSamplingContext = dsc;

client.emit && client.emit('createDsc', dsc);

return dsc;
}
}
23 changes: 16 additions & 7 deletions packages/replay/src/util/addGlobalListeners.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { BaseClient } from '@sentry/core';
import { addGlobalEventProcessor, getCurrentHub } from '@sentry/core';
import type { Client, DynamicSamplingContext } from '@sentry/types';
import { addInstrumentationHandler } from '@sentry/utils';

import { handleAfterSendEvent } from '../coreHandlers/handleAfterSendEvent';
Expand All @@ -25,15 +26,23 @@ export function addGlobalListeners(replay: ReplayContainer): void {
addInstrumentationHandler('history', handleHistorySpanListener(replay));
handleNetworkBreadcrumbs(replay);

// If a custom client has no hooks yet, we continue to use the "old" implementation
const hasHooks = !!(client && client.on);

// Tag all (non replay) events that get sent to Sentry with the current
// replay ID so that we can reference them later in the UI
addGlobalEventProcessor(handleGlobalEventListener(replay, !hasHooks));
addGlobalEventProcessor(handleGlobalEventListener(replay, !hasHooks(client)));

if (hasHooks) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(client as BaseClient<any>).on('afterSendEvent', handleAfterSendEvent(replay));
// If a custom client has no hooks yet, we continue to use the "old" implementation
if (hasHooks(client)) {
client.on('afterSendEvent', handleAfterSendEvent(replay));
client.on('createDsc', (dsc: DynamicSamplingContext) => {
const replayId = replay.getSessionId();
if (replayId) {
dsc.replay_id = replayId;
}
});
}
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
function hasHooks(client: Client | undefined): client is BaseClient<any> {
return !!(client && client.on);
}
14 changes: 12 additions & 2 deletions packages/types/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type { Breadcrumb, BreadcrumbHint } from './breadcrumb';
import type { EventDropReason } from './clientreport';
import type { DataCategory } from './datacategory';
import type { DsnComponents } from './dsn';
import type { Envelope } from './envelope';
import type { DynamicSamplingContext, Envelope } from './envelope';
import type { Event, EventHint } from './event';
import type { Integration, IntegrationClass } from './integration';
import type { ClientOptions } from './options';
Expand Down Expand Up @@ -177,6 +177,11 @@ export interface Client<O extends ClientOptions = ClientOptions> {
*/
on?(hook: 'beforeAddBreadcrumb', callback: (breadcrumb: Breadcrumb, hint?: BreadcrumbHint) => void): void;

/**
* Register a callback whena DSC (Dynamic Sampling Context) is created.
*/
on?(hook: 'createDsc', callback: (dsc: DynamicSamplingContext) => void): void;

/**
* Fire a hook event for transaction start and finish. Expects to be given a transaction as the
* second argument.
Expand All @@ -196,7 +201,12 @@ export interface Client<O extends ClientOptions = ClientOptions> {
emit?(hook: 'afterSendEvent', event: Event, sendResponse: TransportMakeRequestResponse | void): void;

/**
* Fire a hook for when a bredacrumb is added. Expects the breadcrumb as second argument.
* Fire a hook for when a breadcrumb is added. Expects the breadcrumb as second argument.
*/
emit?(hook: 'beforeAddBreadcrumb', breadcrumb: Breadcrumb, hint?: BreadcrumbHint): void;

/**
* Fire a hook for when a DSC (Dynamic Sampling Context) is created. Expects the DSC as second argument.
*/
emit?(hook: 'createDsc', dsc: DynamicSamplingContext): void;
}
1 change: 1 addition & 0 deletions packages/types/src/envelope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ export type DynamicSamplingContext = {
environment?: string;
transaction?: string;
user_segment?: string;
replay_id?: string;
};

export type EnvelopeItemType =
Expand Down