storage-worker-diagnostics.mjs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // 仅 E2E 定向诊断使用:旁观存储 Worker,不改变控制帧、退出码或恢复行为。
  2. import workerThreads from "node:worker_threads";
  3. import { syncBuiltinESMExports } from "node:module";
  4. import { mkdir, writeFile } from "node:fs/promises";
  5. import { join } from "node:path";
  6. const outputDir = process.env.ZCODE_E2E_STORAGE_WORKER_DIAGNOSTICS_DIR;
  7. if (outputDir) {
  8. const OriginalWorker = workerThreads.Worker;
  9. workerThreads.Worker = class extends OriginalWorker {
  10. constructor(entry, options) {
  11. super(entry, options);
  12. if (!options?.argv?.includes("--prepare-storage")) return;
  13. const workerId = this.threadId;
  14. let stderr = "";
  15. let pendingLine = "";
  16. let lastFrame = null;
  17. let workerError = null;
  18. this.stderr?.on("data", (chunk) => {
  19. stderr = (stderr + chunk.toString()).slice(-65_536);
  20. });
  21. this.stdout?.on("data", (chunk) => {
  22. pendingLine += chunk.toString();
  23. const lines = pendingLine.split("\n");
  24. pendingLine = lines.pop().slice(-65_536);
  25. for (const line of lines) {
  26. try {
  27. const frame = JSON.parse(line);
  28. lastFrame = { method: frame.method, params: frame.params };
  29. } catch {
  30. lastFrame = { invalidControlFrame: true };
  31. }
  32. }
  33. });
  34. this.on("error", (error) => {
  35. workerError = error.message;
  36. });
  37. this.on("exit", (exitCode) => {
  38. // 原始 stderr 只保存到本次隔离 artifact,不上报遥测;权限限定为当前测试用户。
  39. void mkdir(outputDir, { recursive: true })
  40. .then(() =>
  41. writeFile(
  42. join(outputDir, `storage-worker-${process.pid}-${workerId}.json`),
  43. JSON.stringify(
  44. {
  45. exitCode,
  46. stderr,
  47. lastFrame,
  48. workerError,
  49. entry: String(entry),
  50. argv: options.argv,
  51. },
  52. null,
  53. 2,
  54. ),
  55. { mode: 0o600 },
  56. ),
  57. )
  58. .catch(() => {
  59. /* 取证落盘失败不得改变被观察 Worker 的行为。 */
  60. });
  61. });
  62. }
  63. };
  64. syncBuiltinESMExports();
  65. }