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

AnalyticsService.ts

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