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

AnalyticsService.ts

208 lines7.0 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​
70function 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​
85/** @public Service construction is part of the canonical Effect module API. */
86export const make = Effect.gen(function* () {
87 const telemetryConfig = yield* TelemetryEnvConfig;
88 const httpClient = yield* HttpClient.HttpClient;
89 const serverConfig = yield* ServerConfig.ServerConfig;
90 const identifier = yield* getTelemetryIdentifier;
91 const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]);
92 const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client";
93 const hostPlatform = yield* HostProcessPlatform;
94 const hostArchitecture = yield* HostProcessArchitecture;
95​
96 const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) =>
97 Effect.flatMap(DateTime.now, (now) =>
98 Ref.modify(bufferRef, (current) => {
99 const appended = [
100 ...current,
101 {
102 event,
103 ...(properties ? { properties } : {}),
104 capturedAt: DateTime.formatIso(now),
105 } satisfies BufferedAnalyticsEvent,
106 ];
107​
108 const next =
109 appended.length > telemetryConfig.maxBufferedEvents
110 ? appended.slice(appended.length - telemetryConfig.maxBufferedEvents)
111 : appended;
112​
113 return [
114 {
115 size: next.length,
116 dropped: next.length !== appended.length,
117 } as const,
118 next,
119 ] as const;
120 }),
121 );
122​
123 const sendBatch = Effect.fn("AnalyticsService.sendBatch")(function* (
124 events: ReadonlyArray<BufferedAnalyticsEvent>,
125 ) {
126 if (!telemetryConfig.enabled || !identifier) return;
127​
128 const payload = {
129 api_key: telemetryConfig.posthogKey,
130 batch: events.map((event) => ({
131 event: event.event,
132 distinct_id: identifier,
133 properties: {
134 ...event.properties,
135 $process_person_profile: false,
136 platform: hostPlatform,
137 wsl: Option.getOrUndefined(telemetryConfig.wslDistroName),
138 arch: hostArchitecture,
139 t3CodeVersion: packageJson.version,
140 clientType,
141 serverOs: serverOsFromNodePlatform(hostPlatform),
142 serverArch: hostArchitecture,
143 serverWslDistro: Option.getOrUndefined(telemetryConfig.wslDistroName),
144 serverAppVersion: packageJson.version,
145 serverMode: serverConfig.mode,
146 },
147 timestamp: event.capturedAt,
148 })),
149 };
150​
151 yield* HttpClientRequest.post(`${telemetryConfig.posthogHost}/batch/`).pipe(
152 HttpClientRequest.bodyJson(payload),
153 Effect.flatMap(httpClient.execute),
154 Effect.flatMap(HttpClientResponse.filterStatusOk),
155 );
156 });
157​
158 const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () {
159 while (true) {
160 const batch = yield* Ref.modify(bufferRef, (current) => {
161 if (current.length === 0) {
162 return [[] as ReadonlyArray<BufferedAnalyticsEvent>, current] as const;
163 }
164 const nextBatch = current.slice(0, telemetryConfig.flushBatchSize);
165 const remaining = current.slice(nextBatch.length);
166 return [nextBatch, remaining] as const;
167 });
168​
169 if (batch.length === 0) {
170 return;
171 }
172​
173 yield* sendBatch(batch).pipe(
174 Effect.catch((error) =>
175 Ref.update(bufferRef, (current) => [...batch, ...current]).pipe(
176 Effect.flatMap(() => Effect.fail(error)),
177 ),
178 ),
179 );
180 }
181 }).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause })));
182​
183 const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")(
184 function* (event, properties) {
185 if (!telemetryConfig.enabled || !identifier) return;
186​
187 const enqueueResult = yield* enqueueBufferedEvent(event, properties);
188 if (enqueueResult.dropped) {
189 yield* Effect.logDebug("analytics buffer full; dropping oldest event", {
190 size: enqueueResult.size,
191 event,
192 });
193 }
194 },
195 );
196​
197 yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), {
198 disableYield: true,
199 }).pipe(Effect.forkScoped);
200​
201 yield* Effect.addFinalizer(() => flush);
202​
203 return AnalyticsService.of({ record, flush });
204});
205​
206export const layer = Layer.effect(AnalyticsService, make);
207​
208export const layerTest = AnalyticsService.layerTest;