|
7 | 7 | import crypto from 'node:crypto'; |
8 | 8 |
|
9 | 9 | import {logger} from '../../logger.js'; |
10 | | -import type {ChromeDevToolsMcpExtension, OsType} from '../types.js'; |
| 10 | +import type { |
| 11 | + ChromeDevToolsMcpExtension, |
| 12 | + LogRequest, |
| 13 | + LogResponse, |
| 14 | + OsType, |
| 15 | +} from '../types.js'; |
11 | 16 |
|
| 17 | +export interface ClearcutSenderConfig { |
| 18 | + appVersion: string; |
| 19 | + osType: OsType; |
| 20 | + clearcutEndpoint?: string; |
| 21 | + forceFlushIntervalMs?: number; |
| 22 | + includePidHeader?: boolean; |
| 23 | +} |
| 24 | + |
| 25 | +const MAX_BUFFER_SIZE = 1000; |
| 26 | +const DEFAULT_CLEARCUT_ENDPOINT = |
| 27 | + 'https://play.googleapis.com/log?format=json_proto'; |
| 28 | +const DEFAULT_FLUSH_INTERVAL_MS = 15 * 60 * 1000; |
| 29 | + |
| 30 | +const LOG_SOURCE = 2839; |
| 31 | +const CLIENT_TYPE = 47; |
| 32 | +const MIN_RATE_LIMIT_WAIT_MS = 30_000; |
| 33 | +const REQUEST_TIMEOUT_MS = 30_000; |
| 34 | +const SHUTDOWN_TIMEOUT_MS = 5_000; |
12 | 35 | const SESSION_ROTATION_INTERVAL_MS = 24 * 60 * 60 * 1000; |
13 | 36 |
|
| 37 | +interface BufferedEvent { |
| 38 | + event: ChromeDevToolsMcpExtension; |
| 39 | + timestamp: number; |
| 40 | +} |
| 41 | + |
14 | 42 | export class ClearcutSender { |
15 | 43 | #appVersion: string; |
16 | 44 | #osType: OsType; |
| 45 | + #clearcutEndpoint: string; |
| 46 | + #flushIntervalMs: number; |
| 47 | + #includePidHeader: boolean; |
17 | 48 | #sessionId: string; |
18 | 49 | #sessionCreated: number; |
| 50 | + #buffer: BufferedEvent[] = []; |
| 51 | + #flushTimer: ReturnType<typeof setTimeout> | null = null; |
| 52 | + #isFlushing = false; |
| 53 | + #timerStarted = false; |
19 | 54 |
|
20 | | - constructor(appVersion: string, osType: OsType) { |
21 | | - this.#appVersion = appVersion; |
22 | | - this.#osType = osType; |
| 55 | + constructor(config: ClearcutSenderConfig) { |
| 56 | + this.#appVersion = config.appVersion; |
| 57 | + this.#osType = config.osType; |
| 58 | + this.#clearcutEndpoint = |
| 59 | + config.clearcutEndpoint ?? DEFAULT_CLEARCUT_ENDPOINT; |
| 60 | + this.#flushIntervalMs = |
| 61 | + config.forceFlushIntervalMs ?? DEFAULT_FLUSH_INTERVAL_MS; |
| 62 | + this.#includePidHeader = config.includePidHeader ?? false; |
23 | 63 | this.#sessionId = crypto.randomUUID(); |
24 | 64 | this.#sessionCreated = Date.now(); |
25 | 65 | } |
26 | 66 |
|
27 | | - async send(event: ChromeDevToolsMcpExtension): Promise<void> { |
28 | | - this.#rotateSessionIfNeeded(); |
29 | | - const enrichedEvent = this.#enrichEvent(event); |
30 | | - this.transport(enrichedEvent); |
31 | | - } |
| 67 | + enqueueEvent(event: ChromeDevToolsMcpExtension): void { |
| 68 | + if (Date.now() - this.#sessionCreated > SESSION_ROTATION_INTERVAL_MS) { |
| 69 | + this.#sessionId = crypto.randomUUID(); |
| 70 | + this.#sessionCreated = Date.now(); |
| 71 | + } |
32 | 72 |
|
33 | | - transport(event: ChromeDevToolsMcpExtension): void { |
34 | | - logger('Telemetry event', JSON.stringify(event, null, 2)); |
| 73 | + this.#addToBuffer({ |
| 74 | + ...event, |
| 75 | + session_id: this.#sessionId, |
| 76 | + app_version: this.#appVersion, |
| 77 | + os_type: this.#osType, |
| 78 | + }); |
| 79 | + |
| 80 | + if (!this.#timerStarted) { |
| 81 | + this.#timerStarted = true; |
| 82 | + this.#scheduleFlush(this.#flushIntervalMs); |
| 83 | + } |
35 | 84 | } |
36 | 85 |
|
37 | 86 | async sendShutdownEvent(): Promise<void> { |
| 87 | + if (this.#flushTimer) { |
| 88 | + clearTimeout(this.#flushTimer); |
| 89 | + this.#flushTimer = null; |
| 90 | + } |
| 91 | + |
38 | 92 | const shutdownEvent: ChromeDevToolsMcpExtension = { |
39 | 93 | server_shutdown: {}, |
40 | 94 | }; |
41 | | - await this.send(shutdownEvent); |
| 95 | + this.enqueueEvent(shutdownEvent); |
| 96 | + |
| 97 | + try { |
| 98 | + await Promise.race([ |
| 99 | + this.#finalFlush(), |
| 100 | + new Promise(resolve => setTimeout(resolve, SHUTDOWN_TIMEOUT_MS)), |
| 101 | + ]); |
| 102 | + } catch (error) { |
| 103 | + logger('Final flush failed:', error); |
| 104 | + } |
42 | 105 | } |
43 | 106 |
|
44 | | - #rotateSessionIfNeeded(): void { |
45 | | - if (Date.now() - this.#sessionCreated > SESSION_ROTATION_INTERVAL_MS) { |
46 | | - this.#sessionId = crypto.randomUUID(); |
47 | | - this.#sessionCreated = Date.now(); |
| 107 | + async #flush(): Promise<void> { |
| 108 | + if (this.#isFlushing) { |
| 109 | + return; |
| 110 | + } |
| 111 | + |
| 112 | + if (this.#buffer.length === 0) { |
| 113 | + this.#scheduleFlush(this.#flushIntervalMs); |
| 114 | + return; |
| 115 | + } |
| 116 | + |
| 117 | + this.#isFlushing = true; |
| 118 | + let nextDelayMs = this.#flushIntervalMs; |
| 119 | + |
| 120 | + // Optimistically remove events from buffer before sending. |
| 121 | + // This prevents race conditions where a simultaneous #finalFlush would include these same events. |
| 122 | + const eventsToSend = [...this.#buffer]; |
| 123 | + this.#buffer = []; |
| 124 | + |
| 125 | + try { |
| 126 | + const result = await this.#sendBatch(eventsToSend); |
| 127 | + |
| 128 | + if (result.success) { |
| 129 | + if (result.nextRequestWaitMs !== undefined) { |
| 130 | + nextDelayMs = Math.max( |
| 131 | + result.nextRequestWaitMs, |
| 132 | + MIN_RATE_LIMIT_WAIT_MS, |
| 133 | + ); |
| 134 | + } |
| 135 | + } else if (result.isPermanentError) { |
| 136 | + logger( |
| 137 | + 'Permanent error, dropped batch of', |
| 138 | + eventsToSend.length, |
| 139 | + 'events', |
| 140 | + ); |
| 141 | + } else { |
| 142 | + // Transient error: Requeue events at the front of the buffer |
| 143 | + // to maintain order and retry them later. |
| 144 | + this.#buffer = [...eventsToSend, ...this.#buffer]; |
| 145 | + } |
| 146 | + } catch (error) { |
| 147 | + // Safety catch for unexpected errors, requeue events |
| 148 | + this.#buffer = [...eventsToSend, ...this.#buffer]; |
| 149 | + logger('Flush failed unexpectedly:', error); |
| 150 | + } finally { |
| 151 | + this.#isFlushing = false; |
| 152 | + this.#scheduleFlush(nextDelayMs); |
48 | 153 | } |
49 | 154 | } |
50 | 155 |
|
51 | | - #enrichEvent(event: ChromeDevToolsMcpExtension): ChromeDevToolsMcpExtension { |
52 | | - return { |
53 | | - ...event, |
54 | | - session_id: this.#sessionId, |
55 | | - app_version: this.#appVersion, |
56 | | - os_type: this.#osType, |
| 156 | + #addToBuffer(event: ChromeDevToolsMcpExtension): void { |
| 157 | + if (this.#buffer.length >= MAX_BUFFER_SIZE) { |
| 158 | + this.#buffer.shift(); |
| 159 | + logger('Telemetry buffer overflow: dropped oldest event'); |
| 160 | + } |
| 161 | + this.#buffer.push({ |
| 162 | + event, |
| 163 | + timestamp: Date.now(), |
| 164 | + }); |
| 165 | + } |
| 166 | + |
| 167 | + #scheduleFlush(delayMs: number): void { |
| 168 | + if (this.#flushTimer) { |
| 169 | + clearTimeout(this.#flushTimer); |
| 170 | + } |
| 171 | + this.#flushTimer = setTimeout(() => { |
| 172 | + this.#flush().catch(err => { |
| 173 | + logger('Flush error:', err); |
| 174 | + }); |
| 175 | + }, delayMs); |
| 176 | + } |
| 177 | + |
| 178 | + async #sendBatch(events: BufferedEvent[]): Promise<{ |
| 179 | + success: boolean; |
| 180 | + isPermanentError?: boolean; |
| 181 | + nextRequestWaitMs?: number; |
| 182 | + }> { |
| 183 | + const requestBody: LogRequest = { |
| 184 | + log_source: LOG_SOURCE, |
| 185 | + request_time_ms: Date.now().toString(), |
| 186 | + client_info: { |
| 187 | + client_type: CLIENT_TYPE, |
| 188 | + }, |
| 189 | + log_event: events.map(({event, timestamp}) => ({ |
| 190 | + event_time_ms: timestamp.toString(), |
| 191 | + source_extension_json: JSON.stringify(event), |
| 192 | + })), |
57 | 193 | }; |
| 194 | + |
| 195 | + const controller = new AbortController(); |
| 196 | + const timeoutId = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS); |
| 197 | + try { |
| 198 | + const response = await fetch(this.#clearcutEndpoint, { |
| 199 | + method: 'POST', |
| 200 | + headers: { |
| 201 | + 'Content-Type': 'application/json', |
| 202 | + // Used in E2E tests to confirm that the watchdog process is killed |
| 203 | + ...(this.#includePidHeader |
| 204 | + ? {'X-Watchdog-Pid': process.pid.toString()} |
| 205 | + : {}), |
| 206 | + }, |
| 207 | + body: JSON.stringify(requestBody), |
| 208 | + signal: controller.signal, |
| 209 | + }); |
| 210 | + |
| 211 | + clearTimeout(timeoutId); |
| 212 | + if (response.ok) { |
| 213 | + const data = (await response.json()) as LogResponse; |
| 214 | + return { |
| 215 | + success: true, |
| 216 | + nextRequestWaitMs: data.next_request_wait_millis, |
| 217 | + }; |
| 218 | + } |
| 219 | + |
| 220 | + const status = response.status; |
| 221 | + if (status >= 500 || status === 429) { |
| 222 | + return {success: false}; |
| 223 | + } |
| 224 | + |
| 225 | + logger('Telemetry permanent error:', status); |
| 226 | + return {success: false, isPermanentError: true}; |
| 227 | + } catch { |
| 228 | + clearTimeout(timeoutId); |
| 229 | + return {success: false}; |
| 230 | + } |
| 231 | + } |
| 232 | + |
| 233 | + async #finalFlush(): Promise<void> { |
| 234 | + if (this.#buffer.length === 0) { |
| 235 | + return; |
| 236 | + } |
| 237 | + const eventsToSend = [...this.#buffer]; |
| 238 | + await this.#sendBatch(eventsToSend); |
| 239 | + } |
| 240 | + |
| 241 | + stopForTesting(): void { |
| 242 | + if (this.#flushTimer) { |
| 243 | + clearTimeout(this.#flushTimer); |
| 244 | + this.#flushTimer = null; |
| 245 | + } |
| 246 | + this.#timerStarted = false; |
| 247 | + } |
| 248 | + |
| 249 | + get bufferSizeForTesting(): number { |
| 250 | + return this.#buffer.length; |
58 | 251 | } |
59 | 252 | } |
0 commit comments