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