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 Context from "effect/Context";
7import * as Crypto from "effect/Crypto";
8import * as DateTime from "effect/DateTime";
9import * as Effect from "effect/Effect";
10import * as Exit from "effect/Exit";
11import * as Layer from "effect/Layer";
12import * as Option from "effect/Option";
13import * as Random from "effect/Random";
14import * as Ref from "effect/Ref";
15import * as Result from "effect/Result";
16import * as Semaphore from "effect/Semaphore";
17import * as HttpClient from "effect/http/HttpClient";
18import * as HttpClientRequest from "effect/http/HttpClientRequest";
19import * as HttpClientResponse from "effect/http/HttpClientResponse";
20
21import packageJson from "../../package.json" with { type: "json" };
22import * as ServerConfig from "../config.ts";
23import { getTelemetryIdentity, type TelemetryOwner } from "./Identify.ts";
24
25interface BufferedAnalyticsEvent {
26 readonly uuid: string;
27 readonly event: string;
28 readonly properties?: Readonly<Record<string, unknown>>;
29 readonly capturedAt: string;
30}
31
32interface DeliveryState {
33 readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>;
34 readonly batchAttempts: number;
35 readonly failures: number;
36 readonly retryAt: number;
37}
38
39// Retry delays shorter than this still wait for the next background check.
40const FLUSH_INTERVAL_MS = 10_000;
41// A hung send would hold the flush lock, and with it the shutdown flush.
42const SEND_TIMEOUT = "10 seconds";
43const MAX_BATCH_ATTEMPTS = 5;
44const RETRY_BASE_DELAY_MS = 2_000;
45// Clients can report any number of owner ids; past this many per observer, new ones
46// are not sent. Each observer has its own cap, so client reports never crowd out the
47// server's own.
48const MAX_RECORDED_OWNERS = 1_000;
49const RETRY_MAX_DELAY_MS = 300_000;
50// These statuses reject the batch itself; unlike 408/429, retrying cannot help.
51const REJECTED_BATCH_STATUSES = new Set([400, 401, 413]);
52
53/** `random` is in [0, 1). */
54function retryDelayMs(failures: number, random: number): number {
55 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failures - 1));
56 return Math.round(ceiling / 2 + (ceiling / 2) * random);
57}
58
59const TelemetryEnvConfig = Config.all({
60 posthogKey: Config.String("T3CODE_POSTHOG_KEY").pipe(
61 Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
62 ),
63 posthogHost: Config.String("T3CODE_POSTHOG_HOST").pipe(
64 Config.withDefault("https://ingest.t3.codes"),
65 ),
66 enabled: Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe(Config.withDefault(true)),
67 flushBatchSize: Config.Number("T3CODE_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)),
68 maxBufferedEvents: Config.Number("T3CODE_TELEMETRY_MAX_BUFFERED_EVENTS").pipe(
69 Config.withDefault(1_000),
70 ),
71 wslDistroName: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
72});
73
74export class AnalyticsService extends Context.Service<
75 AnalyticsService,
76 {
77 readonly record: (
78 event: string,
79 properties?: Readonly<Record<string, unknown>>,
80 ) => Effect.Effect<void>;
81
82 readonly flush: Effect.Effect<void>;
83
84 /**
85 * Records `install.owner_observed` for each owner of this install that the
86 * server read itself or a connecting client reported. Each owner is sent once
87 * per server process, so reconnects and repeated reads are free.
88 */
89 readonly recordOwners: (
90 owners: ReadonlyArray<TelemetryOwner>,
91 observedBy: "server" | "client",
92 ) => Effect.Effect<void>;
93 }
94>()("t3/telemetry/AnalyticsService") {
95 static readonly layerTest = Layer.succeed(
96 AnalyticsService,
97 AnalyticsService.of({
98 record: () => Effect.void,
99 flush: Effect.void,
100 recordOwners: () => Effect.void,
101 }),
102 );
103}
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 httpClient = yield* HttpClient.HttpClient;
125 const serverConfig = yield* ServerConfig.ServerConfig;
126 const { distinctId, installId } = yield* getTelemetryIdentity;
127 const crypto = yield* Crypto.Crypto;
128 const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
129 const deliveryRef = yield* Ref.make<DeliveryState>({
130 failedBatch: [],
131 batchAttempts: 0,
132 failures: 0,
133 retryAt: 0,
134 });
135 const recordedOwnersRef = yield* Ref.make<
136 Readonly<Record<"server" | "client", ReadonlySet<string>>>
137 >({ server: new Set(), client: new Set() });
138 // The background flush and the shutdown flush must not send the same batch at once.
139 const flushLock = yield* Semaphore.make(1);
140 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
141 const hostPlatform = yield* HostProcess.Platform;
142 const hostArchitecture = yield* HostProcess.Architecture;
143
144 const enqueueBufferedEvent = (
145 uuid: string,
146 event: string,
147 properties?: Readonly<Record<string, unknown>>,
148 ) =>
149 Effect.flatMap(DateTime.now, (now) =>
150 Ref.modify(bufferRef, (current) => {
151 const appended = [
152 ...current,
153 {
154 uuid,
155 event,
156 ...(properties ? { properties } : {}),
157 capturedAt: DateTime.formatIso(now),
158 } satisfies BufferedAnalyticsEvent,
159 ];
160
161 const next =
162 appended.length > telemetryConfig.maxBufferedEvents
163 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
164 : appended;
165
166 return [
167 {
168 size: next.length,
169 dropped: next.length !== appended.length,
170 } as const,
171 next,
172 ] as const;
173 }),
174 );
175
176 const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
177 events: ReadonlyArray<BufferedAnalyticsEvent>,
178 ) {
179 if (!telemetryConfig.enabled || !distinctId) return;
180
181 const payload = {
182 api_key: telemetryConfig.posthogKey,
183 batch: events.map((event) => ({
184 uuid: event.uuid,
185 event: event.event,
186 distinct_id: distinctId,
187 properties: {
188 ...event.properties,
189 ...(installId === null ? {} : { installId }),
190 $process_person_profile: false,
191 platform: hostPlatform,
192 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
193 arch: hostArchitecture,
194 t3CodeVersion: packageJson.version,
195 telemetryChannel: ServerConfig.telemetryChannel,
196 clientType,
197 serverOs: serverOsFromNodePlatform(hostPlatform),
198 serverArch: hostArchitecture,
199 serverWslDistro: Option.getOrUndefined(telemetryConfig.wslDistroName),
200 serverAppVersion: packageJson.version,
201 serverMode: serverConfig.mode,
202 },
203 timestamp: event.capturedAt,
204 })),
205 };
206
207 yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
208 HttpClientRequest.bodyJson(payload),
209 Effect.flatMap(httpClient.execute),
210 Effect.flatMap(HttpClientResponse.filterStatusOk),
211 Effect.timeout(SEND_TIMEOUT),
212 );
213 });
214
215 const takeBatch = Ref.modify(bufferRef, (current) => {
216 const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
217 return [nextBatch, current.slice(nextBatch.length)] as const;
218 });
219
220 // Back off even after dropping rejected batches so bad API keys cannot drain the queue in a tight loop.
221 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
222 while (true) {
223 const delivery = yield* Ref.get(deliveryRef);
224 const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch;
225 if (batch.length === 0) {
226 return;
227 }
228
229 const sent = yield* Effect.result(sendBatch(batch));
230 if (Result.isSuccess(sent)) {
231 yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures: 0, retryAt: 0 });
232 continue;
233 }
234
235 const failures = delivery.failures + 1;
236 const batchAttempts = delivery.batchAttempts + 1;
237 const retryAt = (yield* Clock.currentTimeMillis) + retryDelayMs(failures, yield* Random.next);
238 const error = sent.failure;
239 const rejected =
240 error._tag === "HttpClientError" &&
241 error.reason._tag === "StatusCodeError" &&
242 REJECTED_BATCH_STATUSES.has(error.reason.response.status);
243 if (!rejected && batchAttempts < MAX_BATCH_ATTEMPTS) {
244 yield* Ref.set(deliveryRef, { failedBatch: batch, batchAttempts, failures, retryAt });
245 yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
246 attempt: batchAttempts,
247 cause: error,
248 });
249 return;
250 }
251 yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures, retryAt });
252 yield* Effect.logWarning(
253 rejected
254 ? "Dropped telemetry batch the endpoint rejected"
255 : "Dropped telemetry batch after repeated send failures",
256 { events: batch.length, attempts: batchAttempts, cause: error },
257 );
258 return;
259 }
260 }).pipe(flushLock.withPermit);
261
262 const flushWhenDue = Effect.gen(function* () {
263 const { retryAt } = yield* Ref.get(deliveryRef);
264 if ((yield* Clock.currentTimeMillis) >= retryAt) {
265 yield* flush;
266 }
267 });
268
269 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
270 function* (event, properties) {
271 if (!telemetryConfig.enabled || !distinctId) return;
272
273 // Catch Node UUID defects too; best-effort telemetry drops events without UUIDs.
274 const uuid = yield* Effect.exit(crypto.randomUUIDv7());
275 if (Exit.isFailure(uuid)) return;
276
277 const enqueueResult = yield* enqueueBufferedEvent(uuid.value, event, properties);
278 if (enqueueResult.dropped) {
279 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
280 size: enqueueResult.size,
281 event,
282 });
283 }
284 },
285 );
286
287 const recordOwners: AnalyticsService["Service"]["recordOwners"] = Effect.fn(
288 "AnalyticsService.recordOwners",
289 )((owners, observedBy) =>
290 Effect.forEach(
291 owners,
292 ({ source, ownerId }) =>
293 Ref.modify(recordedOwnersRef, (recorded) => {
294 const key = `${source}:${ownerId}`;
295 const seen = recorded[observedBy];
296 return seen.has(key) || seen.size >= MAX_RECORDED_OWNERS
297 ? [false, recorded]
298 : [true, { ...recorded, [observedBy]: new Set(seen).add(key) }];
299 }).pipe(
300 Effect.flatMap((isNew) =>
301 isNew
302 ? record("install.owner_observed", { ownerSource: source, ownerId, observedBy })
303 : Effect.void,
304 ),
305 ),
306 { discard: true },
307 ),
308 );
309
310 yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.andThen(flushWhenDue)), {
311 disableYield: true,
312 }).pipe(Effect.forkScoped);
313
314 yield* Effect.addFinalizer(() => flush);
315
316 return AnalyticsService.of({ record, flush, recordOwners });
317});
318
319export const layer = Layer.effect(AnalyticsService, make);