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 };
44 }>;
45 } | null;
46}
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 }>;
61}
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 = (client: HttpClient.HttpClient, policy?: ManagedPolicyDocument) =>
118 AnalyticsService.layer.pipe(
119 Layer.provideMerge(
120 ServerConfig.ServerConfig.layerTest(process.cwd(), { prefix: "t3-telemetry-retry-" }),
121 ),
122 Layer.provide(
123 ConfigProvider.layer(
124 ConfigProvider.fromUnknown({
125 T3CODE_TELEMETRY_ENABLED: true,
126 T3CODE_POSTHOG_KEY: "phc_test_key",
127 T3CODE_POSTHOG_HOST: "http://localhost",
128 }),
129 ),
130 ),
131 Layer.provide(
132 Layer.mergeAll(
133 Layer.succeed(HostProcess.Platform, "win32"),
134 Layer.succeed(HostProcess.Architecture, "x64"),
135 Layer.succeed(HttpClient.HttpClient, client),
136 ManagedPolicy.layerTest(policy),
137 ),
138 ),
139 );
140
141/**
142 * Runs `record` (20 events by default), then lets `minutes` of background
143 * flushes run against a client that answers every send with `respond`.
144 * Returns the sent batches.
145 */
146const sendFor = (
147 minutes: number,
148 respond: Respond,
149 record: Effect.Effect<
150 void,
151 never,
152 AnalyticsService.AnalyticsService | Effect.Services<typeof getTelemetryIdentity>
153 > = recordTwentyEvents,
154 policy?: ManagedPolicyDocument,
155) =>
156 Effect.gen(function* () {
157 const batches: Array<ReadonlyArray<SentEvent>> = [];
158 const client = HttpClient.make((request) =>
159 Effect.gen(function* () {
160 if (request.body._tag === "Uint8Array") {
161 const body = yield* decodeSentBatch(new TextDecoder().decode(request.body.body)).pipe(
162 Effect.orDie,
163 );
164 batches.push(body.batch);
165 }
166 return yield* respond(request);
167 }),
168 );
169 const runtimeLayer = analyticsLayerWith(client, policy);
170
171 yield* Effect.gen(function* () {
172 yield* record;
173 for (let second = 0; second < minutes * 60; second += 1) {
174 yield* TestClock.adjust("1 second");
175 }
176 }).pipe(Effect.provide(runtimeLayer));
177 return batches;
178 });
179
180it.layer(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))("AnalyticsService test", (it) => {
181 it.effect("waits for desktop shell consent and honors a late telemetry opt-out", () =>
182 Effect.gen(function* () {
183 const env: NodeJS.ProcessEnv = { T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING: "1" };
184 const batches = yield* sendFor(
185 0,
186 respondWithStatus(204),
187 Effect.gen(function* () {
188 const analytics = yield* AnalyticsService.AnalyticsService;
189 yield* analytics.record("test.before-discovery");
190 yield* analytics.flush;
191 env.T3CODE_TELEMETRY_ENABLED = "false";
192 delete env.T3CODE_DESKTOP_SHELL_DISCOVERY_PENDING;
193 yield* analytics.record("test.opted-out");
194 yield* analytics.flush;
195 env.T3CODE_TELEMETRY_ENABLED = "true";
196 yield* analytics.record("test.allowed");
197 yield* analytics.flush;
198 }),
199 ).pipe(Effect.provideService(HostProcess.Environment, env));
200 assert.deepEqual(
201 batches.flat().map((event) => event.event),
202 ["test.allowed"],
203 );
204 }),
205 );
206
207 it.effect("sends an anonymous event under its own id and without the install id", () =>
208 Effect.gen(function* () {
209 const batches = yield* sendFor(
210 0,
211 respondWithStatus(204),
212 Effect.gen(function* () {
213 const analytics = yield* AnalyticsService.AnalyticsService;
214 yield* analytics.record("test.linked");
215 yield* analytics.record("test.anonymous", {}, { anonymous: true });
216 yield* analytics.flush;
217 }),
218 );
219 assert.equal(batches.length, 2);
220 const [linked, anonymous] = batches.map(([event]) => event);
221
222 assert.isDefined(linked?.properties.installId);
223 assert.isDefined(linked?.properties.serverOs);
224 assert.equal(anonymous?.distinct_id, anonymous?.uuid);
225 assert.notEqual(anonymous?.distinct_id, linked?.distinct_id);
226 assert.isUndefined(anonymous?.properties.installId);
227 assert.isUndefined(anonymous?.properties.serverOs);
228 }),
229 );
230
231 it.effect("client owner reports cannot use up the server's owner cap", () =>
232 Effect.gen(function* () {
233 const batches = yield* sendFor(
234 10,
235 respondWithStatus(204),
236 Effect.gen(function* () {
237 const analytics = yield* AnalyticsService.AnalyticsService;
238 yield* analytics.recordOwners(
239 Array.from({ length: 1_001 }, (_, index) => ({
240 source: "device" as const,
241 ownerId: index.toString(16).padStart(64, "0"),
242 })),
243 "client",
244 );
245 // The event buffer also holds 1,000, so send the client events first.
246 yield* analytics.flush;
247 yield* analytics.recordOwners([{ source: "connect", ownerId: "a".repeat(64) }], "server");
248 }),
249 );
250 const owners = batches.flat().map((event) => event.properties.observedBy);
251
252 assert.equal(owners.filter((observedBy) => observedBy === "client").length, 1_000);
253 assert.equal(owners.filter((observedBy) => observedBy === "server").length, 1);
254 }),
255 );
256
257 it.effect("keeps a failed batch through a 20-minute outage and sends it once after", () =>
258 Effect.gen(function* () {
259 const ingest = failingFor(20);
260 const batches = yield* sendFor(40, ingest.respond);
261 const statuses = ingest.answers.map(({ status }) => status);
262 assert.equal(statuses.at(-1), 204);
263 assert.equal(statuses.filter((status) => status === 204).length, 1);
264 const sentUuids = new Set(batches.map((batch) => batch.map(({ uuid }) => uuid).join()));
265 assert.equal(sentUuids.size, 1);
266 assert.equal(batches[0]?.length, 20);
267 }),
268 );
269
270 it.effect("drops a batch that keeps failing for 30 minutes", () =>
271 Effect.gen(function* () {
272 const ingest = failingFor(Infinity);
273 yield* sendFor(60, ingest.respond);
274 const lastSend = ingest.answers.at(-1)?.at ?? 0;
275 assert.isAtLeast(lastSend, 30 * 60_000);
276 assert.isBelow(lastSend, 36 * 60_000);
277 }),
278 );
279
280 it.effect(
281 "sends nothing when a managed policy turns telemetry off, despite the environment",
282 () =>
283 Effect.gen(function* () {
284 const policy = { schemaVersion: 1, organization: "Example Corp" } as const;
285 const allowed = yield* sendFor(1, respondWithStatus(204), recordTwentyEvents, {
286 ...policy,
287 limits: { telemetry: true },
288 });
289 assert.equal(allowed.length, 1);
290 const denied = yield* sendFor(1, respondWithStatus(204), recordTwentyEvents, {
291 ...policy,
292 limits: { telemetry: false },
293 });
294 assert.deepEqual(denied, []);
295 }),
296 );
297
298 it.effect("drops a batch the endpoint rejects without sending it again", () =>
299 Effect.gen(function* () {
300 const batches = yield* sendFor(10, respondWithStatus(400));
301 assert.equal(batches.length, 1);
302 }),
303 );
304
305 it.effect("shutdown stops waiting for a telemetry endpoint that never answers", () =>
306 Effect.gen(function* () {
307 const scope = yield* Scope.make();
308 const context = yield* Layer.buildWithScope(
309 analyticsLayerWith(HttpClient.make(() => Effect.never)),
310 scope,
311 );
312 yield* recordTwentyEvents.pipe(Effect.provide(context));
313
314 const shutdown = yield* Scope.close(scope, Exit.void).pipe(Effect.forkChild);
315 yield* TestClock.adjust("1 second");
316 yield* Fiber.join(shutdown);
317 }),
318 );
319
320 it.effect("flush drains all buffered events across multiple batches", () =>
321 Effect.gen(function* () {
322 const capturedRequests: Array<RecordedBatchRequest> = [];
323 const layerServerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
324 prefix: "t3-telemetry-base-",
325 });
326
327 const layerTelemetry = AnalyticsService.layer.pipe(Layer.provideMerge(layerServerConfig));
328 const layerConfig = ConfigProvider.layer(
329 ConfigProvider.fromUnknown({
330 T3CODE_TELEMETRY_ENABLED: true,
331 T3CODE_POSTHOG_KEY: "phc_test_key",
332 T3CODE_POSTHOG_HOST: "http://localhost",
333 T3CODE_TELEMETRY_FLUSH_BATCH_SIZE: 20,
334 }),
335 );
336 const layerBatchServer = HttpServer.serve(
337 Effect.gen(function* () {
338 const request = yield* HttpServerRequest.HttpServerRequest;
339 if (request.method !== "POST") {
340 return HttpServerResponse.empty({ status: 404 });
341 }
342
343 const payload = yield* request.json.pipe(
344 Effect.map((body) => body as RecordedBatchRequest["body"]),
345 Effect.orElseSucceed(() => null),
346 );
347
348 capturedRequests.push({ path: request.url, body: payload });
349
350 return HttpServerResponse.jsonUnsafe({});
351 }),
352 );
353 const layerRuntime = layerTelemetry.pipe(
354 Layer.provide(layerConfig),
355 Layer.provide(
356 Layer.mergeAll(
357 Layer.succeed(HostProcess.Platform, "linux"),
358 Layer.succeed(HostProcess.Architecture, "arm64"),
359 ManagedPolicy.layerTest(),
360 ),
361 ),
362 Layer.provideMerge(NodeHttpServer.layerTest),
363 );
364
365 yield* Effect.gen(function* () {
366 yield* Layer.launch(layerBatchServer).pipe(Effect.forkScoped);
367 const { distinctId } = yield* getTelemetryIdentity;
368 assert.equal(distinctId !== null, true);
369 const analytics = yield* AnalyticsService.AnalyticsService;
370
371 for (let index = 0; index < 45; index += 1) {
372 yield* analytics.record("test.flush.drain", { index });
373 }
374
375 yield* analytics.flush;
376 }).pipe(Effect.provide(layerRuntime));
377
378 const batchRequests = capturedRequests.filter(
379 (request): request is RecordedBatchRequest & { readonly body: RecordedBatchBody } =>
380 Array.isArray(request.body?.batch),
381 );
382 assert.equal(batchRequests.length, 3);
383 assert.equal(
384 batchRequests.every(
385 (request) => request.path.endsWith("/batch/") || request.path.endsWith("/batch"),
386 ),
387 true,
388 );
389 const deliveredIndexes = batchRequests.flatMap((request) =>
390 request.body.batch
391 .filter((event) => event.event === "test.flush.drain")
392 .map((event) => event.properties?.index)
393 .filter((index): index is number => typeof index === "number"),
394 );
395
396 const sorted = deliveredIndexes.toSorted((a, b) => a - b);
397 assert.equal(sorted.length, 45);
398 assert.deepEqual(
399 sorted,
400 Array.from({ length: 45 }, (_, index) => index),
401 );
402 assert.equal(
403 batchRequests.every((request) =>
404 request.body.batch.every((event) => event.properties?.clientType === "cli-web-client"),
405 ),
406 true,
407 );
408 assert.equal(
409 batchRequests.every((request) =>
410 request.body.batch.every(
411 (event) =>
412 event.properties?.serverOs === "Linux" &&
413 event.properties.serverArch === "arm64" &&
414 event.properties.serverAppVersion === event.properties.t3CodeVersion &&
415 event.properties.serverMode === "web",
416 ),
417 ),
418 true,
419 );
420 }),
421 );
422
423 it.effect("does not send batch requests when telemetry is disabled", () =>
424 Effect.gen(function* () {
425 const capturedPaths: Array<string> = [];
426 const layerServerConfig = ServerConfig.ServerConfig.layerTest(process.cwd(), {
427 prefix: "t3-telemetry-disabled-",
428 });
429 const layerTelemetry = AnalyticsService.layer.pipe(Layer.provideMerge(layerServerConfig));
430 const layerConfig = ConfigProvider.layer(
431 ConfigProvider.fromUnknown({
432 T3CODE_TELEMETRY_ENABLED: false,
433 T3CODE_POSTHOG_KEY: "phc_test_key",
434 T3CODE_POSTHOG_HOST: "http://localhost",
435 }),
436 );
437 const layerBatchServer = HttpServer.serve(
438 Effect.gen(function* () {
439 const request = yield* HttpServerRequest.HttpServerRequest;
440 capturedPaths.push(request.url);
441 return HttpServerResponse.jsonUnsafe({});
442 }),
443 );
444 const layerRuntime = layerTelemetry.pipe(
445 Layer.provide(layerConfig),
446 Layer.provide(
447 Layer.mergeAll(
448 Layer.succeed(HostProcess.Platform, "linux"),
449 Layer.succeed(HostProcess.Architecture, "arm64"),
450 ManagedPolicy.layerTest(),
451 ),
452 ),
453 Layer.provideMerge(NodeHttpServer.layerTest),
454 );
455
456 yield* Effect.gen(function* () {
457 yield* Layer.launch(layerBatchServer).pipe(Effect.forkScoped);
458 const analytics = yield* AnalyticsService.AnalyticsService;
459 yield* analytics.record("test.disabled", { index: 1 });
460 yield* analytics.flush;
461 }).pipe(Effect.provide(layerRuntime));
462
463 assert.deepEqual(capturedPaths, []);
464 }),
465 );
466});