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