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

AnalyticsService.ts

151 lines5.1 KB

1/**
2 * AnalyticsServiceLive - Anonymous PostHog telemetry layer.
3 *
4 * Persists a random installation-scoped anonymous id to state dir, buffers
5 * events in memory, and flushes batches to PostHog over Effect HttpClient.
6 *
7 * @module AnalyticsServiceLive
8 */
9​
10import { Config, DateTime, Effect, Layer, Ref } from "effect";
11import { HttpClient, HttpClientRequest, HttpClientResponse } from "effect/unstable/http";
12​
13import { ServerConfig } from "../../config.ts";
14import { AnalyticsService, type AnalyticsServiceShape } from "../Services/AnalyticsService.ts";
15import { getTelemetryIdentifier } from "../Identify.ts";
16import { version } from "../../../package.json" with { type: "json" };
17​
18interface BufferedAnalyticsEvent {
19 readonly event: string;
20 readonly properties?: Readonly<Record<string, unknown>>;
21 readonly capturedAt: string;
23​
24const TelemetryEnvConfig = Config.all({
25 posthogKey: Config.string("T3CODE_POSTHOG_KEY").pipe(
26 Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
27 ),
28 posthogHost: Config.string("T3CODE_POSTHOG_HOST").pipe(
29 Config.withDefault("https://us.i.posthog.com"),
30 ),
31 enabled: Config.boolean("T3CODE_TELEMETRY_ENABLED").pipe(Config.withDefault(true)),
32 flushBatchSize: Config.number("T3CODE_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)),
33 maxBufferedEvents: Config.number("T3CODE_TELEMETRY_MAX_BUFFERED_EVENTS").pipe(
34 Config.withDefault(1_000),
35 ),
36});
37​
38const makeAnalyticsService = Effect.gen(function* () {
39 const telemetryConfig = yield* TelemetryEnvConfig.asEffect();
40 const httpClient = yield* HttpClient.HttpClient;
41 const serverConfig = yield* ServerConfig;
42 const identifier = yield* getTelemetryIdentifier;
43 const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
44 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
45​
46 const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>
47 Effect.flatMap(DateTime.now, (now) =>
48 Ref.modify(bufferRef, (current) => {
49 const appended = [
50 ...current,
51 {
52 event,
53 ...(properties ? { properties } : {}),
54 capturedAt: DateTime.formatIso(now),
55 } satisfies BufferedAnalyticsEvent,
56 ];
57​
58 const next =
59 appended.length > telemetryConfig.maxBufferedEvents
60 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
61 : appended;
62​
63 return [
64 {
65 size: next.length,
66 dropped: next.length !== appended.length,
67 } as const,
68 next,
69 ] as const;
70 }),
71 );
72​
73 const sendBatch = (events: ReadonlyArray<BufferedAnalyticsEvent>) =>
74 Effect.gen(function* () {
75 if (!telemetryConfig.enabled || !identifier) return;
76​
77 const payload = {
78 api_key: telemetryConfig.posthogKey,
79 batch: events.map((event) => ({
80 event: event.event,
81 distinct_id: identifier,
82 properties: {
83 ...event.properties,
84 $process_person_profile: false,
85 platform: process.platform,
86 wsl: process.env.WSL_DISTRO_NAME,
87 arch: process.arch,
88 t3CodeVersion: version,
89 clientType,
90 },
91 timestamp: event.capturedAt,
92 })),
93 };
94​
95 yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
96 HttpClientRequest.bodyJson(payload),
97 Effect.flatMap(httpClient.execute),
98 Effect.flatMap(HttpClientResponse.filterStatusOk),
99 );
100 });
101​
102 const flush: AnalyticsServiceShape["flush"] = Effect.gen(function* () {
103 while (true) {
104 const batch = yield* Ref.modify(bufferRef, (current) => {
105 if (current.length === 0) {
106 return [[] as ReadonlyArray<BufferedAnalyticsEvent>, current] as const;
107 }
108 const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
109 const remaining = current.slice(nextBatch.length);
110 return [nextBatch, remaining] as const;
111 });
112​
113 if (batch.length === 0) {
114 return;
115 }
116​
117 yield* sendBatch(batch).pipe(
118 Effect.catch((error) =>
119 Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
120 Effect.flatMap(() => Effect.fail(error)),
121 ),
122 ),
123 );
124 }
125 }).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
126​
127 const record: AnalyticsServiceShape["record"] = Effect.fnUntraced(function* (event, properties) {
128 if (!telemetryConfig.enabled || !identifier) return;
129​
130 const enqueueResult = yield* enqueueBufferedEvent(event, properties);
131 if (enqueueResult.dropped) {
132 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
133 size: enqueueResult.size,
134 event,
135 });
136 }
137 });
138​
139 yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
140 disableYield: true,
141 }).pipe(Effect.forkScoped);
142​
143 yield* Effect.addFinalizer(() => flush);
144​
145 return {
146 record,
147 flush,
148 } satisfies AnalyticsServiceShape;
149});
150​
151export const AnalyticsServiceLayerLive = Layer.effect(AnalyticsService, makeAnalyticsService);