Open History to see the last commit
1// T3 ingest retains events and deduplicates retries by UUID.
2import * as HostProcess from "@t3tools/shared/HostProcess";
3import { isCiEnvironment, isDoNotTrackSet } from "@t3tools/shared/otelEnvironment";
4import type { ClientOs } from "@t3tools/contracts";
5import * as Clock from "effect/Clock";
6import * as Config from "effect/Config";
7import * as ConfigProvider from "effect/ConfigProvider";
8import * as Context from "effect/Context";
9import * as SecureRandom from "effect/crypto/SecureRandom";
10import * as DateTime from "effect/DateTime";
11import * as Effect from "effect/Effect";
12import * as Exit from "effect/Exit";
13import * as Layer from "effect/Layer";
14import * as Option from "effect/Option";
15import * as Random from "effect/Random";
16import * as Ref from "effect/Ref";
17import * as Result from "effect/Result";
18import * as Semaphore from "effect/Semaphore";
19import * as HttpClient from "effect/http/HttpClient";
20import * as HttpClientRequest from "effect/http/HttpClientRequest";
21import * as HttpClientResponse from "effect/http/HttpClientResponse";
22
23import packageJson from "../../package.json" with { type: "json" };
24import * as ServerConfig from "../config.ts";
25import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
26import { getTelemetryIdentity, type TelemetryOwner } from "./Identify.ts";
27
28interface BufferedAnalyticsEvent {
29 readonly uuid: string;
30 readonly event: string;
31 readonly properties?: Readonly<Record<string, unknown>>;
32 readonly capturedAt: string;
33 /** Sent under its own id, without the install id, so it links to nothing else. */
34 readonly anonymous?: true;
35}
36
37interface DeliveryState {
38 readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>;
39 readonly batchAttempts: number;
40 readonly firstFailedAt: number;
41 readonly failures: number;
42 readonly retryAt: number;
43}
44
45// Retry delays shorter than this still wait for the next background check.
46const FLUSH_INTERVAL_MS = 10_000;
47// A hung send would hold the flush lock for the next background flush.
48const SEND_TIMEOUT = "10 seconds";
49// Quit and restart wait for this flush; events it cannot send in time are dropped.
50const SHUTDOWN_FLUSH_TIMEOUT = "1 second";
51// A failed batch is tried again until it has failed for this long. Ingest answers 503 when it
52// cannot store a batch, and a broken Cloudflare location can take about 5 minutes to fail over.
53// The waiting batch holds newer events back; `maxBufferedEvents` bounds them meanwhile.
54const MAX_BATCH_RETRY_MS = 30 * 60_000;
55const RETRY_BASE_DELAY_MS = 2_000;
56// Clients can report any number of owner ids; past this many per observer, new ones
57// are not sent. Each observer has its own cap, so client reports never crowd out the
58// server's own.
59const MAX_RECORDED_OWNERS = 1_000;
60const RETRY_MAX_DELAY_MS = 300_000;
61// These statuses reject the batch itself; unlike 408/429, retrying cannot help.
62const REJECTED_BATCH_STATUSES = new Set([400, 401, 413]);
63
64/** `random` is in [0, 1). */
65function retryDelayMs(failures: number, random: number): number {
66 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failures - 1));
67 return Math.round(ceiling / 2 + (ceiling / 2) * random);
68}
69
70const TelemetryEnvConfig = Config.all({
71 ingestKey: Config.String("T3CODE_TELEMETRY_KEY").pipe(
72 Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
73 ),
74 ingestHost: Config.String("T3CODE_TELEMETRY_HOST").pipe(
75 Config.withDefault("https://ingest.t3.codes"),
76 ),
77 enabled: Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe(Config.option),
78 flushBatchSize: Config.Number("T3CODE_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)),
79 maxBufferedEvents: Config.Number("T3CODE_TELEMETRY_MAX_BUFFERED_EVENTS").pipe(
80 Config.withDefault(1_000),
81 ),
82 wslDistroName: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
83});
84
85export class AnalyticsService extends Context.Service<
86 AnalyticsService,
87 {
88 /** Whether the event was queued to send; false when telemetry is off. */
89 readonly record: (
90 event: string,
91 properties?: Readonly<Record<string, unknown>>,
92 options?: { readonly anonymous?: boolean },
93 ) => Effect.Effect<boolean>;
94
95 readonly flush: Effect.Effect<void>;
96
97 /**
98 * Records `install.owner_observed` for each owner of this install that the
99 * server read itself or a connecting client reported. Each owner is sent once
100 * per server process, so reconnects and repeated reads are free.
101 */
102 readonly recordOwners: (
103 owners: ReadonlyArray<TelemetryOwner>,
104 observedBy: "server" | "client",
105 ) => Effect.Effect<void>;
106 }
107>()("t3/telemetry/AnalyticsService") {}
108
109function serverOsFromNodePlatform(platform: string): ClientOs {
110 switch (platform) {
111 case "darwin":
112 return "macOS";
113 case "win32":
114 return "Windows";
115 case "linux":
116 return "Linux";
117 case "android":
118 return "Android";
119 default:
120 return "other";
121 }
122}
123
124/** @public */
125/** @public */
126export const make = Effect.gen(function* () {
127 const telemetryConfig = yield* TelemetryEnvConfig;
128 const hostEnvironment = yield* HostProcess.Environment;
129 const awaitingShellConsent = hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1";
130 const enabledByDefault = !isCiEnvironment(hostEnvironment);
131 const enabledAtStartup = Option.getOrElse(telemetryConfig.enabled, () => enabledByDefault);
132 // A managed policy can switch analytics off over the environment, never on.
133 const policyAllows =
134 ManagedPolicy.deniedBy(yield* ManagedPolicy.ManagedPolicy, "telemetry") === undefined;
135 // A cached PATH does not establish consent from the current login shell.
136 const telemetryEnabled = Effect.suspend(() => {
137 if (!enabledAtStartup || !policyAllows || isDoNotTrackSet(hostEnvironment))
138 return Effect.succeed(false);
139 if (!awaitingShellConsent) return Effect.succeed(true);
140 if (hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1")
141 return Effect.succeed(false);
142 const preference = hostEnvironment.T3CODE_TELEMETRY_ENABLED;
143 return Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe(
144 Config.withDefault(enabledByDefault),
145 Effect.provideService(
146 ConfigProvider.ConfigProvider,
147 ConfigProvider.fromEnv({
148 env: preference === undefined ? {} : { T3CODE_TELEMETRY_ENABLED: preference },
149 }),
150 ),
151 Effect.orElseSucceed(() => false),
152 );
153 });
154 const httpClient = yield* HttpClient.HttpClient;
155 const serverConfig = yield* ServerConfig.ServerConfig;
156 const { distinctId, installId } = yield* getTelemetryIdentity;
157 const crypto = yield* SecureRandom.SecureRandom;
158 const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
159 const deliveryRef = yield* Ref.make<DeliveryState>({
160 failedBatch: [],
161 batchAttempts: 0,
162 firstFailedAt: 0,
163 failures: 0,
164 retryAt: 0,
165 });
166 const recordedOwnersRef = yield* Ref.make<
167 Readonly<Record<"server" | "client", ReadonlySet<string>>>
168 >({ server: new Set(), client: new Set() });
169 // The background flush and the shutdown flush must not send the same batch at once.
170 const flushLock = yield* Semaphore.make(1);
171 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
172 const hostPlatform = yield* HostProcess.Platform;
173 const hostArchitecture = yield* HostProcess.Architecture;
174
175 const enqueueBufferedEvent = (
176 uuid: string,
177 event: string,
178 properties: Readonly<Record<string, unknown>> | undefined,
179 anonymous: boolean,
180 ) =>
181 Effect.flatMap(DateTime.now, (now) =>
182 Ref.modify(bufferRef, (current) => {
183 const appended = [
184 ...current,
185 {
186 uuid,
187 event,
188 ...(properties ? { properties } : {}),
189 capturedAt: DateTime.formatIso(now),
190 ...(anonymous ? { anonymous: true as const } : {}),
191 } satisfies BufferedAnalyticsEvent,
192 ];
193
194 const next =
195 appended.length > telemetryConfig.maxBufferedEvents
196 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
197 : appended;
198
199 return [
200 {
201 size: next.length,
202 dropped: next.length !== appended.length,
203 } as const,
204 next,
205 ] as const;
206 }),
207 );
208
209 const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
210 events: ReadonlyArray<BufferedAnalyticsEvent>,
211 ) {
212 if (!(yield* telemetryEnabled) || !distinctId) return;
213
214 const payload = {
215 api_key: telemetryConfig.ingestKey,
216 batch: events.map((event) => ({
217 uuid: event.uuid,
218 event: event.event,
219 distinct_id: event.anonymous ? event.uuid : distinctId,
220 properties: event.anonymous
221 ? {
222 ...event.properties,
223 $process_person_profile: false,
224 t3CodeVersion: packageJson.version,
225 telemetryChannel: ServerConfig.telemetryChannel,
226 }
227 : {
228 ...event.properties,
229 ...(installId === null ? {} : { installId }),
230 $process_person_profile: false,
231 platform: hostPlatform,
232 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
233 arch: hostArchitecture,
234 t3CodeVersion: packageJson.version,
235 telemetryChannel: ServerConfig.telemetryChannel,
236 clientType,
237 serverOs: serverOsFromNodePlatform(hostPlatform),
238 serverArch: hostArchitecture,
239 serverWslDistro: Option.getOrUndefined(telemetryConfig.wslDistroName),
240 serverAppVersion: packageJson.version,
241 serverMode: serverConfig.mode,
242 },
243 timestamp: event.capturedAt,
244 })),
245 };
246
247 yield* HttpClientRequest.post(`${telemetryConfig.ingestHost}/batch/`).pipe(
248 HttpClientRequest.bodyJson(payload),
249 Effect.flatMap(httpClient.execute),
250 Effect.flatMap(HttpClientResponse.filterStatusOk),
251 Effect.timeout(SEND_TIMEOUT),
252 );
253 });
254
255 // An anonymous event goes out alone, or the ingest could link it to the other events by request.
256 const takeBatch = Ref.modify(bufferRef, (current) => {
257 const next = current.findIndex((event) => event.anonymous);
258 if (next === 0) return [current.slice(0, 1), current.slice(1)] as const;
259 const linked = current.slice(0, next === -1 ? current.length : next);
260 const batch = linked.slice(0, telemetryConfig.flushBatchSize);
261 return [batch, current.slice(batch.length)] as const;
262 });
263
264 // Back off even after dropping rejected batches so bad API keys cannot drain the queue in a tight loop.
265 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
266 while (true) {
267 const delivery = yield* Ref.get(deliveryRef);
268 const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch;
269 if (batch.length === 0) {
270 return;
271 }
272
273 const sent = yield* Effect.result(sendBatch(batch));
274 if (Result.isSuccess(sent)) {
275 yield* Ref.set(deliveryRef, {
276 failedBatch: [],
277 batchAttempts: 0,
278 firstFailedAt: 0,
279 failures: 0,
280 retryAt: 0,
281 });
282 continue;
283 }
284
285 const now = yield* Clock.currentTimeMillis;
286 const failures = delivery.failures + 1;
287 const batchAttempts = delivery.batchAttempts + 1;
288 const firstFailedAt = delivery.batchAttempts === 0 ? now : delivery.firstFailedAt;
289 const retryAt = now + retryDelayMs(failures, yield* Random.next);
290 const error = sent.failure;
291 const rejected =
292 error._tag === "HttpClientError" &&
293 error.reason._tag === "StatusCodeError" &&
294 REJECTED_BATCH_STATUSES.has(error.reason.response.status);
295 if (!rejected && now - firstFailedAt < MAX_BATCH_RETRY_MS) {
296 yield* Ref.set(deliveryRef, {
297 failedBatch: batch,
298 batchAttempts,
299 firstFailedAt,
300 failures,
301 retryAt,
302 });
303 yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
304 attempt: batchAttempts,
305 cause: error,
306 });
307 return;
308 }
309 yield* Ref.set(deliveryRef, {
310 failedBatch: [],
311 batchAttempts: 0,
312 firstFailedAt: 0,
313 failures,
314 retryAt,
315 });
316 yield* Effect.logWarning(
317 rejected
318 ? "Dropped telemetry batch the endpoint rejected"
319 : "Dropped telemetry batch after repeated send failures",
320 { events: batch.length, attempts: batchAttempts, cause: error },
321 );
322 return;
323 }
324 }).pipe(flushLock.withPermit);
325
326 const flushWhenDue = Effect.gen(function* () {
327 const { retryAt } = yield* Ref.get(deliveryRef);
328 if ((yield* Clock.currentTimeMillis) >= retryAt) {
329 yield* flush;
330 }
331 });
332
333 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
334 function* (event, properties, options) {
335 if (!(yield* telemetryEnabled) || !distinctId) return false;
336
337 // Catch Node UUID defects too; best-effort telemetry drops events without UUIDs.
338 const uuid = yield* Effect.exit(crypto.uuidV7());
339 if (Exit.isFailure(uuid)) return false;
340
341 const enqueueResult = yield* enqueueBufferedEvent(
342 uuid.value,
343 event,
344 properties,
345 options?.anonymous === true,
346 );
347 if (enqueueResult.dropped) {
348 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
349 size: enqueueResult.size,
350 event,
351 });
352 }
353 return true;
354 },
355 );
356
357 const recordOwners: AnalyticsService["Service"]["recordOwners"] = Effect.fn(
358 "AnalyticsService.recordOwners",
359 )((owners, observedBy) =>
360 Effect.forEach(
361 owners,
362 ({ source, ownerId }) =>
363 Ref.modify(recordedOwnersRef, (recorded) => {
364 const key = `${source}:${ownerId}`;
365 const seen = recorded[observedBy];
366 return seen.has(key) || seen.size >= MAX_RECORDED_OWNERS
367 ? [false, recorded]
368 : [true, { ...recorded, [observedBy]: new Set(seen).add(key) }];
369 }).pipe(
370 Effect.flatMap((isNew) =>
371 isNew
372 ? record("install.owner_observed", { ownerSource: source, ownerId, observedBy })
373 : Effect.void,
374 ),
375 ),
376 { discard: true },
377 ),
378 );
379
380 yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.andThen(flushWhenDue)), {
381 disableYield: true,
382 }).pipe(Effect.forkScoped);
383
384 yield* Effect.addFinalizer(() =>
385 flush.pipe(Effect.timeout(SHUTDOWN_FLUSH_TIMEOUT), Effect.ignore),
386 );
387
388 return AnalyticsService.of({ record, flush, recordOwners });
389});
390
391export const layer = Layer.effect(AnalyticsService, make);