-
-
Notifications
You must be signed in to change notification settings - Fork 283
/
Copy pathutils.ts
97 lines (77 loc) · 2.49 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
import type { Environment } from '@trezor/env-utils';
import { getWeakRandomId } from '@trezor/utils';
import type { App, Event as AnalyticsEvent } from './types';
export const getTrackingRandomId = () => getWeakRandomId(10);
export const getRandomId = () => getWeakRandomId(10);
export const encodeDataToQueryString = <T extends AnalyticsEvent>(
instanceId: string,
sessionId: string,
commitId: string,
version: string,
event: T,
) => {
const { type, timestamp } = event;
const params = new URLSearchParams({
c_v: version,
c_type: type || '',
c_commit: commitId,
c_instance_id: instanceId,
c_session_id: sessionId,
c_timestamp: timestamp || Date.now().toString(),
c_message_id: getRandomId(),
});
if (event.payload) {
Object.entries(event.payload).forEach(([key, value]) =>
params.append(key, value?.toString() ?? ''),
);
}
return params.toString();
};
export const getUrl = (app: App, isDev: boolean, environment?: Environment) => {
let base = `https://data.trezor.io/${app}/log`;
if (environment) {
base = `${base}/${environment}`;
}
if (isDev) {
return `${base}/develop.log`;
}
return `${base}/stable.log`;
};
const reportEventError = (
type: ReportEventProps['type'],
retry: ReportEventProps['retry'],
err: any,
) => {
let errorMessage = err?.error?.message || err?.message;
if (typeof errorMessage !== 'string') {
// this should never happen
errorMessage = 'Unknown error.';
}
// to circumvent sentry inbound filter
if (errorMessage.includes('Failed to fetch')) {
errorMessage = 'Failed to analytics fetch.';
}
const reportedMessage = `Analytics report failed. Reporting '${type}' ${
retry ? 'again' : 'was unsuccessful'
}. ${errorMessage}`;
console.error(reportedMessage);
};
interface ReportEventProps {
type: AnalyticsEvent['type'];
url: string;
options: RequestInit;
retry: boolean;
}
export const reportEvent = async ({ type, url, options, retry }: ReportEventProps) => {
try {
const response = await fetch(url, options);
if (!response.ok) {
console.error(`Analytics response not ok. Response status: ${response.status}.`);
}
} catch (err) {
reportEventError(type, retry, err);
if (retry) {
setTimeout(() => reportEvent({ type, url, options, retry: false }), 1000);
}
}
};