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