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

AnalyticsService.ts

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