TypeScript
fix(infra): task-cache telemetry no longer strands an event queued during a flush (#25653)
Julius Marmingee2d3ded436f7
diff --git a/infra/task-cache/src/runHook.test.ts b/infra/task-cache/src/runHook.test.tsindex 727890ec2e8..175092bd36a 100644--- a/infra/task-cache/src/runHook.test.ts+++ b/infra/task-cache/src/runHook.test.ts@@ -162,7 +162,7 @@ it("uses one machine hook across fresh worktrees without modifying Vite+", asyncexpect(await run("build", secondWorktree)).toBe(0);await report(4);expect(await run("build", secondWorktree, true)).toBe(0);- expect(completedReports).toBe(5);+ await report(5);expect(await NodeFSP.readFile(entrypoint, "utf8")).toBe(originalEntrypoint);expect(await run("nested", root, false, "--no-cache")).toBe(0);expect(await run("build", nested)).toBe(0);diff --git a/infra/task-cache/src/telemetry.test.ts b/infra/task-cache/src/telemetry.test.tsindex 024aed74bed..612b0194b53 100644--- a/infra/task-cache/src/telemetry.test.ts+++ b/infra/task-cache/src/telemetry.test.ts@@ -5,6 +5,11 @@ import * as NodePath from "node:path";import { expect, it, vi } from "vite-plus/test";import { flushTelemetry, observeSummaries, summarize } from "./telemetry.ts";+vi.mock("node:fs", async (importOriginal) => {+ const fs = await importOriginal<typeof import("node:fs")>();+ return { ...fs, rmdirSync: vi.fn(fs.rmdirSync) };+});+const task = (result: unknown) => ({package_name: "@team/server",task_name: "typecheck",@@ -160,3 +165,40 @@ it("drops revoked credentials and continues delivering other queued endpoints",NodeFS.rmSync(home, { recursive: true, force: true });}});++it("delivers an event queued while the previous flusher releases its lock", async () => {+ const home = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "cache-handoff-"));+ const endpoint = "https://cache.example/projects/t3code";+ try {+ const queue = NodePath.join(home, ".cache/t3-task-cache/telemetry");+ const state = NodePath.join(home, ".config/t3-task-cache");+ NodeFS.mkdirSync(queue, { recursive: true });+ NodeFS.mkdirSync(state, { recursive: true });+ NodeFS.writeFileSync(+ NodePath.join(state, "credentials.json"),+ JSON.stringify({ [endpoint]: { name: "alice", token: "secret-token" } }),+ );+ using request = vi+ .spyOn(globalThis, "fetch")+ .mockImplementation(async () => new Response(null, { status: 204 }));+ const rmdirSync = vi.mocked(NodeFS.rmdirSync);+ const release = rmdirSync.getMockImplementation()!;+ let competing: Promise<void> | undefined;+ // The next command queues its event after this flusher's last scan, and its own flusher+ // gives up because the lock is still held.+ rmdirSync.mockImplementationOnce((path, options) => {+ NodeFS.writeFileSync(+ NodePath.join(queue, "late.json"),+ JSON.stringify({ endpoint, event: { id: "late" } }),+ );+ competing = flushTelemetry(home, {});+ release(path, options);+ });+ await flushTelemetry(home, {});+ await competing;+ expect(request).toHaveBeenCalledOnce();+ expect(NodeFS.readdirSync(queue)).toEqual([]);+ } finally {+ NodeFS.rmSync(home, { recursive: true, force: true });+ }+});diff --git a/infra/task-cache/src/telemetry.ts b/infra/task-cache/src/telemetry.tsindex 509167b6c02..0fb8d5914dd 100644--- a/infra/task-cache/src/telemetry.ts+++ b/infra/task-cache/src/telemetry.ts@@ -161,6 +161,28 @@ export function observeSummaries(export async function flushTelemetry(home = NodeOS.homedir(), env = process.env) {const queue = NodePath.join(home, ".cache/t3-task-cache/telemetry");+ const deadline = Date.now() + 15_000;+ const skipped = new Set<string>();+ // A flusher that finds the lock taken exits and leaves its event to the holder. Re-check after+ // releasing, or an event queued after the holder's last scan waits for the next command.+ try {+ while (+ (await drainTelemetry(queue, home, env, deadline, skipped)) &&+ Date.now() < deadline &&+ NodeFS.readdirSync(queue).some((entry) => entry.endsWith(".json") && !skipped.has(entry))+ );+ } catch {+ /* Leave unsent events for a later invocation. */+ }+}++async function drainTelemetry(+ queue: string,+ home: string,+ env: NodeJS.ProcessEnv,+ deadline: number,+ skipped: Set<string>,+) {const lock = NodePath.join(queue, "flush.lock");try {NodeFS.mkdirSync(queue, { recursive: true, mode: 0o700 });@@ -171,7 +193,7 @@ export async function flushTelemetry(home = NodeOS.homedir(), env = process.env)}NodeFS.mkdirSync(lock);} catch {- return;+ return false;}try {const files = NodeFS.readdirSync(queue)@@ -188,14 +210,12 @@ export async function flushTelemetry(home = NodeOS.homedir(), env = process.env)const credentials = NodeFS.existsSync(credentialsFile)? JSON.parse(NodeFS.readFileSync(credentialsFile, "utf8")): {};- const deadline = Date.now() + 15_000;- const skipped = new Set<string>();// Re-scan between sends so a concurrent command's final summary joins this flush.for (let sent = 0; sent < 100 && Date.now() < deadline;) {const file = NodeFS.readdirSync(queue).filter((entry) => entry.endsWith(".json") && !skipped.has(entry)).sort()[0];- if (!file) break;+ if (!file) return true;const path = NodePath.join(queue, file);const { endpoint, event } = JSON.parse(NodeFS.readFileSync(path, "utf8"));const url = new URL(endpoint);@@ -229,7 +249,7 @@ export async function flushTelemetry(home = NodeOS.homedir(), env = process.env)headers: { Authorization: `Bearer ${env.ACTIONS_ID_TOKEN_REQUEST_TOKEN}` },signal: AbortSignal.timeout(3000),});- if (!response.ok) return;+ if (!response.ok) return false;const token = (await response.json()) as { value: string };authorization = `Bearer ${token.value}`;} else {@@ -246,7 +266,7 @@ export async function flushTelemetry(home = NodeOS.homedir(), env = process.env)});await response.body?.cancel();if (response.ok || [400, 401, 403, 413].includes(response.status)) NodeFS.unlinkSync(path);- else return;+ else return false;}} catch {/* Leave unsent events for a later invocation. */