Skip to content
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,18 @@
import * as Sentry from '@sentry/browser';

window.Sentry = Sentry;
window.Replay = Sentry.replayIntegration({
flushMinDelay: 200,
flushMaxDelay: 200,
minReplayDuration: 0,
stickySession: true,
});

Sentry.init({
dsn: 'https://public@dsn.ingest.sentry.io/1337',
sampleRate: 1,
replaysSessionSampleRate: 0.0,
replaysOnErrorSampleRate: 1.0,

integrations: [window.Replay],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
document.getElementById('error1').addEventListener('click', () => {
throw new Error('First Error');
});

document.getElementById('error2').addEventListener('click', () => {
throw new Error('Second Error');
});

document.getElementById('click').addEventListener('click', () => {
// Just a click for interaction
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<button id="error1">Throw First Error</button>
<button id="error2">Throw Second Error</button>
<button id="click">Click me</button>
</body>
</html>
Original file line number Diff line number Diff line change
@@ -0,0 +1,270 @@
import { expect } from '@playwright/test';
import { sentryTest } from '../../../utils/fixtures';
import { envelopeRequestParser, waitForErrorRequest } from '../../../utils/helpers';
import {
getReplaySnapshot,
isReplayEvent,
shouldSkipReplayTest,
waitForReplayRunning,
} from '../../../utils/replayHelpers';

sentryTest(
'buffer mode remains after interrupting error event ingest',
async ({ getLocalTestUrl, page, browserName }) => {
if (shouldSkipReplayTest() || browserName === 'webkit') {
sentryTest.skip();
}

let errorCount = 0;
let replayCount = 0;
const errorEventIds: string[] = [];
const replayIds: string[] = [];
let firstReplayEventResolved: (value?: unknown) => void = () => {};
// Need TS 5.7 for withResolvers
const firstReplayEventPromise = new Promise(resolve => {
firstReplayEventResolved = resolve;
});

const url = await getLocalTestUrl({ testDir: __dirname, skipDsnRouteHandler: true });

await page.route('https://dsn.ingest.sentry.io/**/*', async route => {
const event = envelopeRequestParser(route.request());

// Track error events
if (event && !event.type && event.event_id) {
errorCount++;
errorEventIds.push(event.event_id);
if (event.tags?.replayId) {
replayIds.push(event.tags.replayId as string);

if (errorCount === 1) {
firstReplayEventResolved();
// intentional so that it never resolves, we'll force a reload instead to interrupt the normal flow
await new Promise(resolve => setTimeout(resolve, 100000));
}
}
}

// Track replay events and simulate failure for the first replay
if (event && isReplayEvent(event)) {
replayCount++;
}

// Success for other requests
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'test-id' }),
});
});

await page.goto(url);

// Wait for replay to initialize
await waitForReplayRunning(page);

waitForErrorRequest(page);
await page.locator('#error1').click();

// This resolves, but the route doesn't get fulfilled as we want the reload to "interrupt" this flow
await firstReplayEventPromise;
expect(errorCount).toBe(1);
expect(replayCount).toBe(0);
expect(replayIds).toHaveLength(1);

const firstSession = await getReplaySnapshot(page);
const firstSessionId = firstSession.session?.id;
expect(firstSessionId).toBeDefined();
expect(firstSession.session?.sampled).toBe('buffer');
expect(firstSession.session?.dirty).toBe(true);
expect(firstSession.recordingMode).toBe('buffer');

await page.reload();
const secondSession = await getReplaySnapshot(page);
expect(secondSession.session?.sampled).toBe('buffer');
expect(secondSession.session?.dirty).toBe(true);
expect(secondSession.recordingMode).toBe('buffer');
expect(secondSession.session?.id).toBe(firstSessionId);
expect(secondSession.session?.segmentId).toBe(0);
},
);

sentryTest('buffer mode remains after interrupting replay flush', async ({ getLocalTestUrl, page, browserName }) => {
if (shouldSkipReplayTest() || browserName === 'webkit') {
sentryTest.skip();
}

let errorCount = 0;
let replayCount = 0;
const errorEventIds: string[] = [];
const replayIds: string[] = [];
let firstReplayEventResolved: (value?: unknown) => void = () => {};
// Need TS 5.7 for withResolvers
const firstReplayEventPromise = new Promise(resolve => {
firstReplayEventResolved = resolve;
});

const url = await getLocalTestUrl({ testDir: __dirname, skipDsnRouteHandler: true });

await page.route('https://dsn.ingest.sentry.io/**/*', async route => {
const event = envelopeRequestParser(route.request());

// Track error events
if (event && !event.type && event.event_id) {
errorCount++;
errorEventIds.push(event.event_id);
if (event.tags?.replayId) {
replayIds.push(event.tags.replayId as string);
}
}

// Track replay events and simulate failure for the first replay
if (event && isReplayEvent(event)) {
replayCount++;
if (replayCount === 1) {
firstReplayEventResolved();
// intentional so that it never resolves, we'll force a reload instead to interrupt the normal flow
await new Promise(resolve => setTimeout(resolve, 100000));
}
}

// Success for other requests
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'test-id' }),
});
});

await page.goto(url);

// Wait for replay to initialize
await waitForReplayRunning(page);

await page.locator('#error1').click();
await firstReplayEventPromise;
expect(errorCount).toBe(1);
expect(replayCount).toBe(1);
expect(replayIds).toHaveLength(1);

// Get the first session info
const firstSession = await getReplaySnapshot(page);
const firstSessionId = firstSession.session?.id;
expect(firstSessionId).toBeDefined();
expect(firstSession.session?.sampled).toBe('buffer');
expect(firstSession.session?.dirty).toBe(true);
expect(firstSession.recordingMode).toBe('buffer'); // But still in buffer mode

await page.reload();
await waitForReplayRunning(page);
const secondSession = await getReplaySnapshot(page);
expect(secondSession.session?.sampled).toBe('buffer');
expect(secondSession.session?.dirty).toBe(true);
expect(secondSession.session?.id).toBe(firstSessionId);
expect(secondSession.session?.segmentId).toBe(1);
// Because a flush attempt was made and not allowed to complete, segmentId increased from 0,
// so we resume in session mode
expect(secondSession.recordingMode).toBe('session');
});

sentryTest(
'starts a new session after interrupting replay flush and session "expires"',
async ({ getLocalTestUrl, page, browserName }) => {
if (shouldSkipReplayTest() || browserName === 'webkit') {
sentryTest.skip();
}

let errorCount = 0;
let replayCount = 0;
const errorEventIds: string[] = [];
const replayIds: string[] = [];
let firstReplayEventResolved: (value?: unknown) => void = () => {};
// Need TS 5.7 for withResolvers
const firstReplayEventPromise = new Promise(resolve => {
firstReplayEventResolved = resolve;
});

const url = await getLocalTestUrl({ testDir: __dirname, skipDsnRouteHandler: true });

await page.route('https://dsn.ingest.sentry.io/**/*', async route => {
const event = envelopeRequestParser(route.request());

// Track error events
if (event && !event.type && event.event_id) {
errorCount++;
errorEventIds.push(event.event_id);
if (event.tags?.replayId) {
replayIds.push(event.tags.replayId as string);
}
}

// Track replay events and simulate failure for the first replay
if (event && isReplayEvent(event)) {
replayCount++;
if (replayCount === 1) {
firstReplayEventResolved();
// intentional so that it never resolves, we'll force a reload instead to interrupt the normal flow
await new Promise(resolve => setTimeout(resolve, 100000));
}
}

// Success for other requests
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'test-id' }),
});
});

await page.goto(url);

// Wait for replay to initialize
await waitForReplayRunning(page);

// Trigger first error - this should change session sampled to "session"
await page.locator('#error1').click();
await firstReplayEventPromise;
expect(errorCount).toBe(1);
expect(replayCount).toBe(1);
expect(replayIds).toHaveLength(1);

// Get the first session info
const firstSession = await getReplaySnapshot(page);
const firstSessionId = firstSession.session?.id;
expect(firstSessionId).toBeDefined();
expect(firstSession.session?.sampled).toBe('buffer');
expect(firstSession.session?.dirty).toBe(true);
expect(firstSession.recordingMode).toBe('buffer'); // But still in buffer mode

// Now expire the session by manipulating session storage
// Simulate session expiry by setting lastActivity to a time in the past
await page.evaluate(() => {
const replayIntegration = (window as any).Replay;
const replay = replayIntegration['_replay'];

// Set session as expired (15 minutes ago)
if (replay.session) {
const fifteenMinutesAgo = Date.now() - 15 * 60 * 1000;
replay.session.lastActivity = fifteenMinutesAgo;
replay.session.started = fifteenMinutesAgo;

// Also update session storage if sticky sessions are enabled
const sessionKey = 'sentryReplaySession';
const sessionData = sessionStorage.getItem(sessionKey);
if (sessionData) {
const session = JSON.parse(sessionData);
session.lastActivity = fifteenMinutesAgo;
session.started = fifteenMinutesAgo;
sessionStorage.setItem(sessionKey, JSON.stringify(session));
}
}
});

await page.reload();
const secondSession = await getReplaySnapshot(page);
expect(secondSession.session?.sampled).toBe('buffer');
expect(secondSession.recordingMode).toBe('buffer');
expect(secondSession.session?.id).not.toBe(firstSessionId);
expect(secondSession.session?.segmentId).toBe(0);
},
);
15 changes: 15 additions & 0 deletions packages/replay-internal/src/coreHandlers/handleGlobalEvent.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Event, EventHint } from '@sentry/core';
import { DEBUG_BUILD } from '../debug-build';
import { saveSession } from '../session/saveSession';
import type { ReplayContainer } from '../types';
import { isErrorEvent, isFeedbackEvent, isReplayEvent, isTransactionEvent } from '../util/eventUtils';
import { isRrwebError } from '../util/isRrwebError';
Expand Down Expand Up @@ -69,6 +70,20 @@ export function handleGlobalEventListener(replay: ReplayContainer): (event: Even
event.tags = { ...event.tags, replayId: replay.getSessionId() };
}

// If we sampled this error in buffer mode, immediately mark the session as "sampled"
// by changing the sampled state from 'buffer' to 'session'. Otherwise, if the application is interrupte
// before `afterSendEvent` occurs, then the session would remain as "buffer" but we have an error event
// that is tagged with a replay id. This could end up creating replays w/ excessive durations because
// of the linked error.
if (isErrorEventSampled && replay.recordingMode === 'buffer' && replay.session?.sampled === 'buffer') {
const session = replay.session;
session.dirty = true;
// Save the session if sticky sessions are enabled to persist the state change
if (replay.getOptions().stickySession) {
saveSession(session);
}
}

return event;
},
{ id: 'Replay' },
Expand Down
1 change: 1 addition & 0 deletions packages/replay-internal/src/replay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -606,6 +606,7 @@ export class ReplayContainer implements ReplayContainerInterface {

// Once this session ends, we do not want to refresh it
if (this.session) {
this.session.dirty = false;
this._updateUserActivity(activityTime);
this._updateSessionActivity(activityTime);
this._maybeSaveSession();
Expand Down
2 changes: 2 additions & 0 deletions packages/replay-internal/src/session/Session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ export function makeSession(session: Partial<Session> & { sampled: Sampled }): S
const segmentId = session.segmentId || 0;
const sampled = session.sampled;
const previousSessionId = session.previousSessionId;
const dirty = session.dirty || false;

return {
id,
Expand All @@ -21,5 +22,6 @@ export function makeSession(session: Partial<Session> & { sampled: Sampled }): S
segmentId,
sampled,
previousSessionId,
dirty,
};
}
7 changes: 7 additions & 0 deletions packages/replay-internal/src/types/replay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -383,6 +383,13 @@ export interface Session {
* Is the session sampled? `false` if not sampled, otherwise, `session` or `buffer`
*/
sampled: Sampled;

/**
* Session is dirty when its id has been linked to an event (e.g. error event).
* This is helpful when a session is mistakenly stuck in "buffer" mode (e.g. network issues preventing it from being converted to "session" mode).
* The dirty flag is used to prevent updating the session start time to the earliest event in the buffer so that it can be refreshed if it's been expired.
*/
dirty?: boolean;
}

export type EventBufferType = 'sync' | 'worker';
Expand Down
2 changes: 1 addition & 1 deletion packages/replay-internal/src/util/handleRecordingEmit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ export function getHandleRecordingEmit(replay: ReplayContainer): RecordingEmitCa

// When in buffer mode, make sure we adjust the session started date to the current earliest event of the buffer
// this should usually be the timestamp of the checkout event, but to be safe...
if (replay.recordingMode === 'buffer' && session && replay.eventBuffer) {
if (replay.recordingMode === 'buffer' && session && replay.eventBuffer && !session.dirty) {
const earliestEvent = replay.eventBuffer.getEarliestTimestamp();
if (earliestEvent) {
DEBUG_BUILD &&
Expand Down
Loading