|
2 | 2 | * Anonymous PostHog telemetry service. |
3 | 3 | * |
4 | 4 | * Persists an installation-scoped anonymous identifier, buffers events in |
5 | | - * memory, and flushes batches over Effect's HTTP client. |
| 5 | + * memory, and flushes batches over Effect's HTTP client. A failed batch is |
| 6 | + * retried with backoff and dropped after a few tries. Each event carries a |
| 7 | + * uuid, so PostHog can tell a retried copy from a new event. |
6 | 8 | * |
7 | 9 | * @module AnalyticsService |
8 | 10 | */ |
9 | 11 | import { HostProcessArchitecture, HostProcessPlatform } from "@t3tools/shared/hostProcess"; |
10 | 12 | import type { ClientOs } from "@t3tools/contracts"; |
| 13 | +import * as Clock from "effect/Clock"; |
11 | 14 | import * as Config from "effect/Config"; |
12 | 15 | import * as Context from "effect/Context"; |
| 16 | +import * as Crypto from "effect/Crypto"; |
13 | 17 | import * as DateTime from "effect/DateTime"; |
14 | 18 | import * as Effect from "effect/Effect"; |
| 19 | +import * as Exit from "effect/Exit"; |
15 | 20 | import * as Layer from "effect/Layer"; |
16 | 21 | import * as Option from "effect/Option"; |
| 22 | +import * as Random from "effect/Random"; |
17 | 23 | import * as Ref from "effect/Ref"; |
| 24 | +import * as Result from "effect/Result"; |
| 25 | +import * as Semaphore from "effect/Semaphore"; |
18 | 26 | import * as HttpClient from "effect/unstable/http/HttpClient"; |
19 | 27 | import * as HttpClientRequest from "effect/unstable/http/HttpClientRequest"; |
20 | 28 | import * as HttpClientResponse from "effect/unstable/http/HttpClientResponse"; |
@@ -24,11 +32,40 @@ import * as ServerConfig from "../config.ts"; |
24 | 32 | import { getTelemetryIdentifier } from "./Identify.ts"; |
25 | 33 |
|
26 | 34 | interface BufferedAnalyticsEvent { |
| 35 | + readonly uuid: string; |
27 | 36 | readonly event: string; |
28 | 37 | readonly properties?: Readonly<Record<string, unknown>>; |
29 | 38 | readonly capturedAt: string; |
30 | 39 | } |
31 | 40 |
|
| 41 | +interface DeliveryState { |
| 42 | + /** Batch that failed last. It is sent again before newer events. */ |
| 43 | + readonly failedBatch: ReadonlyArray<BufferedAnalyticsEvent>; |
| 44 | + /** Failed sends of `failedBatch`. */ |
| 45 | + readonly batchAttempts: number; |
| 46 | + /** Failed sends since the last success. Sets the backoff delay. */ |
| 47 | + readonly failures: number; |
| 48 | + /** The background flush does not send before this time (epoch ms). */ |
| 49 | + readonly retryAt: number; |
| 50 | +} |
| 51 | + |
| 52 | +const FLUSH_INTERVAL_MS = 1_000; |
| 53 | +// A hung send would hold the flush lock, and with it the shutdown flush. |
| 54 | +const SEND_TIMEOUT = "10 seconds"; |
| 55 | +const MAX_BATCH_ATTEMPTS = 5; |
| 56 | +const RETRY_BASE_DELAY_MS = 2_000; |
| 57 | +const RETRY_MAX_DELAY_MS = 300_000; |
| 58 | + |
| 59 | +/** |
| 60 | + * Delay before the next send after `failures` consecutive failed sends. The |
| 61 | + * ceiling doubles from 2s up to 5 minutes, and the delay is a random point in |
| 62 | + * its upper half. `random` is in [0, 1). |
| 63 | + */ |
| 64 | +export function retryDelayMs(failures: number, random: number): number { |
| 65 | + const ceiling = Math.min(RETRY_MAX_DELAY_MS, RETRY_BASE_DELAY_MS * 2 ** (failures - 1)); |
| 66 | + return Math.round(ceiling / 2 + (ceiling / 2) * random); |
| 67 | +} |
| 68 | + |
32 | 69 | const TelemetryEnvConfig = Config.all({ |
33 | 70 | posthogKey: Config.String("T3CODE_POSTHOG_KEY").pipe( |
34 | 71 | Config.withDefault("phc_XOWci4oZP4VvLiEyrFqkFjP4CZn55mjYYBMREK5Wd6m"), |
@@ -88,17 +125,31 @@ export const make = Effect.gen(function* () { |
88 | 125 | const httpClient = yield* HttpClient.HttpClient; |
89 | 126 | const serverConfig = yield* ServerConfig.ServerConfig; |
90 | 127 | const identifier = yield* getTelemetryIdentifier; |
| 128 | + const crypto = yield* Crypto.Crypto; |
91 | 129 | const bufferRef = yield* Ref.make<ReadonlyArray<BufferedAnalyticsEvent>>([]); |
| 130 | + const deliveryRef = yield* Ref.make<DeliveryState>({ |
| 131 | + failedBatch: [], |
| 132 | + batchAttempts: 0, |
| 133 | + failures: 0, |
| 134 | + retryAt: 0, |
| 135 | + }); |
| 136 | + // The background flush and the shutdown flush must not send the same batch at once. |
| 137 | + const flushLock = yield* Semaphore.make(1); |
92 | 138 | const clientType = serverConfig.mode === "desktop" ? "desktop-app" : "cli-web-client"; |
93 | 139 | const hostPlatform = yield* HostProcessPlatform; |
94 | 140 | const hostArchitecture = yield* HostProcessArchitecture; |
95 | 141 |
|
96 | | - const enqueueBufferedEvent = (event: string, properties?: Readonly<Record<string, unknown>>) => |
| 142 | + const enqueueBufferedEvent = ( |
| 143 | + uuid: string, |
| 144 | + event: string, |
| 145 | + properties?: Readonly<Record<string, unknown>>, |
| 146 | + ) => |
97 | 147 | Effect.flatMap(DateTime.now, (now) => |
98 | 148 | Ref.modify(bufferRef, (current) => { |
99 | 149 | const appended = [ |
100 | 150 | ...current, |
101 | 151 | { |
| 152 | + uuid, |
102 | 153 | event, |
103 | 154 | ...(properties ? { properties } : {}), |
104 | 155 | capturedAt: DateTime.formatIso(now), |
@@ -128,6 +179,7 @@ export const make = Effect.gen(function* () { |
128 | 179 | const payload = { |
129 | 180 | api_key: telemetryConfig.posthogKey, |
130 | 181 | batch: events.map((event) => ({ |
| 182 | + uuid: event.uuid, |
131 | 183 | event: event.event, |
132 | 184 | distinct_id: identifier, |
133 | 185 | properties: { |
@@ -152,39 +204,69 @@ export const make = Effect.gen(function* () { |
152 | 204 | HttpClientRequest.bodyJson(payload), |
153 | 205 | Effect.flatMap(httpClient.execute), |
154 | 206 | Effect.flatMap(HttpClientResponse.filterStatusOk), |
| 207 | + Effect.timeout(SEND_TIMEOUT), |
155 | 208 | ); |
156 | 209 | }); |
157 | 210 |
|
| 211 | + const takeBatch = Ref.modify(bufferRef, (current) => { |
| 212 | + const nextBatch = current.slice(0, telemetryConfig.flushBatchSize); |
| 213 | + return [nextBatch, current.slice(nextBatch.length)] as const; |
| 214 | + }); |
| 215 | + |
| 216 | + // Sends batches until the buffer is empty or a send fails. A failed batch is |
| 217 | + // kept for the next flush, and dropped after MAX_BATCH_ATTEMPTS failed sends. |
158 | 218 | const flush: AnalyticsService["Service"]["flush"] = Effect.gen(function* () { |
159 | 219 | 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 | | - |
| 220 | + const delivery = yield* Ref.get(deliveryRef); |
| 221 | + const batch = delivery.failedBatch.length > 0 ? delivery.failedBatch : yield* takeBatch; |
169 | 222 | if (batch.length === 0) { |
170 | 223 | return; |
171 | 224 | } |
172 | 225 |
|
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 | | - ); |
| 226 | + const sent = yield* Effect.result(sendBatch(batch)); |
| 227 | + if (Result.isSuccess(sent)) { |
| 228 | + yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures: 0, retryAt: 0 }); |
| 229 | + continue; |
| 230 | + } |
| 231 | + |
| 232 | + const failures = delivery.failures + 1; |
| 233 | + const batchAttempts = delivery.batchAttempts + 1; |
| 234 | + const retryAt = (yield* Clock.currentTimeMillis) + retryDelayMs(failures, yield* Random.next); |
| 235 | + if (batchAttempts < MAX_BATCH_ATTEMPTS) { |
| 236 | + yield* Ref.set(deliveryRef, { failedBatch: batch, batchAttempts, failures, retryAt }); |
| 237 | + yield* Effect.logDebug("Failed to send telemetry batch; will retry", { |
| 238 | + attempt: batchAttempts, |
| 239 | + cause: sent.failure, |
| 240 | + }); |
| 241 | + return; |
| 242 | + } |
| 243 | + yield* Ref.set(deliveryRef, { failedBatch: [], batchAttempts: 0, failures, retryAt }); |
| 244 | + yield* Effect.logWarning("Dropped telemetry batch after repeated send failures", { |
| 245 | + events: batch.length, |
| 246 | + attempts: batchAttempts, |
| 247 | + cause: sent.failure, |
| 248 | + }); |
| 249 | + return; |
180 | 250 | } |
181 | | - }).pipe(Effect.catch((cause) => Effect.logError("Failed to flush telemetry", { cause }))); |
| 251 | + }).pipe(flushLock.withPermit); |
| 252 | + |
| 253 | + const flushWhenDue = Effect.gen(function* () { |
| 254 | + const { retryAt } = yield* Ref.get(deliveryRef); |
| 255 | + if ((yield* Clock.currentTimeMillis) >= retryAt) { |
| 256 | + yield* flush; |
| 257 | + } |
| 258 | + }); |
182 | 259 |
|
183 | 260 | const record: AnalyticsService["Service"]["record"] = Effect.fn("AnalyticsService.record")( |
184 | 261 | function* (event, properties) { |
185 | 262 | if (!telemetryConfig.enabled || !identifier) return; |
186 | 263 |
|
187 | | - const enqueueResult = yield* enqueueBufferedEvent(event, properties); |
| 264 | + // Telemetry is best effort: an event without a uuid is not sent. The |
| 265 | + // Node implementation throws (a defect) rather than failing, so catch both. |
| 266 | + const uuid = yield* Effect.exit(crypto.randomUUIDv7); |
| 267 | + if (Exit.isFailure(uuid)) return; |
| 268 | + |
| 269 | + const enqueueResult = yield* enqueueBufferedEvent(uuid.value, event, properties); |
188 | 270 | if (enqueueResult.dropped) { |
189 | 271 | yield* Effect.logDebug("analytics buffer full; dropping oldest event", { |
190 | 272 | size: enqueueResult.size, |
@@ -194,7 +276,7 @@ export const make = Effect.gen(function* () { |
194 | 276 | }, |
195 | 277 | ); |
196 | 278 |
|
197 | | - yield* Effect.forever(Effect.sleep(1000).pipe(Effect.flatMap(() => flush)), { |
| 279 | + yield* Effect.forever(Effect.sleep(FLUSH_INTERVAL_MS).pipe(Effect.flatMap(() => flushWhenDue)), { |
198 | 280 | disableYield: true, |
199 | 281 | }).pipe(Effect.forkScoped); |
200 | 282 |
|
|