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 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
3 changes: 2 additions & 1 deletion packages/session-replay-browser/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@
"publish": "node ../../scripts/publish/upload-to-s3.js",
"test": "jest",
"typecheck": "tsc -p ./tsconfig.json",
"version": "yarn add @amplitude/analytics-types@\">=1 <3\" @amplitude/analytics-client-common@\">=1 <3\" @amplitude/analytics-core@\">=1 <3\""
"version": "yarn add @amplitude/analytics-types@\">=1 <3\" @amplitude/analytics-client-common@\">=1 <3\" @amplitude/analytics-core@\">=1 <3\"",
"version-file": "node -p \"'export const VERSION = \\'' + require('./package.json').version + '\\';'\" > src/version.ts"
},
"bugs": {
"url": "https://github.com/amplitude/Amplitude-TypeScript/issues"
Expand Down
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
1 change: 1 addition & 0 deletions packages/session-replay-browser/src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +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 = 0;

export const BLOCK_CLASS = 'amp-block';
export const MASK_TEXT_CLASS = 'amp-mask';
Expand Down
6 changes: 6 additions & 0 deletions packages/session-replay-browser/src/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { getGlobalScope } from '@amplitude/analytics-client-common';
import { UNMASK_TEXT_CLASS } from './constants';

export const maskInputFn = (text: string, element: HTMLElement) => {
Expand Down Expand Up @@ -25,3 +26,8 @@ export const isSessionInSample = function (sessionId: number, sampleRate: number
const mod = absHashMultiply % 100;
return mod / 100 < sampleRate;
};

export const getCurrentUrl = () => {
const globalScope = getGlobalScope();
return globalScope?.location ? globalScope.location.href : '';
};
29 changes: 21 additions & 8 deletions packages/session-replay-browser/src/session-replay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { pack, record } from 'rrweb';
import { SessionReplayConfig } from './config';
import {
BLOCK_CLASS,
DEFAULT_SAMPLE_RATE,
DEFAULT_SESSION_REPLAY_PROPERTY,
MASK_TEXT_CLASS,
MAX_EVENT_LIST_SIZE_IN_BYTES,
Expand All @@ -17,7 +18,7 @@ import {
STORAGE_PREFIX,
defaultSessionStore,
} from './constants';
import { isSessionInSample, maskInputFn } from './helpers';
import { isSessionInSample, maskInputFn, getCurrentUrl } from './helpers';
import {
MAX_RETRIES_EXCEEDED_MESSAGE,
MISSING_API_KEY_MESSAGE,
Expand All @@ -37,6 +38,7 @@ import {
SessionReplayContext,
SessionReplayOptions,
} from './typings/session-replay';
import { VERSION } from './version';

export class SessionReplay implements AmplitudeSessionReplay {
name = '@amplitude/session-replay-browser';
Expand Down Expand Up @@ -127,7 +129,7 @@ export class SessionReplay implements AmplitudeSessionReplay {
this.stopRecordingEvents = null;
} catch (error) {
const typedError = error as Error;
this.loggerProvider.error(`Error occurred while stopping recording: ${typedError.toString()}`);
this.loggerProvider.warn(`Error occurred while stopping recording: ${typedError.toString()}`);
}
const sessionIdToSend = sessionId || this.config?.sessionId;
if (this.events.length && sessionIdToSend) {
Expand Down Expand Up @@ -183,7 +185,7 @@ export class SessionReplay implements AmplitudeSessionReplay {

getShouldRecord() {
if (!this.config) {
this.loggerProvider.warn(`Session is not being recorded due to lack of config, please call sessionReplay.init.`);
this.loggerProvider.error(`Session is not being recorded due to lack of config, please call sessionReplay.init.`);
return false;
}
const globalScope = getGlobalScope();
Expand Down Expand Up @@ -269,7 +271,7 @@ export class SessionReplay implements AmplitudeSessionReplay {
recordCanvas: false,
errorHandler: (error) => {
const typedError = error as Error;
this.loggerProvider.error('Error while recording: ', typedError.toString());
this.loggerProvider.warn('Error while recording: ', typedError.toString());

return true;
},
Expand Down Expand Up @@ -357,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 @@ -383,6 +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.getSampleRate();

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

try {
const options: RequestInit = {
headers: {
'Content-Type': 'application/json',
Accept: '*/*',
Authorization: `Bearer ${apiKey}`,
'X-Client-Version': version,
jxiwang marked this conversation as resolved.
Show resolved Hide resolved
'X-Client-Url': url,
'X-Client-Sample-Rate': `${sampleRate}`,
},
body: JSON.stringify(payload),
method: 'POST',
Expand Down Expand Up @@ -457,7 +470,7 @@ export class SessionReplay implements AmplitudeSessionReplay {

return storedReplaySessionContexts;
} catch (e) {
this.loggerProvider.error(`${STORAGE_FAILURE}: ${e as string}`);
this.loggerProvider.warn(`${STORAGE_FAILURE}: ${e as string}`);
}
return undefined;
}
Expand Down Expand Up @@ -485,7 +498,7 @@ export class SessionReplay implements AmplitudeSessionReplay {
};
});
} catch (e) {
this.loggerProvider.error(`${STORAGE_FAILURE}: ${e as string}`);
this.loggerProvider.warn(`${STORAGE_FAILURE}: ${e as string}`);
}
}

Expand Down Expand Up @@ -520,14 +533,14 @@ export class SessionReplay implements AmplitudeSessionReplay {
return sessionMap;
});
} catch (e) {
this.loggerProvider.error(`${STORAGE_FAILURE}: ${e as string}`);
this.loggerProvider.warn(`${STORAGE_FAILURE}: ${e as string}`);
}
}

completeRequest({ context, err, success }: { context: SessionReplayContext; err?: string; success?: string }) {
context.sessionId && this.cleanUpSessionEventsStore(context.sessionId, context.sequenceId);
if (err) {
this.loggerProvider.error(err);
this.loggerProvider.warn(err);
} else if (success) {
this.loggerProvider.log(success);
}
Expand Down
1 change: 1 addition & 0 deletions packages/session-replay-browser/src/version.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const VERSION = '0.2.5';
Loading