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

AnalyticsService.test.ts

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