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

AnalyticsService.ts

186 lines6.3 KB

1/**
2 * Anonymous PostHog telemetry service.
3 *
4 * Persists an installation-scoped anonymous identifier, buffers events in
5 * memory, and flushes batches over Effect's HTTP client.
6 *
7 * @module AnalyticsService
8 */
9import { HostProcessArchitecture, HostProcessPlatform } from "@v12/shared/hostProcess";
10import * as Config from "effect/Config";
11import * as Context from "effect/Context";
12import * as DateTime from "effect/DateTime";
13import * as Effect from "effect/Effect";
14import * as Layer from "effect/Layer";
15import * as Option from "effect/Option";
16import * as Ref from "effect/Ref";
17import * as HttpClient from "effect/unstable/http/HttpClient";
18import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest";
19import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse";
20​
21import packageJson from "../../package.json" with { type: "json" };
22import * as ServerConfig from "../config.ts";
23import { getTelemetryIdentifier } from "./Identify.ts";
24​
25interface BufferedAnalyticsEvent {
26 readonly event: string;
27 readonly properties?: Readonly<Record<string, unknown>>;
28 readonly capturedAt: string;
30​
31const TelemetryEnvConfig = Config.all({
32 posthogKey: Config.string("V12_POSTHOG_KEY").pipe(
33 Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"),
34 ),
35 posthogHost: Config.string("V12_POSTHOG_HOST").pipe(
36 Config.withDefault("https://us.i.posthog.com"),
37 ),
38 enabled: Config.boolean("V12_TELEMETRY_ENABLED").pipe(Config.withDefault(true)),
39 flushBatchSize: Config.number("V12_TELEMETRY_FLUSH_BATCH_SIZE").pipe(Config.withDefault(20)),
40 maxBufferedEvents: Config.number("V12_TELEMETRY_MAX_BUFFERED_EVENTS").pipe(
41 Config.withDefault(1_000),
42 ),
43 wslDistroName: Config.string("WSL_DISTRO_NAME").pipe(Config.option),
44});
45​
46export class AnalyticsService extends Context.Service<
47 AnalyticsService,
48 {
49 /** Record an anonymous event for best-effort buffered delivery. */
50 readonly record: (
51 event: string,
52 properties?: Readonly<Record<string, unknown>>,
53 ) => Effect.Effect<void>;
54​
55 /** Flush all currently queued telemetry events. */
56 readonly flush: Effect.Effect<void>;
57 }
58>()("v12/telemetry/AnalyticsService") {
59 /** No-op layer for callers that intentionally disable telemetry. */
60 static readonly layerTest = Layer.succeed(
61 AnalyticsService,
62 AnalyticsService.of({
63 record: () => Effect.void,
64 flush: Effect.void,
65 }),
66 );
68​
69export const make = Effect.gen(function* () {
70 const telemetryConfig = yield* TelemetryEnvConfig;
71 const httpClient = yield* HttpClient.HttpClient;
72 const serverConfig = yield* ServerConfig.ServerConfig;
73 const identifier = yield* getTelemetryIdentifier;
74 const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
75 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
76 const hostPlatform = yield* HostProcessPlatform;
77 const hostArchitecture = yield* HostProcessArchitecture;
78​
79 const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>
80 Effect.flatMap(DateTime.now, (now) =>
81 Ref.modify(bufferRef, (current) => {
82 const appended = [
83 ...current,
84 {
85 event,
86 ...(properties ? { properties } : {}),
87 capturedAt: DateTime.formatIso(now),
88 } satisfies BufferedAnalyticsEvent,
89 ];
90​
91 const next =
92 appended.length > telemetryConfig.maxBufferedEvents
93 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
94 : appended;
95​
96 return [
97 {
98 size: next.length,
99 dropped: next.length !== appended.length,
100 } as const,
101 next,
102 ] as const;
103 }),
104 );
105​
106 const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
107 events: ReadonlyArray<BufferedAnalyticsEvent>,
108 ) {
109 if (!telemetryConfig.enabled || !identifier) return;
110​
111 const payload = {
112 api_key: telemetryConfig.posthogKey,
113 batch: events.map((event) => ({
114 event: event.event,
115 distinct_id: identifier,
116 properties: {
117 ...event.properties,
118 $process_person_profile: false,
119 platform: hostPlatform,
120 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
121 arch: hostArchitecture,
122 v12CodeVersion: packageJson.version,
123 clientType,
124 },
125 timestamp: event.capturedAt,
126 })),
127 };
128​
129 yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
130 HttpClientRequest.bodyJson(payload),
131 Effect.flatMap(httpClient.execute),
132 Effect.flatMap(HttpClientResponse.filterStatusOk),
133 );
134 });
135​
136 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
137 while (true) {
138 const batch = yield* Ref.modify(bufferRef, (current) => {
139 if (current.length === 0) {
140 return [[] as ReadonlyArray<BufferedAnalyticsEvent>, current] as const;
141 }
142 const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
143 const remaining = current.slice(nextBatch.length);
144 return [nextBatch, remaining] as const;
145 });
146​
147 if (batch.length === 0) {
148 return;
149 }
150​
151 yield* sendBatch(batch).pipe(
152 Effect.catch((error) =>
153 Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
154 Effect.flatMap(() => Effect.fail(error)),
155 ),
156 ),
157 );
158 }
159 }).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
160​
161 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
162 function* (event, properties) {
163 if (!telemetryConfig.enabled || !identifier) return;
164​
165 const enqueueResult = yield* enqueueBufferedEvent(event, properties);
166 if (enqueueResult.dropped) {
167 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
168 size: enqueueResult.size,
169 event,
170 });
171 }
172 },
173 );
174​
175 yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
176 disableYield: true,
177 }).pipe(Effect.forkScoped);
178​
179 yield* Effect.addFinalizer(() => flush);
180​
181 return AnalyticsService.of({ record, flush });
182});
183​
184export const layer = Layer.effect(AnalyticsService, make);
185​
186export const layerTest = AnalyticsService.layerTest;