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

AnalyticsService.ts

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