Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

AnalyticsService.ts

419 lines15.3 KB

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;
36​
37interface DeliveryState {
38 readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>;
39 readonly batchAttempts: number;
40 readonly firstFailedAt: number;
41 readonly failures: number;
42 readonly retryAt: number;
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);
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​
85// Users name or import their own distros, so only well-known families are reported.
86const WSL_DISTRO_FAMILIES = [
87 ["ubuntu", "Ubuntu"],
88 ["debian", "Debian"],
89 ["kali", "Kali"],
90 ["opensuse", "openSUSE"],
91 ["suse", "SUSE"],
92 ["sles", "SUSE"],
93 ["oraclelinux", "OracleLinux"],
94 ["almalinux", "AlmaLinux"],
95 ["rockylinux", "RockyLinux"],
96 ["fedora", "Fedora"],
97 ["archlinux", "Arch"],
98 ["alpine", "Alpine"],
99 ["nixos", "NixOS"],
100 ["pengwin", "Pengwin"],
101 ["docker-desktop", "docker-desktop"],
102] as const;
103​
104export const wslDistroFamily = (distroName: string): string | undefined => {
105 const name = distroName.trim().toLowerCase();
106 if (name === "") return undefined;
107 return WSL_DISTRO_FAMILIES.find(([prefix]) => name.startsWith(prefix))?.[1] ?? "other";
108};
109​
110export class AnalyticsService extends Context.Service<
111 AnalyticsService,
112 {
113 /** Whether the event was queued to send; false when telemetry is off. */
114 readonly record: (
115 event: string,
116 properties?: Readonly<Record<string, unknown>>,
117 options?: { readonly anonymous?: boolean },
118 ) => Effect.Effect<boolean>;
119​
120 readonly flush: Effect.Effect<void>;
121​
122 /**
123 * Records `install.owner_observed` for each owner of this install that the
124 * server read itself or a connecting client reported. Each owner is sent once
125 * per server process, so reconnects and repeated reads are free.
126 */
127 readonly recordOwners: (
128 owners: ReadonlyArray<TelemetryOwner>,
129 observedBy: "server" | "client",
130 ) => Effect.Effect<void>;
131 }
132>()("t3/telemetry/AnalyticsService") {}
133​
134function serverOsFromNodePlatform(platform: string): ClientOs {
135 switch (platform) {
136 case "darwin":
137 return "macOS";
138 case "win32":
139 return "Windows";
140 case "linux":
141 return "Linux";
142 case "android":
143 return "Android";
144 default:
145 return "other";
146 }
148​
149/** @public */
150/** @public */
151export const make = Effect.gen(function* () {
152 const telemetryConfig = yield* TelemetryEnvConfig;
153 const hostEnvironment = yield* HostProcess.Environment;
154 const awaitingShellConsent = hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1";
155 const enabledByDefault = !isCiEnvironment(hostEnvironment);
156 const enabledAtStartup = Option.getOrElse(telemetryConfig.enabled, () => enabledByDefault);
157 // A managed policy can switch analytics off over the environment, never on.
158 const policyAllows =
159 ManagedPolicy.deniedBy(yield* ManagedPolicy.ManagedPolicy, "telemetry") === undefined;
160 // A cached PATH does not establish consent from the current login shell.
161 const telemetryEnabled = Effect.suspend(() => {
162 if (!enabledAtStartup || !policyAllows || isDoNotTrackSet(hostEnvironment))
163 return Effect.succeed(false);
164 if (!awaitingShellConsent) return Effect.succeed(true);
165 if (hostEnvironment.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING === "1")
166 return Effect.succeed(false);
167 const preference = hostEnvironment.T3CODE_TELEMETRY_ENABLED;
168 return Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe(
169 Config.withDefault(enabledByDefault),
170 Effect.provideService(
171 ConfigProvider.ConfigProvider,
172 ConfigProvider.fromEnv({
173 env: preference === undefined ? {} : { T3CODE_TELEMETRY_ENABLED: preference },
174 }),
175 ),
176 Effect.orElseSucceed(() => false),
177 );
178 });
179 const httpClient = yield* HttpClient.HttpClient;
180 const serverConfig = yield* ServerConfig.ServerConfig;
181 const { distinctId, installId } = yield* getTelemetryIdentity;
182 const crypto = yield* SecureRandom.SecureRandom;
183 const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
184 const deliveryRef = yield* Ref.make<DeliveryState>({
185 failedBatch: [],
186 batchAttempts: 0,
187 firstFailedAt: 0,
188 failures: 0,
189 retryAt: 0,
190 });
191 const recordedOwnersRef = yield* Ref.make<
192 Readonly<Record<"server" | "client", ReadonlySet<string>>>
193 >({ server: new Set(), client: new Set() });
194 // The background flush and the shutdown flush must not send the same batch at once.
195 const flushLock = yield* Semaphore.make(1);
196 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
197 const hostPlatform = yield* HostProcess.Platform;
198 const hostArchitecture = yield* HostProcess.Architecture;
199 const wslDistro = Option.getOrUndefined(
200 Option.flatMapNullishOr(telemetryConfig.wslDistroName, wslDistroFamily),
201 );
202​
203 const enqueueBufferedEvent = (
204 uuid: string,
205 event: string,
206 properties: Readonly<Record<string, unknown>> | undefined,
207 anonymous: boolean,
208 ) =>
209 Effect.flatMap(DateTime.now, (now) =>
210 Ref.modify(bufferRef, (current) => {
211 const appended = [
212 ...current,
213 {
214 uuid,
215 event,
216 ...(properties ? { properties } : {}),
217 capturedAt: DateTime.formatIso(now),
218 ...(anonymous ? { anonymous: true as const } : {}),
219 } satisfies BufferedAnalyticsEvent,
220 ];
221​
222 const next =
223 appended.length > telemetryConfig.maxBufferedEvents
224 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
225 : appended;
226​
227 return [
228 {
229 size: next.length,
230 dropped: next.length !== appended.length,
231 } as const,
232 next,
233 ] as const;
234 }),
235 );
236​
237 const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
238 events: ReadonlyArray<BufferedAnalyticsEvent>,
239 ) {
240 if (!(yield* telemetryEnabled) || !distinctId) return;
241​
242 const payload = {
243 api_key: telemetryConfig.ingestKey,
244 batch: events.map((event) => ({
245 uuid: event.uuid,
246 event: event.event,
247 distinct_id: event.anonymous ? event.uuid : distinctId,
248 properties: event.anonymous
249 ? {
250 ...event.properties,
251 $process_person_profile: false,
252 t3CodeVersion: packageJson.version,
253 telemetryChannel: ServerConfig.telemetryChannel,
254 }
255 : {
256 ...event.properties,
257 ...(installId === null ? {} : { installId }),
258 $process_person_profile: false,
259 platform: hostPlatform,
260 wsl: wslDistro,
261 arch: hostArchitecture,
262 t3CodeVersion: packageJson.version,
263 telemetryChannel: ServerConfig.telemetryChannel,
264 clientType,
265 serverOs: serverOsFromNodePlatform(hostPlatform),
266 serverArch: hostArchitecture,
267 serverWslDistro: wslDistro,
268 serverAppVersion: packageJson.version,
269 serverMode: serverConfig.mode,
270 },
271 timestamp: event.capturedAt,
272 })),
273 };
274​
275 yield* HttpClientRequest.post(`${telemetryConfig.ingestHost}/batch/`).pipe(
276 HttpClientRequest.bodyJson(payload),
277 Effect.flatMap(httpClient.execute),
278 Effect.flatMap(HttpClientResponse.filterStatusOk),
279 Effect.timeout(SEND_TIMEOUT),
280 );
281 });
282​
283 // An anonymous event goes out alone, or the ingest could link it to the other events by request.
284 const takeBatch = Ref.modify(bufferRef, (current) => {
285 const next = current.findIndex((event) => event.anonymous);
286 if (next === 0) return [current.slice(0, 1), current.slice(1)] as const;
287 const linked = current.slice(0, next === -1 ? current.length : next);
288 const batch = linked.slice(0, telemetryConfig.flushBatchSize);
289 return [batch, current.slice(batch.length)] as const;
290 });
291​
292 // Back off even after dropping rejected batches so bad API keys cannot drain the queue in a tight loop.
293 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
294 while (true) {
295 const delivery = yield* Ref.get(deliveryRef);
296 const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch;
297 if (batch.length === 0) {
298 return;
299 }
300​
301 const sent = yield* Effect.result(sendBatch(batch));
302 if (Result.isSuccess(sent)) {
303 yield* Ref.set(deliveryRef, {
304 failedBatch: [],
305 batchAttempts: 0,
306 firstFailedAt: 0,
307 failures: 0,
308 retryAt: 0,
309 });
310 continue;
311 }
312​
313 const now = yield* Clock.currentTimeMillis;
314 const failures = delivery.failures + 1;
315 const batchAttempts = delivery.batchAttempts + 1;
316 const firstFailedAt = delivery.batchAttempts === 0 ? now : delivery.firstFailedAt;
317 const retryAt = now + retryDelayMs(failures, yield* Random.next);
318 const error = sent.failure;
319 const rejected =
320 error._tag === "HttpClientError" &&
321 error.reason._tag === "StatusCodeError" &&
322 REJECTED_BATCH_STATUSES.has(error.reason.response.status);
323 if (!rejected && now - firstFailedAt < MAX_BATCH_RETRY_MS) {
324 yield* Ref.set(deliveryRef, {
325 failedBatch: batch,
326 batchAttempts,
327 firstFailedAt,
328 failures,
329 retryAt,
330 });
331 yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
332 attempt: batchAttempts,
333 cause: error,
334 });
335 return;
336 }
337 yield* Ref.set(deliveryRef, {
338 failedBatch: [],
339 batchAttempts: 0,
340 firstFailedAt: 0,
341 failures,
342 retryAt,
343 });
344 yield* Effect.logWarning(
345 rejected
346 ? "Dropped telemetry batch the endpoint rejected"
347 : "Dropped telemetry batch after repeated send failures",
348 { events: batch.length, attempts: batchAttempts, cause: error },
349 );
350 return;
351 }
352 }).pipe(flushLock.withPermit);
353​
354 const flushWhenDue = Effect.gen(function* () {
355 const { retryAt } = yield* Ref.get(deliveryRef);
356 if ((yield* Clock.currentTimeMillis) >= retryAt) {
357 yield* flush;
358 }
359 });
360​
361 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
362 function* (event, properties, options) {
363 if (!(yield* telemetryEnabled) || !distinctId) return false;
364​
365 // Catch Node UUID defects too; best-effort telemetry drops events without UUIDs.
366 const uuid = yield* Effect.exit(crypto.uuidV7());
367 if (Exit.isFailure(uuid)) return false;
368​
369 const enqueueResult = yield* enqueueBufferedEvent(
370 uuid.value,
371 event,
372 properties,
373 options?.anonymous === true,
374 );
375 if (enqueueResult.dropped) {
376 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
377 size: enqueueResult.size,
378 event,
379 });
380 }
381 return true;
382 },
383 );
384​
385 const recordOwners: AnalyticsService["Service"]["recordOwners"] = Effect.fn(
386 "AnalyticsService.recordOwners",
387 )((owners, observedBy) =>
388 Effect.forEach(
389 owners,
390 ({ source, ownerId }) =>
391 Ref.modify(recordedOwnersRef, (recorded) => {
392 const key = `${source}:${ownerId}`;
393 const seen = recorded[observedBy];
394 return seen.has(key) || seen.size >= MAX_RECORDED_OWNERS
395 ? [false, recorded]
396 : [true, { ...recorded, [observedBy]: new Set(seen).add(key) }];
397 }).pipe(
398 Effect.flatMap((isNew) =>
399 isNew
400 ? record("install.owner_observed", { ownerSource: source, ownerId, observedBy })
401 : Effect.void,
402 ),
403 ),
404 { discard: true },
405 ),
406 );
407​
408 yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.andThen(flushWhenDue)), {
409 disableYield: true,
410 }).pipe(Effect.forkScoped);
411​
412 yield* Effect.addFinalizer(() =>
413 flush.pipe(Effect.timeout(SHUTDOWN_FLUSH_TIMEOUT), Effect.ignore),
414 );
415​
416 return AnalyticsService.of({ record, flush, recordOwners });
417});
418​
419export const layer = Layer.effect(AnalyticsService, make);