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

AnalyticsService.ts

272 lines9.1 KB

1/**
2 * Each event carries a uuid, so PostHog can tell a retried copy from a new
3 * event.
4 */
5import * as HostProcess from "@t3tools/shared/HostProcess";
6import type { ClientOs } from "@t3tools/contracts";
7import * as Clock from "effect/Clock";
8import * as Config from "effect/Config";
9import * as Context from "effect/Context";
10import * as Crypto from "effect/Crypto";
11import * as DateTime from "effect/DateTime";
12import * as Effect from "effect/Effect";
13import * as Exit from "effect/Exit";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Random from "effect/Random";
17import * as Ref from "effect/Ref";
18import * as Result from "effect/Result";
19import * as Semaphore from "effect/Semaphore";
20import * as HttpClient from "effect/http/HttpClient";
21import * as HttpClientRequest from "effect/http/HttpClientRequest";
22import * as HttpClientResponse from "effect/http/HttpClientResponse";
23​
24import packageJson from "../../package.json" with { type: "json" };
25import * as ServerConfig from "../config.ts";
26import { getTelemetryIdentifier } from "./Identify.ts";
27​
28interface BufferedAnalyticsEvent {
29 readonly uuid: string;
30 readonly event: string;
31 readonly properties?: Readonly<Record<string, unknown>>;
32 readonly capturedAt: string;
34​
35interface DeliveryState {
36 readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>;
37 readonly batchAttempts: number;
38 readonly failures: number;
39 readonly retryAt: number;
41​
42const FLUSH_INTERVAL_MS = 1_000;
43// A hung send would hold the flush lock, and with it the shutdown flush.
44const SEND_TIMEOUT = "10 seconds";
45const MAX_BATCH_ATTEMPTS = 5;
46const RETRY_BASE_DELAY_MS = 2_000;
47const RETRY_MAX_DELAY_MS = 300_000;
48​
49/** `random` is in [0, 1). */
50export function retryDelayMs(failures: number, random: number): number {
51 const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failures - 1));
52 return Math.round(ceiling / 2 + (ceiling / 2) * random);
54​
55const TelemetryEnvConfig = Config.all({
56 posthogKey: Config.String("T3CODE_POSTHOG_KEY").pipe(
57 Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
58 ),
59 posthogHost: Config.String("T3CODE_POSTHOG_HOST").pipe(
60 Config.withDefault("https://us.i.posthog.com"),
61 ),
62 enabled: Config.Boolean("T3CODE_TELEMETRY_ENABLED").pipe(Config.withDefault(true)),
63 flushBatchSize: Config.Number("T3CODE_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)),
64 maxBufferedEvents: Config.Number("T3CODE_TELEMETRY_MAX_BUFFERED_EVENTS").pipe(
65 Config.withDefault(1_000),
66 ),
67 wslDistroName: Config.String("WSL_DISTRO_NAME").pipe(Config.option),
68});
69​
70export class AnalyticsService extends Context.Service<
71 AnalyticsService,
72 {
73 readonly record: (
74 event: string,
75 properties?: Readonly<Record<string, unknown>>,
76 ) => Effect.Effect<void>;
77​
78 readonly flush: Effect.Effect<void>;
79 }
80>()("t3/telemetry/AnalyticsService") {
81 static readonly layerTest = Layer.succeed(
82 AnalyticsService,
83 AnalyticsService.of({
84 record: () => Effect.void,
85 flush: Effect.void,
86 }),
87 );
89​
90function serverOsFromNodePlatform(platform: string): ClientOs {
91 switch (platform) {
92 case "darwin":
93 return "macOS";
94 case "win32":
95 return "Windows";
96 case "linux":
97 return "Linux";
98 case "android":
99 return "Android";
100 default:
101 return "other";
102 }
104​
105/** @public */
106/** @public Service construction is part of the canonical Effect module API. */
107export const make = Effect.gen(function* () {
108 const telemetryConfig = yield* TelemetryEnvConfig;
109 const httpClient = yield* HttpClient.HttpClient;
110 const serverConfig = yield* ServerConfig.ServerConfig;
111 const identifier = yield* getTelemetryIdentifier;
112 const crypto = yield* Crypto.Crypto;
113 const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
114 const deliveryRef = yield* Ref.make<DeliveryState>({
115 failedBatch: [],
116 batchAttempts: 0,
117 failures: 0,
118 retryAt: 0,
119 });
120 // The background flush and the shutdown flush must not send the same batch at once.
121 const flushLock = yield* Semaphore.make(1);
122 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
123 const hostPlatform = yield* HostProcess.Platform;
124 const hostArchitecture = yield* HostProcess.Architecture;
125​
126 const enqueueBufferedEvent = (
127 uuid: string,
128 event: string,
129 properties?: Readonly<Record<string, unknown>>,
130 ) =>
131 Effect.flatMap(DateTime.now, (now) =>
132 Ref.modify(bufferRef, (current) => {
133 const appended = [
134 ...current,
135 {
136 uuid,
137 event,
138 ...(properties ? { properties } : {}),
139 capturedAt: DateTime.formatIso(now),
140 } satisfies BufferedAnalyticsEvent,
141 ];
142​
143 const next =
144 appended.length > telemetryConfig.maxBufferedEvents
145 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
146 : appended;
147​
148 return [
149 {
150 size: next.length,
151 dropped: next.length !== appended.length,
152 } as const,
153 next,
154 ] as const;
155 }),
156 );
157​
158 const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
159 events: ReadonlyArray<BufferedAnalyticsEvent>,
160 ) {
161 if (!telemetryConfig.enabled || !identifier) return;
162​
163 const payload = {
164 api_key: telemetryConfig.posthogKey,
165 batch: events.map((event) => ({
166 uuid: event.uuid,
167 event: event.event,
168 distinct_id: identifier,
169 properties: {
170 ...event.properties,
171 $process_person_profile: false,
172 platform: hostPlatform,
173 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
174 arch: hostArchitecture,
175 t3CodeVersion: packageJson.version,
176 clientType,
177 serverOs: serverOsFromNodePlatform(hostPlatform),
178 serverArch: hostArchitecture,
179 serverWslDistro: Option.getOrUndefined(telemetryConfig.wslDistroName),
180 serverAppVersion: packageJson.version,
181 serverMode: serverConfig.mode,
182 },
183 timestamp: event.capturedAt,
184 })),
185 };
186​
187 yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
188 HttpClientRequest.bodyJson(payload),
189 Effect.flatMap(httpClient.execute),
190 Effect.flatMap(HttpClientResponse.filterStatusOk),
191 Effect.timeout(SEND_TIMEOUT),
192 );
193 });
194​
195 const takeBatch = Ref.modify(bufferRef, (current) => {
196 const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
197 return [nextBatch, current.slice(nextBatch.length)] as const;
198 });
199​
200 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
201 while (true) {
202 const delivery = yield* Ref.get(deliveryRef);
203 const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch;
204 if (batch.length === 0) {
205 return;
206 }
207​
208 const sent = yield* Effect.result(sendBatch(batch));
209 if (Result.isSuccess(sent)) {
210 yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures: 0, retryAt: 0 });
211 continue;
212 }
213​
214 const failures = delivery.failures + 1;
215 const batchAttempts = delivery.batchAttempts + 1;
216 const retryAt = (yield* Clock.currentTimeMillis) + retryDelayMs(failures, yield* Random.next);
217 if (batchAttempts < MAX_BATCH_ATTEMPTS) {
218 yield* Ref.set(deliveryRef, { failedBatch: batch, batchAttempts, failures, retryAt });
219 yield* Effect.logDebug("Failed to send telemetry batch; will retry", {
220 attempt: batchAttempts,
221 cause: sent.failure,
222 });
223 return;
224 }
225 yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures, retryAt });
226 yield* Effect.logWarning("Dropped telemetry batch after repeated send failures", {
227 events: batch.length,
228 attempts: batchAttempts,
229 cause: sent.failure,
230 });
231 return;
232 }
233 }).pipe(flushLock.withPermit);
234​
235 const flushWhenDue = Effect.gen(function* () {
236 const { retryAt } = yield* Ref.get(deliveryRef);
237 if ((yield* Clock.currentTimeMillis) >= retryAt) {
238 yield* flush;
239 }
240 });
241​
242 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
243 function* (event, properties) {
244 if (!telemetryConfig.enabled || !identifier) return;
245​
246 // Telemetry is best effort: an event without a uuid is not sent. The
247 // Node implementation throws (a defect) rather than failing, so catch both.
248 const uuid = yield* Effect.exit(crypto.randomUUIDv7());
249 if (Exit.isFailure(uuid)) return;
250​
251 const enqueueResult = yield* enqueueBufferedEvent(uuid.value, event, properties);
252 if (enqueueResult.dropped) {
253 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
254 size: enqueueResult.size,
255 event,
256 });
257 }
258 },
259 );
260​
261 yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.flatMap(() => flushWhenDue)), {
262 disableYield: true,
263 }).pipe(Effect.forkScoped);
264​
265 yield* Effect.addFinalizer(() => flush);
266​
267 return AnalyticsService.of({ record, flush });
268});
269​
270export const layer = Layer.effect(AnalyticsService, make);
271​
272const layerTest = AnalyticsService.layerTest;