Open History to see the last commit
1/**
2 * Events go to the T3 Code ingest endpoint, which keeps a copy and forwards
3 * them to PostHog. Each event carries a uuid, so PostHog can tell a retried
4 * copy from a new event.
5 */
6import * as HostProcess from "@t3tools/shared/HostProcess";
7import type { ClientOs } from "@t3tools/contracts";
8import * as Clock from "effect/Clock";
9import * as Config from "effect/Config";
10import * as Context from "effect/Context";
11import * as Crypto from "effect/Crypto";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Exit from "effect/Exit";
15import * as Layer from "effect/Layer";
16import * as Option from "effect/Option";
17import * as Random from "effect/Random";
18import * as Ref from "effect/Ref";
19import * as Result from "effect/Result";
20import * as Semaphore from "effect/Semaphore";
21import * as HttpClient from "effect/http/HttpClient";
22import * as HttpClientRequest from "effect/http/HttpClientRequest";
23import * as HttpClientResponse from "effect/http/HttpClientResponse";
24
25import packageJson from "../../package.json" with { type: "json" };
26import * as ServerConfig from "../config.ts";
27import { getTelemetryIdentity, type TelemetryOwner } from "./Identify.ts";
28
29interface BufferedAnalyticsEvent {
30 readonly uuid: string;
31 readonly event: string;
32 readonly properties?: Readonly<Record<string, unknown>>;
33 readonly capturedAt: string;
34}
35
36interface DeliveryState {
37 readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>;
38 readonly batchAttempts: number;
39 readonly failures: number;
40 readonly retryAt: number;
41}
42
43// The background flush checks for work at this interval, so a retry delay
44// shorter than it waits for the next check.
45const FLUSH_INTERVAL_MS = 10_000;
46// A hung send would hold the flush lock, and with it the shutdown flush.
47const SEND_TIMEOUT = "10 seconds";
48const MAX_BATCH_ATTEMPTS = 5;
49const RETRY_BASE_DELAY_MS = 2_000;
50// Clients can report any number of owner ids; past this many per observer, new ones
51// are not sent. Each observer has its own cap, so client reports never crowd out the
52// server's own.
53const MAX_RECORDED_OWNERS = 1_000;
54const RETRY_MAX_DELAY_MS = 300_000;
55// The endpoint answers these when the batch itself is wrong (bad body, wrong
56// api_key, too large), so sending it again cannot help. 408 and 429 are not
57// here because a later send can succeed.
58const REJECTED_BATCH_STATUSES = new Set([400, 401, 413]);
59
60/**
61 * Release channel of this build. Release workflows set it for
62 * pingdotgg/t3code builds (see apps/server/vite.config.ts); every other build
63 * reports "dev". It is separate from `__T3CODE_BUILD_CHANNEL__`, which names
64 * stable "latest" and preview "nightly" for the sign-in page.
65 */
66declare const __T3CODE_TELEMETRY_CHANNEL__: "stable" | "nightly" | "preview" | "dev" | undefined;
67
68/** `random` is in [0, 1). */
69export function retryDelayMs(failures: number, random: number): number {
70 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failures - 1));
71 return Math.round(ceiling / 2 + (ceiling / 2) * random);
72}
73
74const TelemetryEnvConfig = Config.all({
75 posthogKey: Config.String("T3CODE_POSTHOG_KEY").pipe(
76 Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
77 ),
78 posthogHost: Config.String("T3CODE_POSTHOG_HOST").pipe(
79 Config.withDefault("https://ingest.t3.codes"),
80 ),
81 enabled: Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe(Config.withDefault(true)),
82 flushBatchSize: Config.Number("T3CODE_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)),
83 maxBufferedEvents: Config.Number("T3CODE_TELEMETRY_MAX_BUFFERED_EVENTS").pipe(
84 Config.withDefault(1_000),
85 ),
86 wslDistroName: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
87});
88
89export class AnalyticsService extends Context.Service<
90 AnalyticsService,
91 {
92 readonly record: (
93 event: string,
94 properties?: Readonly<Record<string, unknown>>,
95 ) => Effect.Effect<void>;
96
97 readonly flush: Effect.Effect<void>;
98
99 /**
100 * Records `install.owner_observed` for each owner of this install that the
101 * server read itself or a connecting client reported. Each owner is sent once
102 * per server process, so reconnects and repeated reads are free.
103 */
104 readonly recordOwners: (
105 owners: ReadonlyArray<TelemetryOwner>,
106 observedBy: "server" | "client",
107 ) => Effect.Effect<void>;
108 }
109>()("t3/telemetry/AnalyticsService") {
110 static readonly layerTest = Layer.succeed(
111 AnalyticsService,
112 AnalyticsService.of({
113 record: () => Effect.void,
114 flush: Effect.void,
115 recordOwners: () => Effect.void,
116 }),
117 );
118}
119
120function serverOsFromNodePlatform(platform: string): ClientOs {
121 switch (platform) {
122 case "darwin":
123 return "macOS";
124 case "win32":
125 return "Windows";
126 case "linux":
127 return "Linux";
128 case "android":
129 return "Android";
130 default:
131 return "other";
132 }
133}
134
135/** @public */
136/** @public Service construction is part of the canonical Effect module API. */
137export const make = Effect.gen(function* () {
138 const telemetryConfig = yield* TelemetryEnvConfig;
139 const httpClient = yield* HttpClient.HttpClient;
140 const serverConfig = yield* ServerConfig.ServerConfig;
141 const { distinctId, installId } = yield* getTelemetryIdentity;
142 const crypto = yield* Crypto.Crypto;
143 const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
144 const deliveryRef = yield* Ref.make<DeliveryState>({
145 failedBatch: [],
146 batchAttempts: 0,
147 failures: 0,
148 retryAt: 0,
149 });
150 const recordedOwnersRef = yield* Ref.make<
151 Readonly<Record<"server" | "client", ReadonlySet<string>>>
152 >({ server: new Set(), client: new Set() });
153 // The background flush and the shutdown flush must not send the same batch at once.
154 const flushLock = yield* Semaphore.make(1);
155 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
156 const telemetryChannel =
157 typeof __T3CODE_TELEMETRY_CHANNEL__ === "undefined" ? "dev" : __T3CODE_TELEMETRY_CHANNEL__;
158 const hostPlatform = yield* HostProcess.Platform;
159 const hostArchitecture = yield* HostProcess.Architecture;
160
161 const enqueueBufferedEvent = (
162 uuid: string,
163 event: string,
164 properties?: Readonly<Record<string, unknown>>,
165 ) =>
166 Effect.flatMap(DateTime.now, (now) =>
167 Ref.modify(bufferRef, (current) => {
168 const appended = [
169 ...current,
170 {
171 uuid,
172 event,
173 ...(properties ? { properties } : {}),
174 capturedAt: DateTime.formatIso(now),
175 } satisfies BufferedAnalyticsEvent,
176 ];
177
178 const next =
179 appended.length > telemetryConfig.maxBufferedEvents
180 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
181 : appended;
182
183 return [
184 {
185 size: next.length,
186 dropped: next.length !== appended.length,
187 } as const,
188 next,
189 ] as const;
190 }),
191 );
192
193 const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
194 events: ReadonlyArray<BufferedAnalyticsEvent>,
195 ) {
196 if (!telemetryConfig.enabled || !distinctId) return;
197
198 const payload = {
199 api_key: telemetryConfig.posthogKey,
200 batch: events.map((event) => ({
201 uuid: event.uuid,
202 event: event.event,
203 distinct_id: distinctId,
204 properties: {
205 ...event.properties,
206 ...(installId === null ? {} : { installId }),
207 $process_person_profile: false,
208 platform: hostPlatform,
209 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
210 arch: hostArchitecture,
211 t3CodeVersion: packageJson.version,
212 telemetryChannel,
213 clientType,
214 serverOs: serverOsFromNodePlatform(hostPlatform),
215 serverArch: hostArchitecture,
216 serverWslDistro: Option.getOrUndefined(telemetryConfig.wslDistroName),
217 serverAppVersion: packageJson.version,
218 serverMode: serverConfig.mode,
219 },
220 timestamp: event.capturedAt,
221 })),
222 };
223
224 yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
225 HttpClientRequest.bodyJson(payload),
226 Effect.flatMap(httpClient.execute),
227 Effect.flatMap(HttpClientResponse.filterStatusOk),
228 Effect.timeout(SEND_TIMEOUT),
229 );
230 });
231
232 const takeBatch = Ref.modify(bufferRef, (current) => {
233 const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
234 return [nextBatch, current.slice(nextBatch.length)] as const;
235 });
236
237 // A rejected batch is dropped at once, but the next batch still waits for the
238 // backoff, so a wrong api_key does not send every batch as fast as it can.
239 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
240 while (true) {
241 const delivery = yield* Ref.get(deliveryRef);
242 const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch;
243 if (batch.length === 0) {
244 return;
245 }
246
247 const sent = yield* Effect.result(sendBatch(batch));
248 if (Result.isSuccess(sent)) {
249 yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures: 0, retryAt: 0 });
250 continue;
251 }
252
253 const failures = delivery.failures + 1;
254 const batchAttempts = delivery.batchAttempts + 1;
255 const retryAt = (yield* Clock.currentTimeMillis) + retryDelayMs(failures, yield* Random.next);
256 const error = sent.failure;
257 const rejected =
258 error._tag === "HttpClientError" &&
259 error.reason._tag === "StatusCodeError" &&
260 REJECTED_BATCH_STATUSES.has(error.reason.response.status);
261 if (!rejected && batchAttempts < MAX_BATCH_ATTEMPTS) {
262 yield* Ref.set(deliveryRef, { failedBatch: batch, batchAttempts, failures, retryAt });
263 yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
264 attempt: batchAttempts,
265 cause: error,
266 });
267 return;
268 }
269 yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures, retryAt });
270 yield* Effect.logWarning(
271 rejected
272 ? "Dropped telemetry batch the endpoint rejected"
273 : "Dropped telemetry batch after repeated send failures",
274 { events: batch.length, attempts: batchAttempts, cause: error },
275 );
276 return;
277 }
278 }).pipe(flushLock.withPermit);
279
280 const flushWhenDue = Effect.gen(function* () {
281 const { retryAt } = yield* Ref.get(deliveryRef);
282 if ((yield* Clock.currentTimeMillis) >= retryAt) {
283 yield* flush;
284 }
285 });
286
287 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
288 function* (event, properties) {
289 if (!telemetryConfig.enabled || !distinctId) return;
290
291 // Telemetry is best effort: an event without a uuid is not sent. The
292 // Node implementation throws (a defect) rather than failing, so catch both.
293 const uuid = yield* Effect.exit(crypto.randomUUIDv7());
294 if (Exit.isFailure(uuid)) return;
295
296 const enqueueResult = yield* enqueueBufferedEvent(uuid.value, event, properties);
297 if (enqueueResult.dropped) {
298 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
299 size: enqueueResult.size,
300 event,
301 });
302 }
303 },
304 );
305
306 const recordOwners: AnalyticsService["Service"]["recordOwners"] = Effect.fn(
307 "AnalyticsService.recordOwners",
308 )((owners, observedBy) =>
309 Effect.forEach(
310 owners,
311 ({ source, ownerId }) =>
312 Ref.modify(recordedOwnersRef, (recorded) => {
313 const key = `${source}:${ownerId}`;
314 const seen = recorded[observedBy];
315 return seen.has(key) || seen.size >= MAX_RECORDED_OWNERS
316 ? [false, recorded]
317 : [true, { ...recorded, [observedBy]: new Set(seen).add(key) }];
318 }).pipe(
319 Effect.flatMap((isNew) =>
320 isNew
321 ? record("install.owner_observed", { ownerSource: source, ownerId, observedBy })
322 : Effect.void,
323 ),
324 ),
325 { discard: true },
326 ),
327 );
328
329 yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.flatMap(() => flushWhenDue)), {
330 disableYield: true,
331 }).pipe(Effect.forkScoped);
332
333 yield* Effect.addFinalizer(() => flush);
334
335 return AnalyticsService.of({ record, flush, recordOwners });
336});
337
338export const layer = Layer.effect(AnalyticsService, make);
339
340const layerTest = AnalyticsService.layerTest;