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 { awaitBackgroundTurn } from "../serverActivation.ts";
28import { getTelemetryIdentifier } from "./Identify.ts";
29
30interface BufferedAnalyticsEvent {
31 readonly uuid: string;
32 readonly event: string;
33 readonly properties?: Readonly<Record<string, unknown>>;
34 readonly capturedAt: string;
35}
36
37interface DeliveryState {
38 readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>;
39 readonly batchAttempts: number;
40 readonly failures: number;
41 readonly retryAt: number;
42}
43
44// The background flush checks for work at this interval, so a retry delay
45// shorter than it waits for the next check.
46const FLUSH_INTERVAL_MS = 10_000;
47// A hung send would hold the flush lock, and with it the shutdown flush.
48const SEND_TIMEOUT = "10 seconds";
49const MAX_BATCH_ATTEMPTS = 5;
50const RETRY_BASE_DELAY_MS = 2_000;
51const RETRY_MAX_DELAY_MS = 300_000;
52// The endpoint answers these when the batch itself is wrong (bad body, wrong
53// api_key, too large), so sending it again cannot help. 408 and 429 are not
54// here because a later send can succeed.
55const REJECTED_BATCH_STATUSES = new Set([400, 401, 413]);
56
57/**
58 * Release channel of this build. Release workflows set it for
59 * pingdotgg/t3code builds (see apps/server/vite.config.ts); every other build
60 * reports "dev". It is separate from `__T3CODE_BUILD_CHANNEL__`, which names
61 * stable "latest" and preview "nightly" for the sign-in page.
62 */
63declare const __T3CODE_TELEMETRY_CHANNEL__: "stable" | "nightly" | "preview" | "dev" | undefined;
64
65/** `random` is in [0, 1). */
66export function retryDelayMs(failures: number, random: number): number {
67 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failures - 1));
68 return Math.round(ceiling / 2 + (ceiling / 2) * random);
69}
70
71const TelemetryEnvConfig = Config.all({
72 posthogKey: Config.String("T3CODE_POSTHOG_KEY").pipe(
73 Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
74 ),
75 posthogHost: Config.String("T3CODE_POSTHOG_HOST").pipe(
76 Config.withDefault("https://ingest.t3.codes"),
77 ),
78 enabled: Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe(Config.withDefault(true)),
79 flushBatchSize: Config.Number("T3CODE_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)),
80 maxBufferedEvents: Config.Number("T3CODE_TELEMETRY_MAX_BUFFERED_EVENTS").pipe(
81 Config.withDefault(1_000),
82 ),
83 wslDistroName: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
84});
85
86export class AnalyticsService extends Context.Service<
87 AnalyticsService,
88 {
89 readonly record: (
90 event: string,
91 properties?: Readonly<Record<string, unknown>>,
92 ) => Effect.Effect<void>;
93
94 readonly flush: Effect.Effect<void>;
95 }
96>()("t3/telemetry/AnalyticsService") {
97 static readonly layerTest = Layer.succeed(
98 AnalyticsService,
99 AnalyticsService.of({
100 record: () => Effect.void,
101 flush: Effect.void,
102 }),
103 );
104}
105
106function serverOsFromNodePlatform(platform: string): ClientOs {
107 switch (platform) {
108 case "darwin":
109 return "macOS";
110 case "win32":
111 return "Windows";
112 case "linux":
113 return "Linux";
114 case "android":
115 return "Android";
116 default:
117 return "other";
118 }
119}
120
121/** @public */
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 telemetryChannel =
140 typeof __T3CODE_TELEMETRY_CHANNEL__ === "undefined" ? "dev" : __T3CODE_TELEMETRY_CHANNEL__;
141 const hostPlatform = yield* HostProcess.Platform;
142 const hostArchitecture = yield* HostProcess.Architecture;
143
144 const enqueueBufferedEvent = (
145 uuid: string,
146 event: string,
147 properties?: Readonly<Record<string, unknown>>,
148 ) =>
149 Effect.flatMap(DateTime.now, (now) =>
150 Ref.modify(bufferRef, (current) => {
151 const appended = [
152 ...current,
153 {
154 uuid,
155 event,
156 ...(properties ? { properties } : {}),
157 capturedAt: DateTime.formatIso(now),
158 } satisfies BufferedAnalyticsEvent,
159 ];
160
161 const next =
162 appended.length > telemetryConfig.maxBufferedEvents
163 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
164 : appended;
165
166 return [
167 {
168 size: next.length,
169 dropped: next.length !== appended.length,
170 } as const,
171 next,
172 ] as const;
173 }),
174 );
175
176 const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
177 events: ReadonlyArray<BufferedAnalyticsEvent>,
178 ) {
179 if (!telemetryConfig.enabled || !identifier) return;
180
181 const payload = {
182 api_key: telemetryConfig.posthogKey,
183 batch: events.map((event) => ({
184 uuid: event.uuid,
185 event: event.event,
186 distinct_id: identifier,
187 properties: {
188 ...event.properties,
189 $process_person_profile: false,
190 platform: hostPlatform,
191 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
192 arch: hostArchitecture,
193 t3CodeVersion: packageJson.version,
194 telemetryChannel,
195 clientType,
196 serverOs: serverOsFromNodePlatform(hostPlatform),
197 serverArch: hostArchitecture,
198 serverWslDistro: Option.getOrUndefined(telemetryConfig.wslDistroName),
199 serverAppVersion: packageJson.version,
200 serverMode: serverConfig.mode,
201 },
202 timestamp: event.capturedAt,
203 })),
204 };
205
206 yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
207 HttpClientRequest.bodyJson(payload),
208 Effect.flatMap(httpClient.execute),
209 Effect.flatMap(HttpClientResponse.filterStatusOk),
210 Effect.timeout(SEND_TIMEOUT),
211 );
212 });
213
214 const takeBatch = Ref.modify(bufferRef, (current) => {
215 const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
216 return [nextBatch, current.slice(nextBatch.length)] as const;
217 });
218
219 // A rejected batch is dropped at once, but the next batch still waits for the
220 // backoff, so a wrong api_key does not send every batch as fast as it can.
221 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
222 while (true) {
223 const delivery = yield* Ref.get(deliveryRef);
224 const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch;
225 if (batch.length === 0) {
226 return;
227 }
228
229 const sent = yield* Effect.result(sendBatch(batch));
230 if (Result.isSuccess(sent)) {
231 yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures: 0, retryAt: 0 });
232 continue;
233 }
234
235 const failures = delivery.failures + 1;
236 const batchAttempts = delivery.batchAttempts + 1;
237 const retryAt = (yield* Clock.currentTimeMillis) + retryDelayMs(failures, yield* Random.next);
238 const error = sent.failure;
239 const rejected =
240 error._tag === "HttpClientError" &&
241 error.reason._tag === "StatusCodeError" &&
242 REJECTED_BATCH_STATUSES.has(error.reason.response.status);
243 if (!rejected && batchAttempts < MAX_BATCH_ATTEMPTS) {
244 yield* Ref.set(deliveryRef, { failedBatch: batch, batchAttempts, failures, retryAt });
245 yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
246 attempt: batchAttempts,
247 cause: error,
248 });
249 return;
250 }
251 yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures, retryAt });
252 yield* Effect.logWarning(
253 rejected
254 ? "Dropped telemetry batch the endpoint rejected"
255 : "Dropped telemetry batch after repeated send failures",
256 { events: batch.length, attempts: batchAttempts, cause: error },
257 );
258 return;
259 }
260 }).pipe(flushLock.withPermit);
261
262 const flushWhenDue = Effect.gen(function* () {
263 const { retryAt } = yield* Ref.get(deliveryRef);
264 if ((yield* Clock.currentTimeMillis) >= retryAt) {
265 yield* flush;
266 }
267 });
268
269 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
270 function* (event, properties) {
271 if (!telemetryConfig.enabled || !identifier) return;
272
273 // Telemetry is best effort: an event without a uuid is not sent. The
274 // Node implementation throws (a defect) rather than failing, so catch both.
275 const uuid = yield* Effect.exit(crypto.randomUUIDv7());
276 if (Exit.isFailure(uuid)) return;
277
278 const enqueueResult = yield* enqueueBufferedEvent(uuid.value, event, properties);
279 if (enqueueResult.dropped) {
280 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
281 size: enqueueResult.size,
282 event,
283 });
284 }
285 },
286 );
287
288 // A starting server sends its first batch once startup work may run.
289 yield* awaitBackgroundTurn.pipe(
290 Effect.andThen(
291 Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.flatMap(() => flushWhenDue)), {
292 disableYield: true,
293 }),
294 ),
295 Effect.forkScoped,
296 );
297
298 yield* Effect.addFinalizer(() => flush);
299
300 return AnalyticsService.of({ record, flush });
301});
302
303export const layer = Layer.effect(AnalyticsService, make);
304
305const layerTest = AnalyticsService.layerTest;