telemetryDeliveryReliability.test.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. import { mkdtempSync, rmSync } from "node:fs";
  2. import { tmpdir } from "node:os";
  3. import { join } from "node:path";
  4. import { afterEach, describe, expect, it, vi } from "vitest";
  5. const tempHomes: string[] = [];
  6. function makeTempHome(): string {
  7. const home = mkdtempSync(join(tmpdir(), "zcode-telemetry-delivery-"));
  8. tempHomes.push(home);
  9. return home;
  10. }
  11. async function waitForCalls(
  12. mock: ReturnType<typeof vi.fn<typeof fetch>>,
  13. expectedCalls: number,
  14. ): Promise<void> {
  15. for (let attempt = 0; attempt < 20; attempt += 1) {
  16. if (mock.mock.calls.length === expectedCalls) return;
  17. await new Promise((resolve) => setTimeout(resolve, 10));
  18. }
  19. expect(mock).toHaveBeenCalledTimes(expectedCalls);
  20. }
  21. afterEach(() => {
  22. vi.restoreAllMocks();
  23. while (tempHomes.length > 0) {
  24. const home = tempHomes.pop();
  25. if (home) rmSync(home, { recursive: true, force: true });
  26. }
  27. });
  28. describe("telemetry delivery reliability", () => {
  29. it("retries a network failure once with the identical endpoint, body, and event_id", async () => {
  30. const home = makeTempHome();
  31. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  32. const fetchMock = vi
  33. .fn<typeof fetch>()
  34. .mockRejectedValueOnce(new Error("temporary network failure"))
  35. .mockResolvedValueOnce(new Response(null, { status: 204 }));
  36. const sleep = vi.fn(async () => {});
  37. const resolveZCodeEndpointOrigin = vi.fn(async () => "https://telemetry.example.com");
  38. const ids = ["logical-event-id", "stable-device-mid"];
  39. const service = createTelemetryCore({
  40. fetchImpl: fetchMock,
  41. homeDir: home,
  42. randomUUID: () => ids.shift() ?? "unexpected-id",
  43. resolveZCodeEndpointOrigin,
  44. sleep,
  45. });
  46. await service.reportEvent({
  47. context: {
  48. clientTimezone: "Asia/Shanghai",
  49. clientLanguage: "zh-CN",
  50. screenResolution: "1920x1080",
  51. },
  52. elementName: "off_peak_task_create_result",
  53. eventRegion: "app.automations",
  54. eventType: "result",
  55. eventExtraDetail: { off_peak_task_id: "OP-1" },
  56. });
  57. expect(fetchMock).toHaveBeenCalledTimes(2);
  58. expect(fetchMock.mock.calls[1]?.[0]).toBe(fetchMock.mock.calls[0]?.[0]);
  59. expect(fetchMock.mock.calls[1]?.[1]?.body).toBe(fetchMock.mock.calls[0]?.[1]?.body);
  60. expect(JSON.parse(String(fetchMock.mock.calls[1]?.[1]?.body))).toMatchObject({
  61. event_id: "logical-event-id",
  62. });
  63. expect(resolveZCodeEndpointOrigin).toHaveBeenCalledTimes(1);
  64. expect(sleep).toHaveBeenCalledWith(300);
  65. });
  66. it.each([
  67. { status: 408, delayMs: 300 },
  68. { status: 429, delayMs: 1_000 },
  69. { status: 500, delayMs: 300 },
  70. ])("retries HTTP $status once", async ({ status, delayMs }) => {
  71. const home = makeTempHome();
  72. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  73. const fetchMock = vi
  74. .fn<typeof fetch>()
  75. .mockResolvedValueOnce(new Response(null, { status }))
  76. .mockResolvedValueOnce(new Response(null, { status: 204 }));
  77. const sleep = vi.fn(async () => {});
  78. const service = createTelemetryCore({
  79. fetchImpl: fetchMock,
  80. homeDir: home,
  81. randomUUID: () => "retryable-event-id",
  82. sleep,
  83. });
  84. await service.reportAppLaunch({
  85. clientTimezone: "Asia/Shanghai",
  86. clientLanguage: "zh-CN",
  87. screenResolution: "1920x1080",
  88. });
  89. expect(fetchMock).toHaveBeenCalledTimes(2);
  90. expect(sleep).toHaveBeenCalledWith(delayMs);
  91. });
  92. it.each([400, 401])("does not retry permanent HTTP %s", async (status) => {
  93. const home = makeTempHome();
  94. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  95. const fetchMock = vi.fn<typeof fetch>().mockResolvedValue(new Response(null, { status }));
  96. const sleep = vi.fn(async () => {});
  97. const warn = vi.fn();
  98. const service = createTelemetryCore({
  99. fetchImpl: fetchMock,
  100. homeDir: home,
  101. randomUUID: () => "permanent-event-id",
  102. sleep,
  103. warn,
  104. });
  105. await expect(
  106. service.reportAppLaunch({
  107. clientTimezone: "Asia/Shanghai",
  108. clientLanguage: "zh-CN",
  109. screenResolution: "1920x1080",
  110. }),
  111. ).rejects.toThrow(String(status));
  112. expect(fetchMock).toHaveBeenCalledTimes(1);
  113. expect(sleep).not.toHaveBeenCalled();
  114. expect(warn).toHaveBeenCalledTimes(1);
  115. });
  116. it("aborts a hanging attempt and retries once", async () => {
  117. const home = makeTempHome();
  118. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  119. const fetchMock = vi
  120. .fn<typeof fetch>()
  121. .mockImplementationOnce(async (_input, init) => {
  122. await new Promise<never>((_resolve, reject) => {
  123. init?.signal?.addEventListener("abort", () => reject(new Error("aborted")), {
  124. once: true,
  125. });
  126. });
  127. throw new Error("unreachable");
  128. })
  129. .mockResolvedValueOnce(new Response(null, { status: 204 }));
  130. const sleep = vi.fn(async () => {});
  131. const service = createTelemetryCore({
  132. fetchImpl: fetchMock,
  133. homeDir: home,
  134. randomUUID: () => "timeout-event-id",
  135. requestTimeoutMs: 5,
  136. sleep,
  137. });
  138. await service.reportAppLaunch({
  139. clientTimezone: "Asia/Shanghai",
  140. clientLanguage: "zh-CN",
  141. screenResolution: "1920x1080",
  142. });
  143. expect(fetchMock).toHaveBeenCalledTimes(2);
  144. expect(fetchMock.mock.calls[0]?.[1]?.signal).toBeInstanceOf(AbortSignal);
  145. expect(sleep).toHaveBeenCalledWith(300);
  146. });
  147. it("logs one redacted final warning after both attempts fail", async () => {
  148. const home = makeTempHome();
  149. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  150. const fetchMock = vi
  151. .fn<typeof fetch>()
  152. .mockRejectedValue(new Error("secret C:\\Users\\private\\token.txt"));
  153. const warn = vi.fn();
  154. const service = createTelemetryCore({
  155. fetchImpl: fetchMock,
  156. homeDir: home,
  157. randomUUID: () => "redacted-event-id",
  158. sleep: async () => {},
  159. warn,
  160. });
  161. await expect(
  162. service.reportEvent({
  163. context: {
  164. clientTimezone: "Asia/Shanghai",
  165. clientLanguage: "zh-CN",
  166. screenResolution: "1920x1080",
  167. },
  168. elementName: "off_peak_task_create_result",
  169. eventRegion: "app.automations",
  170. eventType: "result",
  171. eventExtraDetail: {},
  172. }),
  173. ).rejects.toThrow();
  174. expect(fetchMock).toHaveBeenCalledTimes(2);
  175. expect(warn).toHaveBeenCalledTimes(1);
  176. const warning = String(warn.mock.calls[0]?.[0]);
  177. expect(warning).toContain("event=off_peak_task_create_result");
  178. expect(warning).toContain("eventId=redacted-event-id");
  179. expect(warning).toContain("attempts=2");
  180. expect(warning).not.toContain("Users");
  181. expect(warning).not.toContain("token.txt");
  182. });
  183. it("flushes reports added while an app-quit drain is already waiting", async () => {
  184. const home = makeTempHome();
  185. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  186. const releases: Array<() => void> = [];
  187. const fetchMock = vi.fn<typeof fetch>().mockImplementation(
  188. () =>
  189. new Promise<Response>((resolve) => {
  190. releases.push(() => resolve(new Response(null, { status: 204 })));
  191. }),
  192. );
  193. const service = createTelemetryCore({
  194. fetchImpl: fetchMock,
  195. homeDir: home,
  196. randomUUID: () => `dynamic-${fetchMock.mock.calls.length}`,
  197. });
  198. const context = {
  199. clientTimezone: "Asia/Shanghai",
  200. clientLanguage: "zh-CN",
  201. screenResolution: "1920x1080",
  202. };
  203. const firstReport = service.reportAppLaunch(context);
  204. await waitForCalls(fetchMock, 1);
  205. let flushed = false;
  206. const flush = service.flushPendingReports({ timeoutMs: 1_000 }).then(() => {
  207. flushed = true;
  208. });
  209. const secondReport = service.reportAppLaunch(context);
  210. await waitForCalls(fetchMock, 2);
  211. releases[0]?.();
  212. await firstReport;
  213. await Promise.resolve();
  214. expect(flushed).toBe(false);
  215. releases[1]?.();
  216. await Promise.all([secondReport, flush]);
  217. expect(flushed).toBe(true);
  218. });
  219. it("stops waiting for pending reports when the flush deadline expires", async () => {
  220. const home = makeTempHome();
  221. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  222. let releaseFetch: (() => void) | undefined;
  223. const fetchMock = vi.fn<typeof fetch>().mockImplementation(
  224. () =>
  225. new Promise<Response>((resolve) => {
  226. releaseFetch = () => resolve(new Response(null, { status: 204 }));
  227. }),
  228. );
  229. const warn = vi.fn();
  230. const service = createTelemetryCore({
  231. fetchImpl: fetchMock,
  232. homeDir: home,
  233. randomUUID: () => "flush-timeout-event-id",
  234. requestTimeoutMs: 1_000,
  235. warn,
  236. });
  237. const report = service.reportAppLaunch({
  238. clientTimezone: "Asia/Shanghai",
  239. clientLanguage: "zh-CN",
  240. screenResolution: "1920x1080",
  241. });
  242. await waitForCalls(fetchMock, 1);
  243. await service.flushPendingReports({ timeoutMs: 5 });
  244. expect(warn).toHaveBeenCalledWith("Telemetry flush timed out; pending=1");
  245. releaseFetch?.();
  246. await report;
  247. });
  248. });
  249. describe("session_create 稳定事件身份", () => {
  250. it("同用户/session 跨 core 和 HTTP 重试同 ID,不同用户或 session 不碰撞", async () => {
  251. const { createTelemetryCore } = await import("../src/telemetry/telemetryCore.js");
  252. const home = makeTempHome();
  253. const fetchMock = vi
  254. .fn<typeof fetch>()
  255. .mockRejectedValueOnce(new Error("offline"))
  256. .mockImplementation(async () => new Response(null, { status: 204 }));
  257. const input = {
  258. context: { clientTimezone: "UTC", clientLanguage: "en", screenResolution: "" },
  259. elementName: "session_create",
  260. eventRegion: "app",
  261. eventType: "result",
  262. eventExtraDetail: { create_source: "project" },
  263. talkId: "sess-1",
  264. messageId: "input-1",
  265. userId: "user-1",
  266. };
  267. const core = () =>
  268. createTelemetryCore({ fetchImpl: fetchMock, homeDir: home, sleep: async () => {} });
  269. await core().reportEvent(input);
  270. await core().reportEvent({
  271. ...input,
  272. messageId: "input-2",
  273. eventExtraDetail: { create_source: "session" },
  274. });
  275. await core().reportEvent({ ...input, talkId: "sess-2" });
  276. await core().reportEvent({ ...input, userId: "user-2" });
  277. const ids = fetchMock.mock.calls.map(([, init]) => JSON.parse(String(init?.body)).event_id);
  278. expect(ids).toHaveLength(5);
  279. expect(ids[0]).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-8[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
  280. expect(ids[1]).toBe(ids[0]);
  281. expect(ids[2]).toBe(ids[0]);
  282. expect(new Set([ids[0], ids[3], ids[4]]).size).toBe(3);
  283. });
  284. });