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

AnalyticsService.ts

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