1 import { useEffect, useMemo } from 'react';
3 import { useApi } from '@proton/components';
4 import { CryptoProxy } from '@proton/crypto';
5 import createApi from '@proton/shared/lib/api/createApi';
6 import localStorageWithExpiry from '@proton/shared/lib/api/helpers/localStorageWithExpiry';
7 import { TelemetryDriveWebFeature, TelemetryMeasurementGroups } from '@proton/shared/lib/api/telemetry';
8 import { sendTelemetryReport } from '@proton/shared/lib/helpers/metrics';
9 import { randomHexString4 } from '@proton/shared/lib/helpers/uid';
10 import type { Api } from '@proton/shared/lib/interfaces';
11 import noop from '@proton/utils/noop';
13 import * as config from '../config';
14 import { LAST_ACTIVE_PING } from '../store/_user/useActivePing';
15 import { sendErrorReport } from './errorHandling';
16 import { EnrichedError } from './errorHandling/EnrichedError';
17 import { getLastActivePersistedUserSession } from './lastActivePersistedUserSession';
19 export enum ExperimentGroup {
21 treatment = 'treatment',
24 export enum Features {
25 mountToFirstItemRendered = 'mountToFirstItemRendered',
29 * At the present time, these metrics will only work when user is authenticated
32 AddToBookmark = 'addToBookmark',
33 ViewSignUpFlowModal = 'viewSignUpFlowModal',
34 DismissSignUpFlowModal = 'dismissSignUpFlowModal',
35 SubmitSignUpFlowModal = 'submitSignUpFlowModal',
36 SignUpFlowModal = 'signUpFlowModal',
37 SignInFlowModal = 'signInFlowModal',
38 OpenPublicLinkFromSharedWithMe = 'openPublicLinkFromSharedWithMe',
39 PublicScanAndDownload = 'publicScanAndDownload',
40 PublicDownload = 'publicDownload',
41 PublicLinkVisit = 'publicLinkVisit',
42 DeleteBookmarkFromSharedWithMe = 'DeleteBookmarkFromSharedWithMe',
43 SignUpFlowAndRedirectCompleted = 'signUpFlowAndRedirectCompleted',
44 RedirectToCorrectContextShare = 'redirectToCorrectContextShare',
45 RedirectToCorrectAcceptInvitation = 'RedirectToCorrectAcceptInvitation',
46 AddToBookmarkTriggeredModal = 'addToBookmarkTriggeredModal',
48 OnboardingV2Shown = 'onboardingV2Shown',
49 OnboardingV2InstallMacApp = 'onboardingV2InstallMacApp',
50 OnboardingV2InstallWindowsApp = 'onboardingV2InstallWindowsApp',
51 OnboardingV2InstallSkip = 'onboardingV2InstallSkip',
52 OnboardingV2B2BInvite = 'onboardingV2B2BInvite',
53 OnboardingV2B2BInviteSkip = 'onboardingV2B2BInviteSkip',
54 OnboardingV2UploadFile = 'onboardingV2UploadFile',
55 OnboardingV2UploadFolder = 'onboardingV2UploadFolder',
56 OnboardingV2UploadSkip = 'onboardingV2UploadSkip',
58 // Download info on what system will be used for file with size above MEMORY_DOWNLOAD_LIMIT
59 DownloadUsingSW = 'downloadUsingSW',
60 DownloadFallback = 'downloadFallback',
63 type PerformanceTelemetryAdditionalValues = {
67 const sendTelemetryFeaturePerformance = (
69 featureName: Features,
71 treatment: ExperimentGroup,
72 additionalValues: PerformanceTelemetryAdditionalValues = {}
74 // TODO: https://jira.protontech.ch/browse/DD-7
75 // This is ugly and hacky, but it's a cheap way for the metric (without calling /users and without hooks)
76 // Proper back-end solution will be done as part of https://jira.protontech.ch/browse/DD-7
77 const loggedInRecently = localStorageWithExpiry.getData(LAST_ACTIVE_PING) ? 'true' : 'false';
79 void sendTelemetryReport({
81 measurementGroup: TelemetryMeasurementGroups.driveWebFeaturePerformance,
82 event: TelemetryDriveWebFeature.performance,
84 milliseconds: timeInMs,
88 isLoggedIn: window.location.pathname.startsWith('/urls') ? loggedInRecently : 'true',
89 experimentGroup: treatment,
95 const measureAndReport = (
98 group: ExperimentGroup,
102 additionalValues?: PerformanceTelemetryAdditionalValues
105 const measure = performance.measure(measureName, startMark, endMark);
106 // it can be undefined on browsers below Safari below 14.1 and Firefox 103
108 sendTelemetryFeaturePerformance(api, feature, measure.duration, group, additionalValues);
112 new EnrichedError('Telemetry Performance Error', {
122 * Executes a feature group with either control or treatment functions.
124 * @param {Features} feature The type of feature to execute (e.g. 'A', 'B', etc.) defined in the `Features` enum
125 * @param {boolean} applyTreatment Whether to execute the treatment or control function
126 * @param {(()) => Promise<T>} controlFunction A function returning a Promise that should be fulfilled when `applyTreatment` is false
127 * @param {(()) => Promise<T>} treatmentFunction A function returning a Promise that should be fulfilled when `applyTreatment` is true
128 * @returns {Promise<T>} The Promise of the executed function, returns T when fulfilled, both control and treatment should have same return type
130 export const measureExperimentalPerformance = <T>(
133 applyTreatment: boolean,
134 controlFunction: () => Promise<T>,
135 treatmentFunction: () => Promise<T>
137 // Something somewhat unique, if we have collision it's not end of the world we drop the metric
138 const distinguisher = `${performance.now()}-${randomHexString4()}`;
139 const startMark = `start-${feature}-${distinguisher}`;
140 const endMark = `end-${feature}-${distinguisher}`;
141 const measureName = `measure-${feature}-${distinguisher}`;
143 performance.mark(startMark);
144 const result = applyTreatment ? treatmentFunction() : controlFunction();
148 performance.mark(endMark);
153 applyTreatment ? ExperimentGroup.treatment : ExperimentGroup.control,
159 performance.clearMarks(endMark);
160 performance.clearMeasures(measureName);
161 performance.clearMarks(startMark);
168 export const measureFeaturePerformance = (api: Api, feature: Features, experimentGroup = ExperimentGroup.control) => {
169 const startMark = `start-${feature}-${randomHexString4()}`;
170 const endMark = `end-${feature}-${randomHexString4()}`;
171 const measureName = `measure-${feature}-${randomHexString4()}`;
176 const clear = () => {
177 performance.clearMarks(startMark);
178 performance.clearMarks(endMark);
179 performance.clearMeasures(measureName);
188 performance.mark(startMark);
191 end: (additionalValues?: PerformanceTelemetryAdditionalValues) => {
192 if (!ended && started) {
194 performance.mark(endMark);
195 measureAndReport(api, feature, experimentGroup, measureName, startMark, endMark, additionalValues);
203 export const useMeasureFeaturePerformanceOnMount = (features: Features) => {
204 const api = useApi();
206 // It will be a new measure object each time the api changes or the features changes.
207 // If it changes in between the previous measure has started and not ended yet the values will be cleared and ignored.
208 const measure = useMemo(() => measureFeaturePerformance(api, features), [api, features]);
220 const apiInstance = createApi({ config, sendLocaleHeaders: true });
222 export const countActionWithTelemetry = (action: Actions, count: number = 1) => {
223 const persistedSession = getLastActivePersistedUserSession();
225 if (persistedSession?.UID) {
226 // API calls will now be Authenticated with x-pm-uid header
227 apiInstance.UID = persistedSession?.UID;
230 // TODO: https://jira.protontech.ch/browse/DD-7
231 // This is ugly and hacky, but it's a cheap way for the metric (without calling /users and without hooks)
232 // Proper back-end solution will be done as part of https://jira.protontech.ch/browse/DD-7
233 const loggedInRecently = localStorageWithExpiry.getData(LAST_ACTIVE_PING) ? 'true' : 'false';
235 return sendTelemetryReport({
237 measurementGroup: TelemetryMeasurementGroups.driveWebActions,
238 event: TelemetryDriveWebFeature.actions,
243 isLoggedIn: window.location.pathname.startsWith('/urls') ? loggedInRecently : 'true',
249 const TEN_MINUTES = 10 * 60 * 1000;
251 export async function getTimeBasedHash(interval: number = TEN_MINUTES) {
252 const timeBase = Math.floor(Date.now() / interval) * interval;
254 const encoder = new TextEncoder();
255 const data = encoder.encode(timeBase.toString());
256 const hashBuffer = await CryptoProxy.computeHash({ algorithm: 'SHA256', data });
257 const hashArray = Array.from(new Uint8Array(hashBuffer));
258 const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
264 * Tracks user actions within a specified time window, typically used for flows involving redirections.
266 * This function is useful when you want to log an action only if the user starts at point A
267 * and finishes at point B within a given time window. It's particularly helpful in scenarios
268 * where there are redirections in the middle of a flow and passing query parameters through
269 * all redirections is not feasible.
272 * // Sign-Up Modal flow:
273 * // 1. Sign-Up Modal appears (start A)
274 * // 2. User signs up, pays, redirects
275 * // 3. User goes back to shared-with-me page (end B)
276 * // If this happens within the time window, the flow is logged as completed.
278 * @param {Actions} action - The action to be tracked.
279 * @param {number} [duration=TEN_MINUTES] - The time window for tracking the action, default is 10 minutes.
281 * @returns {Object} An object with start and end methods to initiate and complete the tracking.
283 export const traceTelemetry = (action: Actions, duration: number = TEN_MINUTES) => {
286 localStorageWithExpiry.storeData(`telemetry-trace-${action}`, await getTimeBasedHash(duration), duration);
289 const data = localStorageWithExpiry.getData(`telemetry-trace-${action}`);
290 if (data && data === (await getTimeBasedHash(duration))) {
291 countActionWithTelemetry(action);
293 localStorageWithExpiry.deleteData(`telemetry-trace-${action}`);