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(session replay): add metadata to headers #598

Merged
merged 4 commits into from
Oct 13, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
3 changes: 2 additions & 1 deletion packages/session-replay-browser/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { FetchTransport } from '@amplitude/analytics-client-common';
import { Config, Logger } from '@amplitude/analytics-core';
import { LogLevel } from '@amplitude/analytics-types';
import { SessionReplayConfig as ISessionReplayConfig, SessionReplayOptions } from './typings/session-replay';
import { DEFAULT_SAMPLE_RATE } from './constants';

export const getDefaultConfig = () => ({
flushMaxRetries: 2,
Expand Down Expand Up @@ -29,7 +30,7 @@ export class SessionReplayConfig extends Config implements ISessionReplayConfig
: defaultConfig.flushMaxRetries;

this.apiKey = apiKey;
this.sampleRate = options.sampleRate || 1;
this.sampleRate = options.sampleRate || DEFAULT_SAMPLE_RATE;

this.deviceId = options.deviceId;
this.sessionId = options.sessionId;
Expand Down
2 changes: 1 addition & 1 deletion packages/session-replay-browser/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export const DEFAULT_EVENT_PROPERTY_PREFIX = '[Amplitude]';
export const DEFAULT_SESSION_REPLAY_PROPERTY = `${DEFAULT_EVENT_PROPERTY_PREFIX} Session Recorded`;
export const DEFAULT_SESSION_START_EVENT = 'session_start';
export const DEFAULT_SESSION_END_EVENT = 'session_end';
export const DEFAULT_SAMPLE_RATE = 1;
export const DEFAULT_SAMPLE_RATE = 0;

export const BLOCK_CLASS = 'amp-block';
export const MASK_TEXT_CLASS = 'amp-mask';
Expand Down
10 changes: 7 additions & 3 deletions packages/session-replay-browser/src/session-replay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ import {
SessionReplayContext,
SessionReplayOptions,
} from './typings/session-replay';
import { VERSION } from './verstion';
import { VERSION } from './version';

export class SessionReplay implements AmplitudeSessionReplay {
name = '@amplitude/session-replay-browser';
Expand Down Expand Up @@ -359,6 +359,10 @@ export class SessionReplay implements AmplitudeSessionReplay {
await Promise.all(list.map((context) => this.send(context, useRetry)));
}

getSampleRate() {
return this.config?.sampleRate || DEFAULT_SAMPLE_RATE;
}

getServerUrl() {
if (this.config?.serverZone === ServerZone.EU) {
return SESSION_REPLAY_EU_SERVER_URL;
Expand All @@ -385,10 +389,9 @@ export class SessionReplay implements AmplitudeSessionReplay {
if (!deviceId) {
return this.completeRequest({ context, err: MISSING_DEVICE_ID_MESSAGE });
}

const url = getCurrentUrl();
const version = VERSION;
const sampleRate = this.config?.sampleRate || DEFAULT_SAMPLE_RATE;
const sampleRate = this.getSampleRate();

const urlParams = new URLSearchParams({
device_id: deviceId,
Expand All @@ -400,6 +403,7 @@ export class SessionReplay implements AmplitudeSessionReplay {
version: 1,
events: context.events,
};

try {
const options: RequestInit = {
headers: {
Expand Down
43 changes: 39 additions & 4 deletions packages/session-replay-browser/test/session-replay.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import * as AnalyticsClientCommon from '@amplitude/analytics-client-common';
import { LogLevel, Logger, ServerZone } from '@amplitude/analytics-types';
import * as IDBKeyVal from 'idb-keyval';
import * as RRWeb from 'rrweb';
import { DEFAULT_SESSION_REPLAY_PROPERTY, SESSION_REPLAY_SERVER_URL } from '../src/constants';
import { DEFAULT_SAMPLE_RATE, DEFAULT_SESSION_REPLAY_PROPERTY, SESSION_REPLAY_SERVER_URL } from '../src/constants';
import * as Helpers from '../src/helpers';
import { UNEXPECTED_ERROR_MESSAGE, getSuccessMessage } from '../src/messages';
import { SessionReplay } from '../src/session-replay';
import { IDBStore, RecordingStatus, SessionReplayConfig, SessionReplayOptions } from '../src/typings/session-replay';
import { VERSION } from '../src/verstion';
import { VERSION } from '../src/version';

jest.mock('idb-keyval');
type MockedIDBKeyVal = jest.Mocked<typeof import('idb-keyval')>;
Expand Down Expand Up @@ -38,6 +38,7 @@ describe('SessionReplayPlugin', () => {
const { get, update } = IDBKeyVal as MockedIDBKeyVal;
const { record } = RRWeb as MockedRRWeb;
let originalFetch: typeof global.fetch;
let location: typeof global.window.location;
const mockLoggerProvider: MockedLogger = {
error: jest.fn(),
log: jest.fn(),
Expand Down Expand Up @@ -80,6 +81,7 @@ describe('SessionReplayPlugin', () => {
jest.resetAllMocks();
jest.spyOn(global.Math, 'random').mockRestore();
global.fetch = originalFetch;
global.window.location = location;
jest.useRealTimers();
});
describe('init', () => {
Expand Down Expand Up @@ -255,7 +257,14 @@ describe('SessionReplayPlugin', () => {
const sessionReplay = new SessionReplay();
await sessionReplay.init(apiKey, mockOptions).promise;
sessionReplay.getShouldRecord = () => false;
const result = sessionReplay.getSessionRecordingProperties();
expect(result).toEqual({});
});

test('should return an default sample rate if not set', async () => {
const sessionReplay = new SessionReplay();
await sessionReplay.init(apiKey, mockOptions).promise;
sessionReplay.getShouldRecord = () => false;
const result = sessionReplay.getSessionRecordingProperties();
expect(result).toEqual({});
});
Expand Down Expand Up @@ -1007,6 +1016,15 @@ describe('SessionReplayPlugin', () => {
});
});

describe('getSampleRate', () => {
test('should return undefined if no config set', () => {
jxiwang marked this conversation as resolved.
Show resolved Hide resolved
const sessionReplay = new SessionReplay();
sessionReplay.config = undefined;
const sampleRate = sessionReplay.getSampleRate();
expect(sampleRate).toEqual(0);
});
});

describe('send', () => {
test('should not send anything if api key not set', async () => {
const sessionReplay = new SessionReplay();
Expand Down Expand Up @@ -1059,7 +1077,7 @@ describe('SessionReplayPlugin', () => {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: 'Bearer static_key',
'X-Client-Sample-Rate': '1',
'X-Client-Sample-Rate': `${DEFAULT_SAMPLE_RATE}`,
'X-Client-Url': window.location.href,
'X-Client-Version': VERSION,
},
Expand Down Expand Up @@ -1089,7 +1107,7 @@ describe('SessionReplayPlugin', () => {
Accept: '*/*',
'Content-Type': 'application/json',
Authorization: 'Bearer static_key',
'X-Client-Sample-Rate': '1',
'X-Client-Sample-Rate': `${DEFAULT_SAMPLE_RATE}`,
'X-Client-Url': window.location.href,
'X-Client-Version': VERSION,
},
Expand Down Expand Up @@ -1777,4 +1795,21 @@ describe('SessionReplayPlugin', () => {
});
});
});

describe('getCurrentUrl', () => {
let windowSpy: jest.SpyInstance;
beforeEach(() => {
windowSpy = jest.spyOn(globalThis, 'window', 'get');
});

afterEach(() => {
windowSpy.mockRestore();
});

test('runs without error', () => {
windowSpy.mockImplementation(() => undefined);
const url = Helpers.getCurrentUrl();
expect(url).toEqual('');
});
});
});
Loading