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

AnalyticsService.ts

387 lines14.2 KB

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