e2e-failure-artifacts.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  1. import { createHash } from "node:crypto";
  2. import { createReadStream, createWriteStream } from "node:fs";
  3. import { mkdir, readdir, rm, stat, writeFile } from "node:fs/promises";
  4. import { dirname, join, relative, resolve } from "node:path";
  5. import { pipeline } from "node:stream/promises";
  6. import {
  7. startElectronWindowRecording,
  8. type ElectronWindowRecordingSession,
  9. } from "../helpers/electron-window-recorder.js";
  10. const MAX_CASE_LOG_BYTES_PER_FILE = 10 * 1024 * 1024;
  11. const DEFAULT_FAILURE_VIDEO_FRAME_INTERVAL_MS = 250;
  12. const DEFAULT_FAILURE_VIDEO_PRE_ROLL_MS = 2_000;
  13. const DEFAULT_FAILURE_VIDEO_TAIL_MS = 2_000;
  14. const DEFAULT_FAILURE_VIDEO_CAPTURE_TIMEOUT_MS = 5_000;
  15. const DEFAULT_FAILURE_VIDEO_ENCODE_TIMEOUT_MS = 30_000;
  16. const DEFAULT_FAILURE_VIDEO_STOP_TIMEOUT_MS = 45_000;
  17. const FAILURE_LOG_COLLECTION_TIMEOUT_MS = 5_000;
  18. const FAILURE_MANIFEST_WRITE_TIMEOUT_MS = 2_000;
  19. export interface E2EFailureArtifactTest {
  20. file?: string;
  21. fullName?: string;
  22. fullTitle?: string;
  23. title: string;
  24. _currentRetry?: number;
  25. _retries?: number;
  26. }
  27. export interface E2EFailureArtifactResult {
  28. duration: number;
  29. error?: unknown;
  30. errorCategory?: string;
  31. passed: boolean;
  32. status: string;
  33. }
  34. export interface E2EFailureArtifactRefs {
  35. caseId: string;
  36. caseManifest: string;
  37. collectionErrors?: string[];
  38. logsIndex: string;
  39. retryIndex: number;
  40. video?: string;
  41. workerId: string;
  42. }
  43. interface ActiveCaseCapture {
  44. caseDir: string;
  45. caseId: string;
  46. caseTitle: string;
  47. logOffsets: Map<string, number>;
  48. recorder?: ElectronWindowRecordingSession;
  49. recordingError?: string;
  50. retryIndex: number;
  51. startedAt: string;
  52. workerId: string;
  53. }
  54. export interface E2EFailureArtifactCollectorOptions {
  55. artifactDir: string;
  56. browser: WebdriverIO.Browser;
  57. enabled?: boolean;
  58. workerId?: string;
  59. }
  60. /**
  61. * 为失败 case 收集独立的日志增量和窗口视频。
  62. *
  63. * 同一个 WDIO worker 内的 Mocha case 串行执行,因此通过每个 runtime log 的 byte
  64. * offset 截取 case 时间窗是确定性的;跨 worker 则由运行时日志根目录隔离保证。
  65. */
  66. export class E2EFailureArtifactCollector {
  67. private readonly activeCaptures = new Map<string, ActiveCaseCapture>();
  68. private readonly artifactDir: string;
  69. private readonly browser: WebdriverIO.Browser;
  70. private readonly enabled: boolean;
  71. private readonly workerId: string;
  72. constructor(options: E2EFailureArtifactCollectorOptions) {
  73. this.artifactDir = resolve(options.artifactDir);
  74. this.browser = options.browser;
  75. this.enabled = options.enabled ?? process.env.ZCODE_E2E_FAILURE_ARTIFACTS === "1";
  76. this.workerId = sanitizeFilePart(options.workerId ?? process.env.ZCODE_E2E_WORKER_ID ?? "main");
  77. }
  78. async start(test: E2EFailureArtifactTest): Promise<void> {
  79. if (!this.enabled) {
  80. return;
  81. }
  82. const caseTitle = getCaseTitle(test);
  83. const retryIndex = test._currentRetry ?? 0;
  84. const activeKey = getActiveKey(caseTitle, retryIndex);
  85. const caseId = createCaseId(caseTitle);
  86. const caseDir = resolve(
  87. this.artifactDir,
  88. "failures",
  89. this.workerId,
  90. caseId,
  91. `attempt-${retryIndex}`,
  92. );
  93. const runtimeLogDir = resolve(this.artifactDir, "runtime-logs", this.workerId);
  94. const activeCapture: ActiveCaseCapture = {
  95. caseDir,
  96. caseId,
  97. caseTitle,
  98. logOffsets: await snapshotLogOffsets(runtimeLogDir),
  99. retryIndex,
  100. startedAt: new Date().toISOString(),
  101. workerId: this.workerId,
  102. };
  103. await mkdir(caseDir, { recursive: true });
  104. try {
  105. activeCapture.recorder = await startElectronWindowRecording({
  106. browser: this.browser,
  107. captureTimeoutMs: readTimeoutEnv(
  108. "ZCODE_E2E_FAILURE_VIDEO_CAPTURE_TIMEOUT_MS",
  109. DEFAULT_FAILURE_VIDEO_CAPTURE_TIMEOUT_MS,
  110. ),
  111. encodeTimeoutMs: readTimeoutEnv(
  112. "ZCODE_E2E_FAILURE_VIDEO_ENCODE_TIMEOUT_MS",
  113. DEFAULT_FAILURE_VIDEO_ENCODE_TIMEOUT_MS,
  114. ),
  115. frameDir: join(caseDir, "frames"),
  116. frameIntervalMs: readDurationEnv(
  117. "ZCODE_E2E_FAILURE_VIDEO_FRAME_INTERVAL_MS",
  118. DEFAULT_FAILURE_VIDEO_FRAME_INTERVAL_MS,
  119. ),
  120. outputPath: join(caseDir, "video.webm"),
  121. preRollDurationMs: readDurationEnv(
  122. "ZCODE_E2E_FAILURE_VIDEO_PRE_ROLL_MS",
  123. DEFAULT_FAILURE_VIDEO_PRE_ROLL_MS,
  124. ),
  125. stopTimeoutMs: readTimeoutEnv(
  126. "ZCODE_E2E_FAILURE_VIDEO_STOP_TIMEOUT_MS",
  127. DEFAULT_FAILURE_VIDEO_STOP_TIMEOUT_MS,
  128. ),
  129. });
  130. } catch (error) {
  131. // 修复原因:录制依赖 Electron capturePage;窗口崩溃时录制失败不能覆盖原始断言或崩溃结果。
  132. activeCapture.recordingError = toErrorMessage(error);
  133. }
  134. this.activeCaptures.set(activeKey, activeCapture);
  135. }
  136. async complete(
  137. test: E2EFailureArtifactTest,
  138. result: E2EFailureArtifactResult,
  139. ): Promise<E2EFailureArtifactRefs | undefined> {
  140. if (!this.enabled) {
  141. return undefined;
  142. }
  143. const caseTitle = getCaseTitle(test);
  144. const retryIndex = test._currentRetry ?? 0;
  145. const activeKey = getActiveKey(caseTitle, retryIndex);
  146. const activeCapture = this.activeCaptures.get(activeKey);
  147. this.activeCaptures.delete(activeKey);
  148. if (!activeCapture) {
  149. return undefined;
  150. }
  151. if (result.passed) {
  152. await activeCapture.recorder?.discard().catch(() => undefined);
  153. await rm(activeCapture.caseDir, { force: true, recursive: true });
  154. return undefined;
  155. }
  156. const collectionErrors = activeCapture.recordingError ? [activeCapture.recordingError] : [];
  157. let videoPath: string | undefined;
  158. try {
  159. const recordingResult = await activeCapture.recorder?.stop({
  160. tailDurationMs: readDurationEnv(
  161. "ZCODE_E2E_FAILURE_VIDEO_TAIL_MS",
  162. DEFAULT_FAILURE_VIDEO_TAIL_MS,
  163. ),
  164. });
  165. if (recordingResult) {
  166. videoPath = relative(this.artifactDir, recordingResult.videoPath);
  167. if (recordingResult.captureError) {
  168. collectionErrors.push(`video: ${recordingResult.captureError}`);
  169. }
  170. }
  171. } catch (error) {
  172. collectionErrors.push(`video: ${toErrorMessage(error)}`);
  173. }
  174. const logsDir = join(activeCapture.caseDir, "logs");
  175. let logFiles: Array<{ path: string; truncated: boolean }> = [];
  176. try {
  177. await runWithTimeout(
  178. async () => {
  179. await mkdir(logsDir, { recursive: true });
  180. logFiles = await materializeLogDeltas({
  181. afterRoot: resolve(this.artifactDir, "runtime-logs", activeCapture.workerId),
  182. beforeOffsets: activeCapture.logOffsets,
  183. outputDir: logsDir,
  184. });
  185. await writeFile(
  186. join(logsDir, "index.json"),
  187. `${JSON.stringify({ files: logFiles }, null, 2)}\n`,
  188. "utf-8",
  189. );
  190. },
  191. FAILURE_LOG_COLLECTION_TIMEOUT_MS,
  192. "case log collection",
  193. );
  194. } catch (error) {
  195. collectionErrors.push(`logs: ${toErrorMessage(error)}`);
  196. }
  197. const caseManifestPath = join(activeCapture.caseDir, "case.json");
  198. const caseManifest = {
  199. artifacts: {
  200. logsIndex: relative(this.artifactDir, join(logsDir, "index.json")),
  201. video: videoPath,
  202. },
  203. caseId: activeCapture.caseId,
  204. collectionErrors,
  205. completedAt: new Date().toISOString(),
  206. result: {
  207. durationMs: result.duration,
  208. error: result.error ? toErrorMessage(result.error) : undefined,
  209. errorCategory: result.errorCategory,
  210. passed: false,
  211. status: result.status,
  212. },
  213. retryIndex: activeCapture.retryIndex,
  214. retryLimit: test._retries ?? 0,
  215. spec: test.file,
  216. startedAt: activeCapture.startedAt,
  217. title: activeCapture.caseTitle,
  218. version: 1,
  219. workerId: activeCapture.workerId,
  220. };
  221. try {
  222. await runWithTimeout(
  223. () => writeFile(caseManifestPath, `${JSON.stringify(caseManifest, null, 2)}\n`, "utf-8"),
  224. FAILURE_MANIFEST_WRITE_TIMEOUT_MS,
  225. "case manifest write",
  226. );
  227. } catch (error) {
  228. // 修复原因:诊断文件系统异常也不能拖住 afterTest;错误随 test result 返回,
  229. // 即使 case.json 无法落盘,summary 仍能说明采集失败原因。
  230. collectionErrors.push(`manifest: ${toErrorMessage(error)}`);
  231. }
  232. return {
  233. caseId: activeCapture.caseId,
  234. caseManifest: relative(this.artifactDir, caseManifestPath),
  235. collectionErrors: collectionErrors.length > 0 ? collectionErrors : undefined,
  236. logsIndex: relative(this.artifactDir, join(logsDir, "index.json")),
  237. retryIndex: activeCapture.retryIndex,
  238. video: videoPath,
  239. workerId: activeCapture.workerId,
  240. };
  241. }
  242. }
  243. export async function snapshotLogOffsets(rootDir: string): Promise<Map<string, number>> {
  244. const offsets = new Map<string, number>();
  245. for (const filePath of await listRegularFiles(rootDir)) {
  246. offsets.set(relative(rootDir, filePath), (await stat(filePath)).size);
  247. }
  248. return offsets;
  249. }
  250. export async function materializeLogDeltas(options: {
  251. afterRoot: string;
  252. beforeOffsets: Map<string, number>;
  253. outputDir: string;
  254. }): Promise<Array<{ path: string; truncated: boolean }>> {
  255. const results: Array<{ path: string; truncated: boolean }> = [];
  256. for (const filePath of await listRegularFiles(options.afterRoot)) {
  257. const fileStats = await stat(filePath);
  258. const relativePath = relative(options.afterRoot, filePath);
  259. const start = Math.min(options.beforeOffsets.get(relativePath) ?? 0, fileStats.size);
  260. const availableBytes = fileStats.size - start;
  261. if (availableBytes <= 0) {
  262. continue;
  263. }
  264. const copiedBytes = Math.min(availableBytes, MAX_CASE_LOG_BYTES_PER_FILE);
  265. const destination = resolve(options.outputDir, relativePath);
  266. await mkdir(dirname(destination), { recursive: true });
  267. await pipeline(
  268. createReadStream(filePath, { end: start + copiedBytes - 1, start }),
  269. createWriteStream(destination),
  270. );
  271. results.push({ path: relativePath, truncated: copiedBytes < availableBytes });
  272. }
  273. return results;
  274. }
  275. async function listRegularFiles(rootDir: string): Promise<string[]> {
  276. try {
  277. const entries = await readdir(rootDir, { withFileTypes: true });
  278. const paths = await Promise.all(
  279. entries.map(async (entry) => {
  280. const entryPath = join(rootDir, entry.name);
  281. if (entry.isDirectory()) {
  282. return listRegularFiles(entryPath);
  283. }
  284. return entry.isFile() ? [entryPath] : [];
  285. }),
  286. );
  287. return paths.flat();
  288. } catch (error) {
  289. if (isNotFoundError(error)) {
  290. return [];
  291. }
  292. throw error;
  293. }
  294. }
  295. function createCaseId(title: string): string {
  296. return createHash("sha256").update(title).digest("hex").slice(0, 16);
  297. }
  298. function getActiveKey(title: string, retryIndex: number): string {
  299. return `${title}\u0000${retryIndex}`;
  300. }
  301. function getCaseTitle(test: E2EFailureArtifactTest): string {
  302. return test.fullTitle || test.fullName || test.title;
  303. }
  304. function isNotFoundError(error: unknown): boolean {
  305. return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
  306. }
  307. function sanitizeFilePart(value: string): string {
  308. return value.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 100) || "main";
  309. }
  310. function toErrorMessage(error: unknown): string {
  311. return error instanceof Error ? error.message : String(error);
  312. }
  313. function readDurationEnv(name: string, fallback: number): number {
  314. const value = Number.parseInt(process.env[name] ?? "", 10);
  315. if (!Number.isFinite(value)) {
  316. return fallback;
  317. }
  318. return Math.max(0, Math.min(10_000, value));
  319. }
  320. function readTimeoutEnv(name: string, fallback: number): number {
  321. const value = Number.parseInt(process.env[name] ?? "", 10);
  322. if (!Number.isFinite(value)) {
  323. return fallback;
  324. }
  325. return Math.max(1, Math.min(5 * 60_000, value));
  326. }
  327. async function runWithTimeout<T>(
  328. run: () => Promise<T>,
  329. timeoutMs: number,
  330. label: string,
  331. ): Promise<T> {
  332. let timeout: ReturnType<typeof setTimeout> | undefined;
  333. const timeoutPromise = new Promise<never>((_resolve, reject) => {
  334. timeout = setTimeout(() => {
  335. reject(new Error(`${label} timed out after ${timeoutMs}ms`));
  336. }, timeoutMs);
  337. });
  338. try {
  339. return await Promise.race([run(), timeoutPromise]);
  340. } finally {
  341. if (timeout) {
  342. clearTimeout(timeout);
  343. }
  344. }
  345. }