Repository navigation
Expand file tree
/
Copy pathanalytics.ts
More file actions
181 lines (160 loc) · 5.33 KB
/
Copy pathanalytics.ts
File metadata and controls
181 lines (160 loc) · 5.33 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
import { randomUUID } from 'crypto';
import { app } from 'electron';
import fs from 'fs';
import os from 'os';
import {
buildAnalyticsPayload,
mergeAnalyticsDetails,
normalizeOsVersion,
parseOsRelease,
shouldDeliverAnalytics,
type AnalyticsEventName,
type AnalyticsHardware,
} from './analytics-payload';
import { isDev } from './config';
import { readAppState, writeAppState } from './app-state';
const ANALYTICS_ENDPOINT = 'https://ltx-desktop.lightricks.com/v2/ingest';
const REQUEST_TIMEOUT_MS = 5000;
const MAX_RETRIES = 3;
const RETRY_DELAYS_MS = [1000, 3000, 10000]
const MAX_INGEST_REQUESTS = 200
const INGEST_WINDOW_MS = 5 * 60 * 1000
const ingestTimestamps: number[] = []
function pruneIngestTimestamps(now: number): void {
const cutoff = now - INGEST_WINDOW_MS
while (ingestTimestamps.length > 0 && ingestTimestamps[0] <= cutoff) {
ingestTimestamps.shift()
}
}
function ingestAtCapacity(): boolean {
pruneIngestTimestamps(Date.now())
return ingestTimestamps.length >= MAX_INGEST_REQUESTS
}
function tryAcquireIngest(): boolean {
const now = Date.now()
pruneIngestTimestamps(now)
if (ingestTimestamps.length >= MAX_INGEST_REQUESTS) return false
ingestTimestamps.push(now)
return true
}
export function getAnalyticsState(): { analyticsEnabled: boolean; installationId: string } {
const state = readAppState()
return {
analyticsEnabled: state.analyticsEnabled !== false,
installationId: state.installationId ?? '',
}
}
export function setAnalyticsEnabled(enabled: boolean): void {
const state = readAppState()
state.analyticsEnabled = enabled
// Generate installationId on first enable; persist forever after
if (enabled && !state.installationId) {
state.installationId = randomUUID()
}
writeAppState(state)
}
function delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
function isRetryable(status: number): boolean {
return status === 429 || status >= 500
}
async function sendWithRetry(
url: string,
options: RequestInit,
): Promise<void> {
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) {
if (!tryAcquireIngest()) return
try {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
const response = await fetch(url, { ...options, signal: controller.signal })
clearTimeout(timeout)
if (response.ok || !isRetryable(response.status)) return
} catch (err) {
console.warn('[analytics] request attempt failed:', err)
}
if (attempt < MAX_RETRIES) {
await delay(RETRY_DELAYS_MS[attempt])
}
}
}
function readGpuName(info: unknown): string | undefined {
if (typeof info !== 'object' || info === null || !('gpuDevice' in info)) return undefined
const devices = (info as { gpuDevice?: unknown }).gpuDevice
if (!Array.isArray(devices)) return undefined
const named = devices.filter((device): device is { active?: boolean; deviceString?: string } => (
typeof device === 'object' && device !== null
))
const selected = named.find((device) => device.active) ?? named[0]
return typeof selected?.deviceString === 'string' && selected.deviceString
? selected.deviceString
: undefined
}
let hardwarePromise: Promise<AnalyticsHardware> | null = null
function currentHardware(): Promise<AnalyticsHardware> {
hardwarePromise ??= loadHardware()
return hardwarePromise
}
function readLinuxDistro(): string | undefined {
for (const file of ['/etc/os-release', '/usr/lib/os-release']) {
try {
return parseOsRelease(fs.readFileSync(file, 'utf8'))
} catch {
// Try the next location.
}
}
return undefined
}
async function loadHardware(): Promise<AnalyticsHardware> {
const hardware: AnalyticsHardware = {
ramGb: Math.round(os.totalmem() / 1024 ** 3),
// Electron returns the product version on macOS and Windows, and the kernel release on Linux.
osVersion: normalizeOsVersion(process.getSystemVersion()),
osDistro: process.platform === 'linux' ? readLinuxDistro() : undefined,
}
try {
hardware.gpuName = readGpuName(await app.getGPUInfo('basic'))
} catch {
// Hardware metadata is optional and must never prevent an event.
}
return hardware
}
export async function sendAnalyticsEvent(
eventName: AnalyticsEventName,
extraDetails?: Record<string, unknown> | null,
): Promise<void> {
try {
const state = readAppState()
if (!shouldDeliverAnalytics({
dev: isDev,
enabled: state.analyticsEnabled !== false,
})) return
if (ingestAtCapacity()) return
// Generate installationId on first send
if (!state.installationId) {
state.installationId = randomUUID()
writeAppState(state)
}
const now = Date.now()
const payload = buildAnalyticsPayload({
eventName,
eventId: randomUUID(),
timestamp: now,
appVersion: app.getVersion(),
installationId: state.installationId,
platform: process.platform,
extraDetails: mergeAnalyticsDetails(extraDetails, await currentHardware(), eventName),
})
// Fire-and-forget with retries — never throws
void sendWithRetry(ANALYTICS_ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
})
} catch (err) {
console.error('[analytics] failed to send event:', err)
}
}