Open History to see the last commit
1// @effect-diagnostics nodeBuiltinImport:off - launcher integration with filesystem and fetch.
2import * as NodeFS from "node:fs";
3import * as NodeOS from "node:os";
4import * as NodePath from "node:path";
5import { expect, it, vi } from "vite-plus/test";
6import { flushTelemetry, observeSummaries, summarize } from "./telemetry.ts";
7
8const task = (result: unknown) => ({
9 package_name: "@team/server",
10 task_name: "typecheck",
11 command: "SECRET",
12 cwd: "/private",
13 result,
14});
15
16it("counts only confirmed hits, preserves their tier, and never transmits command text", () => {
17 expect(
18 summarize({
19 tasks: [
20 task({ CacheHit: { source: "Remote", saved_duration_ms: 1200 } }),
21 task({ CacheHit: { source: "Local", saved_duration_ms: 500 } }),
22 task({ RestoreFailed: {} }),
23 task({ Spawned: {} }),
24 task({ CacheHit: { saved_duration_ms: 999 } }),
25 task({ CacheHit: { source: "Remote", saved_duration_ms: -1 } }),
26 ],
27 }),
28 ).toEqual([
29 { package: "@team/server", task: "typecheck", source: "remote", savedMs: 1200 },
30 { package: "@team/server", task: "typecheck", source: "local", savedMs: 500 },
31 { package: "@team/server", task: "typecheck", source: "failed", savedMs: 0 },
32 { package: "@team/server", task: "typecheck", source: "executed", savedMs: 0 },
33 { package: "@team/server", task: "typecheck", source: "unspecified", savedMs: 999 },
34 ]);
35});
36
37it("deduplicates shared summaries and retries delivery without credentials in queued records", async () => {
38 const root = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "cache-observer-"));
39 const home = NodePath.join(root, "home");
40 const endpoint = "https://cache.example/projects/t3code";
41 try {
42 const stopA = observeSummaries(root, endpoint, { T3_TASK_CACHE_HOST: "test-host" }, home);
43 const stopB = observeSummaries(root, endpoint, { T3_TASK_CACHE_HOST: "test-host" }, home);
44 const version = NodePath.join(root, "node_modules/.vite/task-cache/v18");
45 NodeFS.mkdirSync(version);
46 NodeFS.writeFileSync(
47 NodePath.join(version, "last-summary.json"),
48 JSON.stringify({
49 tasks: [task({ CacheHit: { source: "Remote", saved_duration_ms: 1200 } })],
50 }),
51 );
52 stopA();
53 stopB();
54 const queue = NodePath.join(home, ".cache/t3-task-cache/telemetry");
55 const files = NodeFS.readdirSync(queue);
56 expect(files).toHaveLength(1);
57 const serialized = NodeFS.readFileSync(NodePath.join(queue, files[0]!), "utf8");
58 expect(serialized).not.toContain("SECRET");
59 expect(JSON.parse(serialized).event.host).toBe("test-host");
60 NodeFS.mkdirSync(NodePath.join(home, ".config/t3-task-cache"), { recursive: true });
61 NodeFS.writeFileSync(
62 NodePath.join(home, ".config/t3-task-cache/credentials.json"),
63 JSON.stringify({ [endpoint]: { name: "alice", token: "secret-token" } }),
64 );
65 using request = vi
66 .spyOn(globalThis, "fetch")
67 .mockResolvedValueOnce(new Response(null, { status: 503 }))
68 .mockImplementationOnce(async () => {
69 const late = JSON.parse(serialized);
70 late.event.id = "b".repeat(64);
71 NodeFS.writeFileSync(NodePath.join(queue, "late.json"), JSON.stringify(late));
72 return new Response(null, { status: 204 });
73 })
74 .mockResolvedValue(new Response(null, { status: 204 }));
75 await flushTelemetry(home, {});
76 expect(NodeFS.readdirSync(queue)).toEqual(files);
77 await flushTelemetry(home, {});
78 expect(NodeFS.readdirSync(queue)).toEqual([]);
79 expect(request).toHaveBeenCalledTimes(3);
80 expect(request.mock.calls[0]![0].toString()).toBe(`${endpoint}/telemetry`);
81 } finally {
82 NodeFS.rmSync(root, { recursive: true, force: true });
83 }
84});
85
86it("skips unauthenticated endpoints without consuming the delivery budget", async () => {
87 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "cache-queue-"));
88 const endpoint = "https://cache.example/projects/t3code";
89 try {
90 const queue = NodePath.join(home, ".cache/t3-task-cache/telemetry");
91 NodeFS.mkdirSync(queue, { recursive: true });
92 const skipped = Array.from({ length: 101 }, (_, i) => `a${i}.json`);
93 for (const file of skipped)
94 NodeFS.writeFileSync(
95 NodePath.join(queue, file),
96 JSON.stringify({ endpoint: "https://old.example/projects/t3code", event: { id: file } }),
97 );
98 NodeFS.writeFileSync(
99 NodePath.join(queue, "b.json"),
100 JSON.stringify({ endpoint, event: { id: "current" } }),
101 );
102 NodeFS.mkdirSync(NodePath.join(home, ".config/t3-task-cache"), { recursive: true });
103 NodeFS.writeFileSync(
104 NodePath.join(home, ".config/t3-task-cache/credentials.json"),
105 JSON.stringify({ [endpoint]: { name: "alice", token: "secret-token" } }),
106 );
107 using request = vi
108 .spyOn(globalThis, "fetch")
109 .mockResolvedValue(new Response(null, { status: 204 }));
110 await flushTelemetry(home, {});
111 expect(NodeFS.readdirSync(queue).sort()).toEqual(skipped.sort());
112 expect(request).toHaveBeenCalledOnce();
113 expect(request.mock.calls[0]![0].toString()).toBe(`${endpoint}/telemetry`);
114 } finally {
115 NodeFS.rmSync(home, { recursive: true, force: true });
116 }
117});
118
119it("excludes tasks that explicitly disable caching from the hit-rate denominator", () => {
120 expect(
121 summarize({
122 tasks: [
123 task({ Spawned: { cache_status: "Disabled" } }),
124 task({ Spawned: { cache_status: { Miss: "changed" } } }),
125 ],
126 }),
127 ).toEqual([{ package: "@team/server", task: "typecheck", source: "executed", savedMs: 0 }]);
128});
129
130it("drops revoked credentials and continues delivering other queued endpoints", async () => {
131 const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "cache-revoked-"));
132 try {
133 const queue = NodePath.join(home, ".cache/t3-task-cache/telemetry");
134 const state = NodePath.join(home, ".config/t3-task-cache");
135 NodeFS.mkdirSync(queue, { recursive: true });
136 NodeFS.mkdirSync(state, { recursive: true });
137 NodeFS.writeFileSync(
138 NodePath.join(state, "credentials.json"),
139 JSON.stringify({
140 "https://revoked.example": { name: "a", token: "old" },
141 "https://current.example": { name: "a", token: "new" },
142 }),
143 );
144 for (const [file, endpoint] of [
145 ["a.json", "https://revoked.example"],
146 ["b.json", "https://current.example"],
147 ])
148 NodeFS.writeFileSync(
149 NodePath.join(queue, file!),
150 JSON.stringify({ endpoint, event: { id: file } }),
151 );
152 using request = vi
153 .spyOn(globalThis, "fetch")
154 .mockResolvedValueOnce(new Response(null, { status: 403 }))
155 .mockResolvedValueOnce(new Response(null, { status: 204 }));
156 await flushTelemetry(home, {});
157 expect(request).toHaveBeenCalledTimes(2);
158 expect(NodeFS.readdirSync(queue)).toEqual([]);
159 } finally {
160 NodeFS.rmSync(home, { recursive: true, force: true });
161 }
162});