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

AnalyticsService.ts

298 lines10.6 KB

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