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 ReplayCanvas integration #9826

Closed
wants to merge 4 commits into from
Closed
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
7 changes: 7 additions & 0 deletions .size-limit.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,13 @@ module.exports = [
gzip: true,
limit: '75 KB',
},
{
name: '@sentry/browser (incl. Tracing, Replay with Canvas) - Webpack (gzipped)',
path: 'packages/browser/build/npm/esm/index.js',
import: '{ init, Replay, BrowserTracing, ReplayCanvas }',
gzip: true,
limit: '90 KB',
},
{
name: '@sentry/browser (incl. Tracing, Replay) - Webpack with treeshaking flags (gzipped)',
path: 'packages/browser/build/npm/esm/index.js',
Expand Down
2 changes: 1 addition & 1 deletion dev-packages/browser-integration-tests/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@
"dependencies": {
"@babel/preset-typescript": "^7.16.7",
"@playwright/test": "^1.31.1",
"@sentry-internal/rrweb": "2.6.0",
"@sentry-internal/rrweb": "2.7.3",
"@sentry/browser": "7.92.0",
"@sentry/tracing": "7.92.0",
"axios": "1.6.0",
Expand Down
7 changes: 7 additions & 0 deletions dev-packages/browser-integration-tests/utils/replayHelpers.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
/* eslint-disable max-lines */
import type { fullSnapshotEvent, incrementalSnapshotEvent } from '@sentry-internal/rrweb';
import { EventType } from '@sentry-internal/rrweb';
import type { ReplayEventWithTime } from '@sentry/browser';
import type {
InternalEventContext,
RecordingEvent,
ReplayContainer,
ReplayPluginOptions,
Session,
} from '@sentry/replay/build/npm/types/types';
import type { Breadcrumb, Event, ReplayEvent, ReplayRecordingMode } from '@sentry/types';
Expand Down Expand Up @@ -171,6 +173,8 @@ export function getReplaySnapshot(page: Page): Promise<{
_isPaused: boolean;
_isEnabled: boolean;
_context: InternalEventContext;
_options: ReplayPluginOptions;
_hasCanvas: boolean;
session: Session | undefined;
recordingMode: ReplayRecordingMode;
}> {
Expand All @@ -182,6 +186,9 @@ export function getReplaySnapshot(page: Page): Promise<{
_isPaused: replay.isPaused(),
_isEnabled: replay.isEnabled(),
_context: replay.getContext(),
_options: replay.getOptions(),
// We cannot pass the function through as this is serialized
_hasCanvas: typeof replay.getOptions()._experiments.canvas?.manager === 'function',
session: replay.session,
recordingMode: replay.recordingMode,
};
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<button onclick="console.log('Test log')">Click me</button>
</body>
</html>
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 = new Sentry.Replay({
flushMinDelay: 200,
flushMaxDelay: 200,
minReplayDuration: 0,
});

Sentry.init({
dsn: 'https://[email protected]/1337',
sampleRate: 0,
replaysSessionSampleRate: 1.0,
replaysOnErrorSampleRate: 0.0,
debug: true,

integrations: [new Sentry.ReplayCanvas(), window.Replay],
});
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 { getReplaySnapshot, shouldSkipReplayTest } from '../../../../utils/replayHelpers';

sentryTest('sets up canvas when adding ReplayCanvas integration first', async ({ getLocalTestUrl, page }) => {
if (shouldSkipReplayTest()) {
sentryTest.skip();
}

await page.route('https://dsn.ingest.sentry.io/**/*', route => {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'test-id' }),
});
});

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

await page.goto(url);

const replay = await getReplaySnapshot(page);
const canvasOptions = replay._options._experiments?.canvas;
expect(canvasOptions.fps).toBe(4);
expect(canvasOptions.quality).toBe(0.6);
expect(replay._hasCanvas).toBe(true);
});
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 = new Sentry.Replay({
flushMinDelay: 200,
flushMaxDelay: 200,
minReplayDuration: 0,
});

Sentry.init({
dsn: 'https://[email protected]/1337',
sampleRate: 0,
replaysSessionSampleRate: 1.0,
replaysOnErrorSampleRate: 0.0,
debug: true,

integrations: [window.Replay, new Sentry.ReplayCanvas()],
});
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 { getReplaySnapshot, shouldSkipReplayTest } from '../../../../utils/replayHelpers';

sentryTest('sets up canvas when adding ReplayCanvas integration after Replay', async ({ getLocalTestUrl, page }) => {
if (shouldSkipReplayTest()) {
sentryTest.skip();
}

await page.route('https://dsn.ingest.sentry.io/**/*', route => {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'test-id' }),
});
});

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

await page.goto(url);

const replay = await getReplaySnapshot(page);
const canvasOptions = replay._options._experiments?.canvas;
expect(canvasOptions.fps).toBe(4);
expect(canvasOptions.quality).toBe(0.6);
expect(replay._hasCanvas).toBe(true);
});
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 = new Sentry.Replay({
flushMinDelay: 200,
flushMaxDelay: 200,
minReplayDuration: 0,
});

Sentry.init({
dsn: 'https://[email protected]/1337',
sampleRate: 0,
replaysSessionSampleRate: 1.0,
replaysOnErrorSampleRate: 0.0,
debug: true,

integrations: [window.Replay],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { expect } from '@playwright/test';

import { sentryTest } from '../../../../utils/fixtures';
import { getReplaySnapshot, shouldSkipReplayTest } from '../../../../utils/replayHelpers';

sentryTest('does not setup up canvas without ReplayCanvas integration', async ({ getLocalTestUrl, page }) => {
if (shouldSkipReplayTest()) {
sentryTest.skip();
}

await page.route('https://dsn.ingest.sentry.io/**/*', route => {
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({ id: 'test-id' }),
});
});

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

await page.goto(url);

const replay = await getReplaySnapshot(page);
const canvasOptions = replay._options._experiments?.canvas;
expect(canvasOptions).toBe(undefined);
expect(replay._hasCanvas).toBe(false);
});
2 changes: 1 addition & 1 deletion packages/browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const INTEGRATIONS = {

export { INTEGRATIONS as Integrations };

export { Replay } from '@sentry/replay';
export { Replay, ReplayCanvas } from '@sentry/replay';
export type {
ReplayEventType,
ReplayEventWithTime,
Expand Down
4 changes: 2 additions & 2 deletions packages/replay/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@
"devDependencies": {
"@babel/core": "^7.17.5",
"@sentry-internal/replay-worker": "7.92.0",
"@sentry-internal/rrweb": "2.6.0",
"@sentry-internal/rrweb-snapshot": "2.6.0",
"@sentry-internal/rrweb": "2.7.3",
"@sentry-internal/rrweb-snapshot": "2.7.3",
"fflate": "^0.8.1",
"jsdom-worker": "^0.2.1"
},
Expand Down
12 changes: 10 additions & 2 deletions packages/replay/rollup.bundle.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,20 @@ import { makeBaseBundleConfig, makeBundleConfigVariants } from '@sentry-internal

const baseBundleConfig = makeBaseBundleConfig({
bundleType: 'addon',
entrypoints: ['src/index.ts'],
entrypoints: ['src/integration.ts'],
jsVersion: 'es6',
licenseTitle: '@sentry/replay',
outputFileBase: () => 'bundles/replay',
});

const builds = makeBundleConfigVariants(baseBundleConfig);
const baseCanvasBundleConfig = makeBaseBundleConfig({
bundleType: 'addon',
entrypoints: ['src/canvas.ts'],
jsVersion: 'es6',
licenseTitle: '@sentry/replaycanvas',
outputFileBase: () => 'bundles/replaycanvas',
});

const builds = [...makeBundleConfigVariants(baseBundleConfig), ...makeBundleConfigVariants(baseCanvasBundleConfig)];

export default builds;
50 changes: 50 additions & 0 deletions packages/replay/src/canvas.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { getCanvasManager } from '@sentry-internal/rrweb';
Copy link
Member

Choose a reason for hiding this comment

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

Oh it's for this, right? Only if the integration is used, the canvas manager will be added to the bundle

Copy link
Member Author

Choose a reason for hiding this comment

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

Yes, exactly - basically wrapping this, but providing a nicer way to add this than to ask people to pass some method into the replay config etc.

Also, it helps with CDN bundles, where this otherwise also very hard/impossible to solve 😬

Copy link
Member

Choose a reason for hiding this comment

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

Will we have any issues creating this bundle because rrweb is devDep?

Copy link
Member Author

Choose a reason for hiding this comment

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

should not be the case, but something is not quite right yet here 😅 so still need to look into it a bit more!

import type { Integration } from '@sentry/types';
import type { ReplayConfiguration } from './types';

interface ReplayCanvasOptions {
quality: 'low' | 'medium' | 'high';
}

/** An integration to add canvas recording to replay. */
export class ReplayCanvas implements Integration {
/**
* @inheritDoc
*/
public static id: string = 'ReplayCanvas';

/**
* @inheritDoc
*/
public name: string;

private _canvasOptions: ReplayCanvasOptions;

public constructor(options?: Partial<ReplayCanvasOptions>) {
this.name = ReplayCanvas.id;
this._canvasOptions = {
quality: (options && options.quality) || 'medium',
};
}

/** @inheritdoc */
public setupOnce(): void {
// noop
}

/**
* Get the options that should be merged into replay options.
* This is what is actually called by the Replay integration to setup canvas.
*/
public getOptions(): Partial<ReplayConfiguration> {
return {
_experiments: {
canvas: {
...this._canvasOptions,
manager: getCanvasManager,
quality: this._canvasOptions.quality,
},
},
};
}
}
1 change: 1 addition & 0 deletions packages/replay/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export { Replay } from './integration';
export { ReplayCanvas } from './canvas';

export type {
ReplayEventType,
Expand Down
41 changes: 41 additions & 0 deletions packages/replay/src/integration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,7 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,

return this._replay.getSessionId();
}

/**
* Initializes replay.
*/
Expand All @@ -326,6 +327,12 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
return;
}

// We have to run this in _initialize, because this runs in setTimeout
// So when this runs all integrations have been added
// Before this, we cannot access integrations on the client,
// so we need to mutate the options here
this._maybeLoadFromReplayCanvasIntegration();

this._replay.initializeSampling();
}

Expand All @@ -339,6 +346,40 @@ Sentry.init({ replaysOnErrorSampleRate: ${errorSampleRate} })`,
recordingOptions: this._recordingOptions,
});
}

/** Get canvas options from ReplayCanvas integration, if it is also added. */
private _maybeLoadFromReplayCanvasIntegration(): void {
// If already defined, skip this...
if (this._initialOptions._experiments.canvas) {
return;
}

// To save bundle size, we skip checking for stuff here
// and instead just try-catch everything - as generally this should all be defined
/* eslint-disable @typescript-eslint/no-non-null-assertion */
try {
const client = getClient()!;
const canvasIntegration = client.getIntegrationById!('ReplayCanvas') as Integration & {
getOptions(): Partial<ReplayConfiguration>;
};
if (!canvasIntegration) {
return;
}
const additionalOptions = canvasIntegration.getOptions();

const mergedExperimentsOptions = {
...this._initialOptions._experiments,
...additionalOptions._experiments,
Copy link
Member

Choose a reason for hiding this comment

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

Are we excluding _experiments from being mangled? I guess we do but this broke CDN bundles before so we should double check 😅

Copy link
Member

Choose a reason for hiding this comment

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

Oh wait, this is just a property this should be safe, no?

Copy link
Member Author

Choose a reason for hiding this comment

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

yeah, this is excluded from being mangled! as we rely on this for some things 😅

};

this._initialOptions._experiments = mergedExperimentsOptions;

this._replay!.getOptions()._experiments = mergedExperimentsOptions;
} catch {
// ignore errors here
}
/* eslint-enable @typescript-eslint/no-non-null-assertion */
}
}

/** Parse Replay-related options from SDK options */
Expand Down
5 changes: 4 additions & 1 deletion packages/types/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,12 @@ export interface Client<O extends ClientOptions = ClientOptions> {
*/
getEventProcessors?(): EventProcessor[];

/** Returns the client's instance of the given integration class, it any. */
/** Returns the client's instance of the given integration class, if it exists. */
getIntegration<T extends Integration>(integration: IntegrationClass<T>): T | null;

/** Returns the client's instance of the given integration name, if it exists. */
getIntegrationById?(integrationId: string): Integration | undefined;

/**
* Add an integration to the client.
* This can be used to e.g. lazy load integrations.
Expand Down
Loading
Loading