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

AnalyticsService.ts

335 lines11.7 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​
100function serverOsFromNodePlatform(platform: string): ClientOs {
101 switch (platform) {
102 case "darwin":
103 return "macOS";
104 case "win32":
105 return "Windows";
106 case "linux":
107 return "Linux";
108 case "android":
109 return "Android";
110 default:
111 return "other";
112 }
114​
115/** @public */
116/** @public */
117export const make = Effect.gen(function* () {
118 const telemetryConfig = yield* TelemetryEnvConfig;
119 const httpClient = yield* HttpClient.HttpClient;
120 const serverConfig = yield* ServerConfig.ServerConfig;
121 const { distinctId, installId } = yield* getTelemetryIdentity;
122 const crypto = yield* Crypto.Crypto;
123 const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
124 const deliveryRef = yield* Ref.make<DeliveryState>({
125 failedBatch: [],
126 batchAttempts: 0,
127 firstFailedAt: 0,
128 failures: 0,
129 retryAt: 0,
130 });
131 const recordedOwnersRef = yield* Ref.make<
132 Readonly<Record<"server" | "client", ReadonlySet<string>>>
133 >({ server: new Set(), client: new Set() });
134 // The background flush and the shutdown flush must not send the same batch at once.
135 const flushLock = yield* Semaphore.make(1);
136 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
137 const hostPlatform = yield* HostProcess.Platform;
138 const hostArchitecture = yield* HostProcess.Architecture;
139​
140 const enqueueBufferedEvent = (
141 uuid: string,
142 event: string,
143 properties?: Readonly<Record<string, unknown>>,
144 ) =>
145 Effect.flatMap(DateTime.now, (now) =>
146 Ref.modify(bufferRef, (current) => {
147 const appended = [
148 ...current,
149 {
150 uuid,
151 event,
152 ...(properties ? { properties } : {}),
153 capturedAt: DateTime.formatIso(now),
154 } satisfies BufferedAnalyticsEvent,
155 ];
156​
157 const next =
158 appended.length > telemetryConfig.maxBufferedEvents
159 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
160 : appended;
161​
162 return [
163 {
164 size: next.length,
165 dropped: next.length !== appended.length,
166 } as const,
167 next,
168 ] as const;
169 }),
170 );
171​
172 const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
173 events: ReadonlyArray<BufferedAnalyticsEvent>,
174 ) {
175 if (!telemetryConfig.enabled || !distinctId) return;
176​
177 const payload = {
178 api_key: telemetryConfig.posthogKey,
179 batch: events.map((event) => ({
180 uuid: event.uuid,
181 event: event.event,
182 distinct_id: distinctId,
183 properties: {
184 ...event.properties,
185 ...(installId === null ? {} : { installId }),
186 $process_person_profile: false,
187 platform: hostPlatform,
188 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
189 arch: hostArchitecture,
190 t3CodeVersion: packageJson.version,
191 telemetryChannel: ServerConfig.telemetryChannel,
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 // Back off even after dropping rejected batches so bad API keys cannot drain the queue in a tight loop.
217 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
218 while (true) {
219 const delivery = yield* Ref.get(deliveryRef);
220 const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch;
221 if (batch.length === 0) {
222 return;
223 }
224​
225 const sent = yield* Effect.result(sendBatch(batch));
226 if (Result.isSuccess(sent)) {
227 yield* Ref.set(deliveryRef, {
228 failedBatch: [],
229 batchAttempts: 0,
230 firstFailedAt: 0,
231 failures: 0,
232 retryAt: 0,
233 });
234 continue;
235 }
236​
237 const now = yield* Clock.currentTimeMillis;
238 const failures = delivery.failures + 1;
239 const batchAttempts = delivery.batchAttempts + 1;
240 const firstFailedAt = delivery.batchAttempts === 0 ? now : delivery.firstFailedAt;
241 const retryAt = now + retryDelayMs(failures, yield* Random.next);
242 const error = sent.failure;
243 const rejected =
244 error._tag === "HttpClientError" &&
245 error.reason._tag === "StatusCodeError" &&
246 REJECTED_BATCH_STATUSES.has(error.reason.response.status);
247 if (!rejected && now - firstFailedAt < MAX_BATCH_RETRY_MS) {
248 yield* Ref.set(deliveryRef, {
249 failedBatch: batch,
250 batchAttempts,
251 firstFailedAt,
252 failures,
253 retryAt,
254 });
255 yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
256 attempt: batchAttempts,
257 cause: error,
258 });
259 return;
260 }
261 yield* Ref.set(deliveryRef, {
262 failedBatch: [],
263 batchAttempts: 0,
264 firstFailedAt: 0,
265 failures,
266 retryAt,
267 });
268 yield* Effect.logWarning(
269 rejected
270 ? "Dropped telemetry batch the endpoint rejected"
271 : "Dropped telemetry batch after repeated send failures",
272 { events: batch.length, attempts: batchAttempts, cause: error },
273 );
274 return;
275 }
276 }).pipe(flushLock.withPermit);
277​
278 const flushWhenDue = Effect.gen(function* () {
279 const { retryAt } = yield* Ref.get(deliveryRef);
280 if ((yield* Clock.currentTimeMillis) >= retryAt) {
281 yield* flush;
282 }
283 });
284​
285 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
286 function* (event, properties) {
287 if (!telemetryConfig.enabled || !distinctId) return;
288​
289 // Catch Node UUID defects too; best-effort telemetry drops events without UUIDs.
290 const uuid = yield* Effect.exit(crypto.randomUUIDv7());
291 if (Exit.isFailure(uuid)) return;
292​
293 const enqueueResult = yield* enqueueBufferedEvent(uuid.value, event, properties);
294 if (enqueueResult.dropped) {
295 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
296 size: enqueueResult.size,
297 event,
298 });
299 }
300 },
301 );
302​
303 const recordOwners: AnalyticsService["Service"]["recordOwners"] = Effect.fn(
304 "AnalyticsService.recordOwners",
305 )((owners, observedBy) =>
306 Effect.forEach(
307 owners,
308 ({ source, ownerId }) =>
309 Ref.modify(recordedOwnersRef, (recorded) => {
310 const key = `${source}:${ownerId}`;
311 const seen = recorded[observedBy];
312 return seen.has(key) || seen.size >= MAX_RECORDED_OWNERS
313 ? [false, recorded]
314 : [true, { ...recorded, [observedBy]: new Set(seen).add(key) }];
315 }).pipe(
316 Effect.flatMap((isNew) =>
317 isNew
318 ? record("install.owner_observed", { ownerSource: source, ownerId, observedBy })
319 : Effect.void,
320 ),
321 ),
322 { discard: true },
323 ),
324 );
325​
326 yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.andThen(flushWhenDue)), {
327 disableYield: true,
328 }).pipe(Effect.forkScoped);
329​
330 yield* Effect.addFinalizer(() => flush);
331​
332 return AnalyticsService.of({ record, flush, recordOwners });
333});
334​
335export const layer = Layer.effect(AnalyticsService, make);