Open History to see the last commit
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;
34}
35
36interface DeliveryState {
37 readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>;
38 readonly batchAttempts: number;
39 readonly firstFailedAt: number;
40 readonly failures: number;
41 readonly retryAt: number;
42}
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);
67}
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 }
121}
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: {
217 ...event.properties,
218 ...(installId === null || event.anonymous ? {} : { installId }),
219 $process_person_profile: false,
220 platform: hostPlatform,
221 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
222 arch: hostArchitecture,
223 t3CodeVersion: packageJson.version,
224 telemetryChannel: ServerConfig.telemetryChannel,
225 clientType,
226 serverOs: serverOsFromNodePlatform(hostPlatform),
227 serverArch: hostArchitecture,
228 serverWslDistro: Option.getOrUndefined(telemetryConfig.wslDistroName),
229 serverAppVersion: packageJson.version,
230 serverMode: serverConfig.mode,
231 },
232 timestamp: event.capturedAt,
233 })),
234 };
235
236 yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
237 HttpClientRequest.bodyJson(payload),
238 Effect.flatMap(httpClient.execute),
239 Effect.flatMap(HttpClientResponse.filterStatusOk),
240 Effect.timeout(SEND_TIMEOUT),
241 );
242 });
243
244 const takeBatch = Ref.modify(bufferRef, (current) => {
245 const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
246 return [nextBatch, current.slice(nextBatch.length)] as const;
247 });
248
249 // Back off even after dropping rejected batches so bad API keys cannot drain the queue in a tight loop.
250 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
251 while (true) {
252 const delivery = yield* Ref.get(deliveryRef);
253 const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch;
254 if (batch.length === 0) {
255 return;
256 }
257
258 const sent = yield* Effect.result(sendBatch(batch));
259 if (Result.isSuccess(sent)) {
260 yield* Ref.set(deliveryRef, {
261 failedBatch: [],
262 batchAttempts: 0,
263 firstFailedAt: 0,
264 failures: 0,
265 retryAt: 0,
266 });
267 continue;
268 }
269
270 const now = yield* Clock.currentTimeMillis;
271 const failures = delivery.failures + 1;
272 const batchAttempts = delivery.batchAttempts + 1;
273 const firstFailedAt = delivery.batchAttempts === 0 ? now : delivery.firstFailedAt;
274 const retryAt = now + retryDelayMs(failures, yield* Random.next);
275 const error = sent.failure;
276 const rejected =
277 error._tag === "HttpClientError" &&
278 error.reason._tag === "StatusCodeError" &&
279 REJECTED_BATCH_STATUSES.has(error.reason.response.status);
280 if (!rejected && now - firstFailedAt < MAX_BATCH_RETRY_MS) {
281 yield* Ref.set(deliveryRef, {
282 failedBatch: batch,
283 batchAttempts,
284 firstFailedAt,
285 failures,
286 retryAt,
287 });
288 yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
289 attempt: batchAttempts,
290 cause: error,
291 });
292 return;
293 }
294 yield* Ref.set(deliveryRef, {
295 failedBatch: [],
296 batchAttempts: 0,
297 firstFailedAt: 0,
298 failures,
299 retryAt,
300 });
301 yield* Effect.logWarning(
302 rejected
303 ? "Dropped telemetry batch the endpoint rejected"
304 : "Dropped telemetry batch after repeated send failures",
305 { events: batch.length, attempts: batchAttempts, cause: error },
306 );
307 return;
308 }
309 }).pipe(flushLock.withPermit);
310
311 const flushWhenDue = Effect.gen(function* () {
312 const { retryAt } = yield* Ref.get(deliveryRef);
313 if ((yield* Clock.currentTimeMillis) >= retryAt) {
314 yield* flush;
315 }
316 });
317
318 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
319 function* (event, properties, options) {
320 if (!(yield* telemetryEnabled) || !distinctId) return false;
321
322 // Catch Node UUID defects too; best-effort telemetry drops events without UUIDs.
323 const uuid = yield* Effect.exit(crypto.uuidV7());
324 if (Exit.isFailure(uuid)) return false;
325
326 const enqueueResult = yield* enqueueBufferedEvent(
327 uuid.value,
328 event,
329 properties,
330 options?.anonymous === true,
331 );
332 if (enqueueResult.dropped) {
333 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
334 size: enqueueResult.size,
335 event,
336 });
337 }
338 return true;
339 },
340 );
341
342 const recordOwners: AnalyticsService["Service"]["recordOwners"] = Effect.fn(
343 "AnalyticsService.recordOwners",
344 )((owners, observedBy) =>
345 Effect.forEach(
346 owners,
347 ({ source, ownerId }) =>
348 Ref.modify(recordedOwnersRef, (recorded) => {
349 const key = `${source}:${ownerId}`;
350 const seen = recorded[observedBy];
351 return seen.has(key) || seen.size >= MAX_RECORDED_OWNERS
352 ? [false, recorded]
353 : [true, { ...recorded, [observedBy]: new Set(seen).add(key) }];
354 }).pipe(
355 Effect.flatMap((isNew) =>
356 isNew
357 ? record("install.owner_observed", { ownerSource: source, ownerId, observedBy })
358 : Effect.void,
359 ),
360 ),
361 { discard: true },
362 ),
363 );
364
365 yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.andThen(flushWhenDue)), {
366 disableYield: true,
367 }).pipe(Effect.forkScoped);
368
369 yield* Effect.addFinalizer(() =>
370 flush.pipe(Effect.timeout(SHUTDOWN_FLUSH_TIMEOUT), Effect.ignore),
371 );
372
373 return AnalyticsService.of({ record, flush, recordOwners });
374});
375
376export const layer = Layer.effect(AnalyticsService, make);