1 import { getSilentApi } from '@proton/shared/lib/api/helpers/customConfig';
3 import { metrics } from '../api/metrics';
4 import type { TelemetryReport } from '../api/telemetry';
5 import { sendMultipleTelemetryData, sendTelemetryData } from '../api/telemetry';
6 import type { METRICS_LOG } from '../constants';
7 import { SECOND } from '../constants';
8 import type { Api } from '../interfaces';
9 import { wait } from './promise';
11 // Make the metrics false by default to avoid (rare) cases where we could have sendMetricReport or sendTelemetryReport
12 // before setting this metricsEnabled value with the user setting.
13 // In that scenario we would send something but the user might not want this.
14 let metricsEnabled = false;
17 * Delay an operation by a random number of seconds between 1 second and the specified
18 * number of seconds. If none is provided, the default is 180 seconds, i.e. 3 minutes
20 export const randomDelay = async (delayInSeconds: number = 180) => {
21 await wait(SECOND * Math.floor(delayInSeconds * Math.random() + 1));
25 * Send metrics report (/metrics endpoint)
27 export const sendMetricsReport = async (api: Api, Log: METRICS_LOG, Title?: string, Data?: any) => {
28 if (!metricsEnabled) {
31 // We delay sending the metrics report because this helper is used in some privacy-sensitive
32 // use-cases, e.g. encrypted search, in which we don't want the server to be able to use the
33 // metric report as a distinguisher to correlate user actions, e.g. performing an encrypted
34 // search and fetching an email shortly after
36 void api(metrics({ Log, Title, Data }));
39 interface SendTelemetryReportArgs extends TelemetryReport {
45 * Send a telemetry report (/data/v1/stats endpoint)
47 export const sendTelemetryReport = async ({
54 }: SendTelemetryReportArgs) => {
55 const possiblySilentApi = silence ? getSilentApi(api) : api;
57 if (!metricsEnabled) {
62 void (await possiblySilentApi(
64 MeasurementGroup: measurementGroup,
67 Dimensions: dimensions,
75 interface SendMultipleTelemetryReportsArgs {
77 reports: TelemetryReport[];
82 * Send multiple telemetry reports (/data/v1/stats/multiple endpoint)
84 export const sendMultipleTelemetryReports = async ({
88 }: SendMultipleTelemetryReportsArgs) => {
89 const possiblySilentApi = silence ? getSilentApi(api) : api;
91 if (!metricsEnabled) {
96 void (await possiblySilentApi(sendMultipleTelemetryData({ reports })));
102 export const setMetricsEnabled = (enabled: boolean) => {
103 metricsEnabled = enabled;