e2e-failure-artifacts.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. // 跳过的 case 没有失败可查;按失败保留会留下空视频和 passed=false 的 case.json。
  152. if (result.passed || result.status === "skipped" || result.status === "pending") {
  153. await activeCapture.recorder?.discard().catch(() => undefined);
  154. await rm(activeCapture.caseDir, { force: true, recursive: true });
  155. return undefined;
  156. }
  157. const collectionErrors = activeCapture.recordingError ? [activeCapture.recordingError] : [];
  158. let videoPath: string | undefined;
  159. try {
  160. const recordingResult = await activeCapture.recorder?.stop({
  161. tailDurationMs: readDurationEnv(
  162. "ZCODE_E2E_FAILURE_VIDEO_TAIL_MS",
  163. DEFAULT_FAILURE_VIDEO_TAIL_MS,
  164. ),
  165. });
  166. if (recordingResult) {
  167. videoPath = relative(this.artifactDir, recordingResult.videoPath);
  168. if (recordingResult.captureError) {
  169. collectionErrors.push(`video: ${recordingResult.captureError}`);
  170. }
  171. }
  172. } catch (error) {
  173. collectionErrors.push(`video: ${toErrorMessage(error)}`);
  174. }
  175. const logsDir = join(activeCapture.caseDir, "logs");
  176. let logFiles: Array<{ path: string; truncated: boolean }> = [];
  177. try {
  178. await runWithTimeout(
  179. async () => {
  180. await mkdir(logsDir, { recursive: true });
  181. logFiles = await materializeLogDeltas({
  182. afterRoot: resolve(this.artifactDir, "runtime-logs", activeCapture.workerId),
  183. beforeOffsets: activeCapture.logOffsets,
  184. outputDir: logsDir,
  185. });
  186. await writeFile(
  187. join(logsDir, "index.json"),
  188. `${JSON.stringify({ files: logFiles }, null, 2)}\n`,
  189. "utf-8",
  190. );
  191. },
  192. FAILURE_LOG_COLLECTION_TIMEOUT_MS,
  193. "case log collection",
  194. );
  195. } catch (error) {
  196. collectionErrors.push(`logs: ${toErrorMessage(error)}`);
  197. }
  198. const caseManifestPath = join(activeCapture.caseDir, "case.json");
  199. const caseManifest = {
  200. artifacts: {
  201. logsIndex: relative(this.artifactDir, join(logsDir, "index.json")),
  202. video: videoPath,
  203. },
  204. caseId: activeCapture.caseId,
  205. collectionErrors,
  206. completedAt: new Date().toISOString(),
  207. result: {
  208. durationMs: result.duration,
  209. error: result.error ? toErrorMessage(result.error) : undefined,
  210. errorCategory: result.errorCategory,
  211. passed: false,
  212. status: result.status,
  213. },
  214. retryIndex: activeCapture.retryIndex,
  215. retryLimit: test._retries ?? 0,
  216. spec: test.file,
  217. startedAt: activeCapture.startedAt,
  218. title: activeCapture.caseTitle,
  219. version: 1,
  220. workerId: activeCapture.workerId,
  221. };
  222. try {
  223. await runWithTimeout(
  224. () => writeFile(caseManifestPath, `${JSON.stringify(caseManifest, null, 2)}\n`, "utf-8"),
  225. FAILURE_MANIFEST_WRITE_TIMEOUT_MS,
  226. "case manifest write",
  227. );
  228. } catch (error) {
  229. // 修复原因:诊断文件系统异常也不能拖住 afterTest;错误随 test result 返回,
  230. // 即使 case.json 无法落盘,summary 仍能说明采集失败原因。
  231. collectionErrors.push(`manifest: ${toErrorMessage(error)}`);
  232. }
  233. return {
  234. caseId: activeCapture.caseId,
  235. caseManifest: relative(this.artifactDir, caseManifestPath),
  236. collectionErrors: collectionErrors.length > 0 ? collectionErrors : undefined,
  237. logsIndex: relative(this.artifactDir, join(logsDir, "index.json")),
  238. retryIndex: activeCapture.retryIndex,
  239. video: videoPath,
  240. workerId: activeCapture.workerId,
  241. };
  242. }
  243. }
  244. export async function snapshotLogOffsets(rootDir: string): Promise<Map<string, number>> {
  245. const offsets = new Map<string, number>();
  246. for (const filePath of await listRegularFiles(rootDir)) {
  247. offsets.set(relative(rootDir, filePath), (await stat(filePath)).size);
  248. }
  249. return offsets;
  250. }
  251. export async function materializeLogDeltas(options: {
  252. afterRoot: string;
  253. beforeOffsets: Map<string, number>;
  254. outputDir: string;
  255. }): Promise<Array<{ path: string; truncated: boolean }>> {
  256. const results: Array<{ path: string; truncated: boolean }> = [];
  257. for (const filePath of await listRegularFiles(options.afterRoot)) {
  258. const fileStats = await stat(filePath);
  259. const relativePath = relative(options.afterRoot, filePath);
  260. const start = Math.min(options.beforeOffsets.get(relativePath) ?? 0, fileStats.size);
  261. const availableBytes = fileStats.size - start;
  262. if (availableBytes <= 0) {
  263. continue;
  264. }
  265. const copiedBytes = Math.min(availableBytes, MAX_CASE_LOG_BYTES_PER_FILE);
  266. const destination = resolve(options.outputDir, relativePath);
  267. await mkdir(dirname(destination), { recursive: true });
  268. await pipeline(
  269. createReadStream(filePath, { end: start + copiedBytes - 1, start }),
  270. createWriteStream(destination),
  271. );
  272. results.push({ path: relativePath, truncated: copiedBytes < availableBytes });
  273. }
  274. return results;
  275. }
  276. async function listRegularFiles(rootDir: string): Promise<string[]> {
  277. try {
  278. const entries = await readdir(rootDir, { withFileTypes: true });
  279. const paths = await Promise.all(
  280. entries.map(async (entry) => {
  281. const entryPath = join(rootDir, entry.name);
  282. if (entry.isDirectory()) {
  283. return listRegularFiles(entryPath);
  284. }
  285. return entry.isFile() ? [entryPath] : [];
  286. }),
  287. );
  288. return paths.flat();
  289. } catch (error) {
  290. if (isNotFoundError(error)) {
  291. return [];
  292. }
  293. throw error;
  294. }
  295. }
  296. function createCaseId(title: string): string {
  297. return createHash("sha256").update(title).digest("hex").slice(0, 16);
  298. }
  299. function getActiveKey(title: string, retryIndex: number): string {
  300. return `${title}\u0000${retryIndex}`;
  301. }
  302. function getCaseTitle(test: E2EFailureArtifactTest): string {
  303. return test.fullTitle || test.fullName || test.title;
  304. }
  305. function isNotFoundError(error: unknown): boolean {
  306. return typeof error === "object" && error !== null && "code" in error && error.code === "ENOENT";
  307. }
  308. function sanitizeFilePart(value: string): string {
  309. return value.replace(/[^a-zA-Z0-9._-]+/g, "_").slice(0, 100) || "main";
  310. }
  311. function toErrorMessage(error: unknown): string {
  312. return error instanceof Error ? error.message : String(error);
  313. }
  314. function readDurationEnv(name: string, fallback: number): number {
  315. const value = Number.parseInt(process.env[name] ?? "", 10);
  316. if (!Number.isFinite(value)) {
  317. return fallback;
  318. }
  319. return Math.max(0, Math.min(10_000, value));
  320. }
  321. function readTimeoutEnv(name: string, fallback: number): number {
  322. const value = Number.parseInt(process.env[name] ?? "", 10);
  323. if (!Number.isFinite(value)) {
  324. return fallback;
  325. }
  326. return Math.max(1, Math.min(5 * 60_000, value));
  327. }
  328. async function runWithTimeout<T>(
  329. run: () => Promise<T>,
  330. timeoutMs: number,
  331. label: string,
  332. ): Promise<T> {
  333. let timeout: ReturnType<typeof setTimeout> | undefined;
  334. const timeoutPromise = new Promise<never>((_resolve, reject) => {
  335. timeout = setTimeout(() => {
  336. reject(new Error(`${label} timed out after ${timeoutMs}ms`));
  337. }, timeoutMs);
  338. });
  339. try {
  340. return await Promise.race([run(), timeoutPromise]);
  341. } finally {
  342. if (timeout) {
  343. clearTimeout(timeout);
  344. }
  345. }
  346. }