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