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

AnalyticsService.ts

154 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 = Effect.fn("sendBatch")(function* (
74 events: ReadonlyArray<BufferedAnalyticsEvent>,
75 ) {
76 if (!telemetryConfig.enabled || !identifier) return;
77​
78 const payload = {
79 api_key: telemetryConfig.posthogKey,
80 batch: events.map((event) => ({
81 event: event.event,
82 distinct_id: identifier,
83 properties: {
84 ...event.properties,
85 $process_person_profile: false,
86 platform: process.platform,
87 wsl: process.env.WSL_DISTRO_NAME,
88 arch: process.arch,
89 t3CodeVersion: version,
90 clientType,
91 },
92 timestamp: event.capturedAt,
93 })),
94 };
95​
96 yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
97 HttpClientRequest.bodyJson(payload),
98 Effect.flatMap(httpClient.execute),
99 Effect.flatMap(HttpClientResponse.filterStatusOk),
100 );
101 });
102​
103 const flush: AnalyticsServiceShape["flush"] = Effect.gen(function* () {
104 while (true) {
105 const batch = yield* Ref.modify(bufferRef, (current) => {
106 if (current.length === 0) {
107 return [[] as ReadonlyArray<BufferedAnalyticsEvent>, current] as const;
108 }
109 const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
110 const remaining = current.slice(nextBatch.length);
111 return [nextBatch, remaining] as const;
112 });
113​
114 if (batch.length === 0) {
115 return;
116 }
117​
118 yield* sendBatch(batch).pipe(
119 Effect.catch((error) =>
120 Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
121 Effect.flatMap(() => Effect.fail(error)),
122 ),
123 ),
124 );
125 }
126 }).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
127​
128 const record: AnalyticsServiceShape["record"] = Effect.fn("record")(
129 function* (event, properties) {
130 if (!telemetryConfig.enabled || !identifier) return;
131​
132 const enqueueResult = yield* enqueueBufferedEvent(event, properties);
133 if (enqueueResult.dropped) {
134 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
135 size: enqueueResult.size,
136 event,
137 });
138 }
139 },
140 );
141​
142 yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
143 disableYield: true,
144 }).pipe(Effect.forkScoped);
145​
146 yield* Effect.addFinalizer(() => flush);
147​
148 return {
149 record,
150 flush,
151 } satisfies AnalyticsServiceShape;
152});
153​
154export const AnalyticsServiceLayerLive = Layer.effect(AnalyticsService, makeAnalyticsService);