Open History to see the last commit
1/**
2 * Anonymous PostHog telemetry service.
3 *
4 * Persists an installation-scoped anonymous identifier, buffers events in
5 * memory, and flushes batches over Effect's HTTP client. A failed batch is
6 * retried with backoff and dropped after a few tries. Each event carries a
7 * uuid, so PostHog can tell a retried copy from a new event.
8 *
9 * @module AnalyticsService
10 */
11import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess";
12import type { ClientOs } from "@t3tools/contracts";
13import * as Clock from "effect/Clock";
14import * as Config from "effect/Config";
15import * as Context from "effect/Context";
16import * as Crypto from "effect/Crypto";
17import * as DateTime from "effect/DateTime";
18import * as Effect from "effect/Effect";
19import * as Exit from "effect/Exit";
20import * as Layer from "effect/Layer";
21import * as Option from "effect/Option";
22import * as Random from "effect/Random";
23import * as Ref from "effect/Ref";
24import * as Result from "effect/Result";
25import * as Semaphore from "effect/Semaphore";
26import * as HttpClient from "effect/http/HttpClient";
27import * as HttpClientRequest from "effect/http/HttpClientRequest";
28import * as HttpClientResponse from "effect/http/HttpClientResponse";
29
30import packageJson from "../../package.json" with { type: "json" };
31import * as ServerConfig from "../config.ts";
32import { getTelemetryIdentifier } from "./Identify.ts";
33
34interface BufferedAnalyticsEvent {
35 readonly uuid: string;
36 readonly event: string;
37 readonly properties?: Readonly<Record<string, unknown>>;
38 readonly capturedAt: string;
39}
40
41interface DeliveryState {
42 /** Batch that failed last. It is sent again before newer events. */
43 readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>;
44 /** Failed sends of `failedBatch`. */
45 readonly batchAttempts: number;
46 /** Failed sends since the last success. Sets the backoff delay. */
47 readonly failures: number;
48 /** The background flush does not send before this time (epoch ms). */
49 readonly retryAt: number;
50}
51
52const FLUSH_INTERVAL_MS = 1_000;
53// A hung send would hold the flush lock, and with it the shutdown flush.
54const SEND_TIMEOUT = "10 seconds";
55const MAX_BATCH_ATTEMPTS = 5;
56const RETRY_BASE_DELAY_MS = 2_000;
57const RETRY_MAX_DELAY_MS = 300_000;
58
59/**
60 * Delay before the next send after `failures` consecutive failed sends. The
61 * ceiling doubles from 2s up to 5 minutes, and the delay is a random point in
62 * its upper half. `random` is in [0, 1).
63 */
64export function 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://us.i.posthog.com"),
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 /** Record an anonymous event for best-effort buffered delivery. */
88 readonly record: (
89 event: string,
90 properties?: Readonly<Record<string, unknown>>,
91 ) => Effect.Effect<void>;
92
93 /** Flush all currently queued telemetry events. */
94 readonly flush: Effect.Effect<void>;
95 }
96>()("t3/telemetry/AnalyticsService") {
97 /** No-op layer for callers that intentionally disable telemetry. */
98 static readonly layerTest = Layer.succeed(
99 AnalyticsService,
100 AnalyticsService.of({
101 record: () => Effect.void,
102 flush: Effect.void,
103 }),
104 );
105}
106
107function serverOsFromNodePlatform(platform: string): ClientOs {
108 switch (platform) {
109 case "darwin":
110 return "macOS";
111 case "win32":
112 return "Windows";
113 case "linux":
114 return "Linux";
115 case "android":
116 return "Android";
117 default:
118 return "other";
119 }
120}
121
122/** @public Service construction is part of the canonical Effect module API. */
123export const make = Effect.gen(function* () {
124 const telemetryConfig = yield* TelemetryEnvConfig;
125 const httpClient = yield* HttpClient.HttpClient;
126 const serverConfig = yield* ServerConfig.ServerConfig;
127 const identifier = yield* getTelemetryIdentifier;
128 const crypto = yield* Crypto.Crypto;
129 const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
130 const deliveryRef = yield* Ref.make<DeliveryState>({
131 failedBatch: [],
132 batchAttempts: 0,
133 failures: 0,
134 retryAt: 0,
135 });
136 // The background flush and the shutdown flush must not send the same batch at once.
137 const flushLock = yield* Semaphore.make(1);
138 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
139 const hostPlatform = yield* HostProcessPlatform;
140 const hostArchitecture = yield* HostProcessArchitecture;
141
142 const enqueueBufferedEvent = (
143 uuid: string,
144 event: string,
145 properties?: Readonly<Record<string, unknown>>,
146 ) =>
147 Effect.flatMap(DateTime.now, (now) =>
148 Ref.modify(bufferRef, (current) => {
149 const appended = [
150 ...current,
151 {
152 uuid,
153 event,
154 ...(properties ? { properties } : {}),
155 capturedAt: DateTime.formatIso(now),
156 } satisfies BufferedAnalyticsEvent,
157 ];
158
159 const next =
160 appended.length > telemetryConfig.maxBufferedEvents
161 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
162 : appended;
163
164 return [
165 {
166 size: next.length,
167 dropped: next.length !== appended.length,
168 } as const,
169 next,
170 ] as const;
171 }),
172 );
173
174 const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
175 events: ReadonlyArray<BufferedAnalyticsEvent>,
176 ) {
177 if (!telemetryConfig.enabled || !identifier) return;
178
179 const payload = {
180 api_key: telemetryConfig.posthogKey,
181 batch: events.map((event) => ({
182 uuid: event.uuid,
183 event: event.event,
184 distinct_id: identifier,
185 properties: {
186 ...event.properties,
187 $process_person_profile: false,
188 platform: hostPlatform,
189 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
190 arch: hostArchitecture,
191 t3CodeVersion: packageJson.version,
192 clientType,
193 serverOs: serverOsFromNodePlatform(hostPlatform),
194 serverArch: hostArchitecture,
195 serverWslDistro: Option.getOrUndefined(telemetryConfig.wslDistroName),
196 serverAppVersion: packageJson.version,
197 serverMode: serverConfig.mode,
198 },
199 timestamp: event.capturedAt,
200 })),
201 };
202
203 yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
204 HttpClientRequest.bodyJson(payload),
205 Effect.flatMap(httpClient.execute),
206 Effect.flatMap(HttpClientResponse.filterStatusOk),
207 Effect.timeout(SEND_TIMEOUT),
208 );
209 });
210
211 const takeBatch = Ref.modify(bufferRef, (current) => {
212 const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
213 return [nextBatch, current.slice(nextBatch.length)] as const;
214 });
215
216 // Sends batches until the buffer is empty or a send fails. A failed batch is
217 // kept for the next flush, and dropped after MAX_BATCH_ATTEMPTS failed sends.
218 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
219 while (true) {
220 const delivery = yield* Ref.get(deliveryRef);
221 const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch;
222 if (batch.length === 0) {
223 return;
224 }
225
226 const sent = yield* Effect.result(sendBatch(batch));
227 if (Result.isSuccess(sent)) {
228 yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures: 0, retryAt: 0 });
229 continue;
230 }
231
232 const failures = delivery.failures + 1;
233 const batchAttempts = delivery.batchAttempts + 1;
234 const retryAt = (yield* Clock.currentTimeMillis) + retryDelayMs(failures, yield* Random.next);
235 if (batchAttempts < MAX_BATCH_ATTEMPTS) {
236 yield* Ref.set(deliveryRef, { failedBatch: batch, batchAttempts, failures, retryAt });
237 yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
238 attempt: batchAttempts,
239 cause: sent.failure,
240 });
241 return;
242 }
243 yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures, retryAt });
244 yield* Effect.logWarning("Dropped telemetry batch after repeated send failures", {
245 events: batch.length,
246 attempts: batchAttempts,
247 cause: sent.failure,
248 });
249 return;
250 }
251 }).pipe(flushLock.withPermit);
252
253 const flushWhenDue = Effect.gen(function* () {
254 const { retryAt } = yield* Ref.get(deliveryRef);
255 if ((yield* Clock.currentTimeMillis) >= retryAt) {
256 yield* flush;
257 }
258 });
259
260 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
261 function* (event, properties) {
262 if (!telemetryConfig.enabled || !identifier) return;
263
264 // Telemetry is best effort: an event without a uuid is not sent. The
265 // Node implementation throws (a defect) rather than failing, so catch both.
266 const uuid = yield* Effect.exit(crypto.randomUUIDv7);
267 if (Exit.isFailure(uuid)) return;
268
269 const enqueueResult = yield* enqueueBufferedEvent(uuid.value, event, properties);
270 if (enqueueResult.dropped) {
271 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
272 size: enqueueResult.size,
273 event,
274 });
275 }
276 },
277 );
278
279 yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.flatMap(() => flushWhenDue)), {
280 disableYield: true,
281 }).pipe(Effect.forkScoped);
282
283 yield* Effect.addFinalizer(() => flush);
284
285 return AnalyticsService.of({ record, flush });
286});
287
288export const layer = Layer.effect(AnalyticsService, make);
289
290const layerTest = AnalyticsService.layerTest;