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

AnalyticsService.test.ts

420 lines14.9 KB

1import * as NodeHttpServer from "@effect/platform-node/NodeHttpServer";
2import * as NodeCrypto from "@effect/platform-node/NodeCrypto";
3import * as NodeServices from "@effect/platform-node/NodeServices";
4import { assert, it } from "@effect/vitest";
5import * as Clock from "effect/Clock";
6import * as ConfigProvider from "effect/ConfigProvider";
7import * as Effect from "effect/Effect";
8import * as Layer from "effect/Layer";
9import * as Schema from "effect/Schema";
10import * as TestClock from "effect/testing/TestClock";
11import * as HttpClient from "effect/http/HttpClient";
12import * as HttpClientError from "effect/http/HttpClientError";
13import * as HttpClientRequest from "effect/http/HttpClientRequest";
14import * as HttpClientResponse from "effect/http/HttpClientResponse";
15import * as HttpServer from "effect/http/HttpServer";
16import * as HttpServerRequest from "effect/http/HttpServerRequest";
17import * as HttpServerResponse from "effect/http/HttpServerResponse";
18import * as HostProcess from "@t3tools/shared/HostProcess";
19​
20import type { ManagedPolicyDocument } from "@t3tools/contracts";
21​
22import * as ServerConfig from "../config.ts";
23import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
24import { getTelemetryIdentity } from "./Identify.ts";
25import * as AnalyticsService from "./AnalyticsService.ts";
26​
27interface RecordedBatchRequest {
28 readonly path: string;
29 readonly body: {
30 readonly batch?: ReadonlyArray<{
31 readonly event?: string;
32 readonly properties?: {
33 readonly index?: number;
34 readonly clientType?: string;
35 readonly serverOs?: string;
36 readonly serverArch?: string;
37 readonly serverAppVersion?: string;
38 readonly serverMode?: string;
39 readonly t3CodeVersion?: string;
40 };
41 }>;
42 } | null;
44​
45interface RecordedBatchBody {
46 readonly batch: ReadonlyArray<{
47 readonly event?: string;
48 readonly properties?: {
49 readonly index?: number;
50 readonly clientType?: string;
51 readonly serverOs?: string;
52 readonly serverArch?: string;
53 readonly serverAppVersion?: string;
54 readonly serverMode?: string;
55 readonly t3CodeVersion?: string;
56 };
57 }>;
59​
60const SentBatch = Schema.fromJsonString(
61 Schema.Struct({
62 batch: Schema.Array(
63 Schema.Struct({
64 uuid: Schema.String,
65 event: Schema.String,
66 distinct_id: Schema.String,
67 properties: Schema.Struct({
68 telemetryChannel: Schema.String,
69 installId: Schema.optionalKey(Schema.String),
70 ownerSource: Schema.optionalKey(Schema.String),
71 observedBy: Schema.optionalKey(Schema.String),
72 }),
73 }),
74 ),
75 }),
76);
77const decodeSentBatch = Schema.decodeEffect(SentBatch);
78type SentEvent = (typeof SentBatch.Type)["batch"][number];
79type Respond = (
80 request: HttpClientRequest.HttpClientRequest,
81) => Effect.Effect<HttpClientResponse.HttpClientResponse, HttpClientError.HttpClientError>;
82​
83const respondWithStatus =
84 (status: number): Respond =>
85 (request) =>
86 Effect.succeed(HttpClientResponse.fromWeb(request, new Response(null, { status })));
87​
88/**
89 * Answers 503 for `minutes` after the first send, then 204. `answers` holds each
90 * answer with its time in ms after the first send (the test clock runs on across tests).
91 */
92const failingFor = (minutes: number) => {
93 const answers: Array<{ readonly at: number; readonly status: number }> = [];
94 let firstSend: number | undefined;
95 const respond: Respond = (request) =>
96 Effect.flatMap(Clock.currentTimeMillis, (now) => {
97 firstSend ??= now;
98 const at = now - firstSend;
99 const status = at < minutes * 60_000 ? 503 : 204;
100 answers.push({ at, status });
101 return respondWithStatus(status)(request);
102 });
103 return { respond, answers };
104};
105​
106const recordTwentyEvents = Effect.gen(function* () {
107 const analytics = yield* AnalyticsService.AnalyticsService;
108 for (let index = 0; index < 20; index += 1) {
109 yield* analytics.record("test.retry", { index });
110 }
111});
112​
113/**
114 * Runs `record` (20 events by default), then lets `minutes` of background
115 * flushes run against a client that answers every send with `respond`.
116 * Returns the sent batches.
117 */
118const sendFor = (
119 minutes: number,
120 respond: Respond,
121 record: Effect.Effect<
122 void,
123 never,
124 AnalyticsService.AnalyticsService | Effect.Services<typeof getTelemetryIdentity>
125 > = recordTwentyEvents,
126 policy?: ManagedPolicyDocument,
127) =>
128 Effect.gen(function* () {
129 const batches: Array<ReadonlyArray<SentEvent>> = [];
130 const client = HttpClient.make((request) =>
131 Effect.gen(function* () {
132 if (request.body._tag === "Uint8Array") {
133 const body = yield* decodeSentBatch(new TextDecoder().decode(request.body.body)).pipe(
134 Effect.orDie,
135 );
136 batches.push(body.batch);
137 }
138 return yield* respond(request);
139 }),
140 );
141 const runtimeLayer = AnalyticsService.layer.pipe(
142 Layer.provideMerge(
143 ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-telemetry-retry-" }),
144 ),
145 Layer.provide(
146 ConfigProvider.layer(
147 ConfigProvider.fromUnknown({
148 T3CODE_TELEMETRY_ENABLED: true,
149 T3CODE_POSTHOG_KEY: "phc_test_key",
150 T3CODE_POSTHOG_HOST: "http://localhost",
151 }),
152 ),
153 ),
154 Layer.provide(
155 Layer.mergeAll(
156 Layer.succeed(HostProcess.Platform, "win32"),
157 Layer.succeed(HostProcess.Architecture, "x64"),
158 Layer.succeed(HttpClient.HttpClient, client),
159 ManagedPolicy.layerTest(policy),
160 ),
161 ),
162 );
163​
164 yield* Effect.gen(function* () {
165 yield* record;
166 for (let second = 0; second < minutes * 60; second += 1) {
167 yield* TestClock.adjust("1 second");
168 }
169 }).pipe(Effect.provide(runtimeLayer));
170 return batches;
171 });
172​
173it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("AnalyticsService test", (it) => {
174 it.effect("waits for desktop shell consent and honors a late telemetry opt-out", () =>
175 Effect.gen(function* () {
176 const env: NodeJS.ProcessEnv = { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" };
177 const batches = yield* sendFor(
178 0,
179 respondWithStatus(204),
180 Effect.gen(function* () {
181 const analytics = yield* AnalyticsService.AnalyticsService;
182 yield* analytics.record("test.before-discovery");
183 yield* analytics.flush;
184 env.T3CODE_TELEMETRY_ENABLED = "false";
185 delete env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING;
186 yield* analytics.record("test.opted-out");
187 yield* analytics.flush;
188 env.T3CODE_TELEMETRY_ENABLED = "true";
189 yield* analytics.record("test.allowed");
190 yield* analytics.flush;
191 }),
192 ).pipe(Effect.provideService(HostProcess.Environment, env));
193 assert.deepEqual(
194 batches.flat().map((event) => event.event),
195 ["test.allowed"],
196 );
197 }),
198 );
199​
200 it.effect("client owner reports cannot use up the server's owner cap", () =>
201 Effect.gen(function* () {
202 const batches = yield* sendFor(
203 10,
204 respondWithStatus(204),
205 Effect.gen(function* () {
206 const analytics = yield* AnalyticsService.AnalyticsService;
207 yield* analytics.recordOwners(
208 Array.from({ length: 1_001 }, (_, index) => ({
209 source: "device" as const,
210 ownerId: index.toString(16).padStart(64, "0"),
211 })),
212 "client",
213 );
214 // The event buffer also holds 1,000, so send the client events first.
215 yield* analytics.flush;
216 yield* analytics.recordOwners([{ source: "connect", ownerId: "a".repeat(64) }], "server");
217 }),
218 );
219 const owners = batches.flat().map((event) => event.properties.observedBy);
220​
221 assert.equal(owners.filter((observedBy) => observedBy === "client").length, 1_000);
222 assert.equal(owners.filter((observedBy) => observedBy === "server").length, 1);
223 }),
224 );
225​
226 it.effect("keeps a failed batch through a 20-minute outage and sends it once after", () =>
227 Effect.gen(function* () {
228 const ingest = failingFor(20);
229 const batches = yield* sendFor(40, ingest.respond);
230 const statuses = ingest.answers.map(({ status }) => status);
231 assert.equal(statuses.at(-1), 204);
232 assert.equal(statuses.filter((status) => status === 204).length, 1);
233 const sentUuids = new Set(batches.map((batch) => batch.map(({ uuid }) => uuid).join()));
234 assert.equal(sentUuids.size, 1);
235 assert.equal(batches[0]?.length, 20);
236 }),
237 );
238​
239 it.effect("drops a batch that keeps failing for 30 minutes", () =>
240 Effect.gen(function* () {
241 const ingest = failingFor(Infinity);
242 yield* sendFor(60, ingest.respond);
243 const lastSend = ingest.answers.at(-1)?.at ?? 0;
244 assert.isAtLeast(lastSend, 30 * 60_000);
245 assert.isBelow(lastSend, 36 * 60_000);
246 }),
247 );
248​
249 it.effect(
250 "sends nothing when a managed policy turns telemetry off, despite the environment",
251 () =>
252 Effect.gen(function* () {
253 const policy = { schemaVersion: 1, organization: "Example Corp" } as const;
254 const allowed = yield* sendFor(1, respondWithStatus(204), recordTwentyEvents, {
255 ...policy,
256 limits: { telemetry: true },
257 });
258 assert.equal(allowed.length, 1);
259 const denied = yield* sendFor(1, respondWithStatus(204), recordTwentyEvents, {
260 ...policy,
261 limits: { telemetry: false },
262 });
263 assert.deepEqual(denied, []);
264 }),
265 );
266​
267 it.effect("drops a batch the endpoint rejects without sending it again", () =>
268 Effect.gen(function* () {
269 const batches = yield* sendFor(10, respondWithStatus(400));
270 assert.equal(batches.length, 1);
271 }),
272 );
273​
274 it.effect("flush drains all buffered events across multiple batches", () =>
275 Effect.gen(function* () {
276 const capturedRequests: Array<RecordedBatchRequest> = [];
277 const layerServerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
278 prefix: "t3-telemetry-base-",
279 });
280​
281 const layerTelemetry = AnalyticsService.layer.pipe(Layer.provideMerge(layerServerConfig));
282 const layerConfig = ConfigProvider.layer(
283 ConfigProvider.fromUnknown({
284 T3CODE_TELEMETRY_ENABLED: true,
285 T3CODE_POSTHOG_KEY: "phc_test_key",
286 T3CODE_POSTHOG_HOST: "http://localhost",
287 T3CODE_TELEMETRY_FLUSH_BATCH_SIZE: 20,
288 }),
289 );
290 const layerBatchServer = HttpServer.serve(
291 Effect.gen(function* () {
292 const request = yield* HttpServerRequest.HttpServerRequest;
293 if (request.method !== "POST") {
294 return HttpServerResponse.empty({ status: 404 });
295 }
296​
297 const payload = yield* request.json.pipe(
298 Effect.map((body) => body as RecordedBatchRequest["body"]),
299 Effect.orElseSucceed(() => null),
300 );
301​
302 capturedRequests.push({ path: request.url, body: payload });
303​
304 return HttpServerResponse.jsonUnsafe({});
305 }),
306 );
307 const layerRuntime = layerTelemetry.pipe(
308 Layer.provide(layerConfig),
309 Layer.provide(
310 Layer.mergeAll(
311 Layer.succeed(HostProcess.Platform, "linux"),
312 Layer.succeed(HostProcess.Architecture, "arm64"),
313 ManagedPolicy.layerTest(),
314 ),
315 ),
316 Layer.provideMerge(NodeHttpServer.layerTest),
317 );
318​
319 yield* Effect.gen(function* () {
320 yield* Layer.launch(layerBatchServer).pipe(Effect.forkScoped);
321 const { distinctId } = yield* getTelemetryIdentity;
322 assert.equal(distinctId !== null, true);
323 const analytics = yield* AnalyticsService.AnalyticsService;
324​
325 for (let index = 0; index < 45; index += 1) {
326 yield* analytics.record("test.flush.drain", { index });
327 }
328​
329 yield* analytics.flush;
330 }).pipe(Effect.provide(layerRuntime));
331​
332 const batchRequests = capturedRequests.filter(
333 (request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
334 Array.isArray(request.body?.batch),
335 );
336 assert.equal(batchRequests.length, 3);
337 assert.equal(
338 batchRequests.every(
339 (request) => request.path.endsWith("/batch/") || request.path.endsWith("/batch"),
340 ),
341 true,
342 );
343 const deliveredIndexes = batchRequests.flatMap((request) =>
344 request.body.batch
345 .filter((event) => event.event === "test.flush.drain")
346 .map((event) => event.properties?.index)
347 .filter((index): index is number => typeof index === "number"),
348 );
349​
350 const sorted = deliveredIndexes.toSorted((a, b) => a - b);
351 assert.equal(sorted.length, 45);
352 assert.deepEqual(
353 sorted,
354 Array.from({ length: 45 }, (_, index) => index),
355 );
356 assert.equal(
357 batchRequests.every((request) =>
358 request.body.batch.every((event) => event.properties?.clientType === "cli-web-client"),
359 ),
360 true,
361 );
362 assert.equal(
363 batchRequests.every((request) =>
364 request.body.batch.every(
365 (event) =>
366 event.properties?.serverOs === "Linux" &&
367 event.properties.serverArch === "arm64" &&
368 event.properties.serverAppVersion === event.properties.t3CodeVersion &&
369 event.properties.serverMode === "web",
370 ),
371 ),
372 true,
373 );
374 }),
375 );
376​
377 it.effect("does not send batch requests when telemetry is disabled", () =>
378 Effect.gen(function* () {
379 const capturedPaths: Array<string> = [];
380 const layerServerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
381 prefix: "t3-telemetry-disabled-",
382 });
383 const layerTelemetry = AnalyticsService.layer.pipe(Layer.provideMerge(layerServerConfig));
384 const layerConfig = ConfigProvider.layer(
385 ConfigProvider.fromUnknown({
386 T3CODE_TELEMETRY_ENABLED: false,
387 T3CODE_POSTHOG_KEY: "phc_test_key",
388 T3CODE_POSTHOG_HOST: "http://localhost",
389 }),
390 );
391 const layerBatchServer = HttpServer.serve(
392 Effect.gen(function* () {
393 const request = yield* HttpServerRequest.HttpServerRequest;
394 capturedPaths.push(request.url);
395 return HttpServerResponse.jsonUnsafe({});
396 }),
397 );
398 const layerRuntime = layerTelemetry.pipe(
399 Layer.provide(layerConfig),
400 Layer.provide(
401 Layer.mergeAll(
402 Layer.succeed(HostProcess.Platform, "linux"),
403 Layer.succeed(HostProcess.Architecture, "arm64"),
404 ManagedPolicy.layerTest(),
405 ),
406 ),
407 Layer.provideMerge(NodeHttpServer.layerTest),
408 );
409​
410 yield* Effect.gen(function* () {
411 yield* Layer.launch(layerBatchServer).pipe(Effect.forkScoped);
412 const analytics = yield* AnalyticsService.AnalyticsService;
413 yield* analytics.record("test.disabled", { index: 1 });
414 yield* analytics.flush;
415 }).pipe(Effect.provide(layerRuntime));
416​
417 assert.deepEqual(capturedPaths, []);
418 }),
419 );
420});