oauth-polling-clock-faults.cjs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // 只改变新测试 Host 的系统时间;performance.now 和真实定时器保持不变。
  2. const { appendFile } = require("node:fs/promises");
  3. const { join } = require("node:path");
  4. const { pathToFileURL } = require("node:url");
  5. const originalNow = Date.now;
  6. const originalFetch = globalThis.fetch;
  7. const origin = process.env.ZCODE_E2E_OAUTH_RACE_URL;
  8. const caseId = process.env.ZCODE_E2E_OAUTH_CLOCK_CASE;
  9. let offset = 0;
  10. Date.now = () => originalNow() + offset;
  11. globalThis.fetch = async (input, init) => {
  12. const response = await originalFetch(input, init);
  13. const url = new URL(input instanceof Request ? input.url : String(input));
  14. // init 响应注入"本机时钟偏快",poll 响应注入"系统时间跳变";偏移在返回给 Host 之前生效。
  15. if (
  16. url.origin === origin &&
  17. (url.pathname === "/api/v1/oauth/cli/init" ||
  18. url.pathname === "/api/v1/oauth/cli/poll/e2e-race")
  19. ) {
  20. const value = response.headers.get("x-e2e-clock-offset-ms");
  21. if (value !== null) {
  22. offset = Number(value);
  23. await appendFile(
  24. join(process.env.ZCODE_E2E_HOST_FAULT_ROOT, `host-boundary-${process.pid}.jsonl`),
  25. JSON.stringify({ pid: process.pid, id: caseId, kind: "clock-shift", offset }) + "\n",
  26. );
  27. }
  28. }
  29. return response;
  30. };
  31. async function start() {
  32. await appendFile(
  33. join(process.env.ZCODE_E2E_HOST_FAULT_ROOT, `host-boundary-${process.pid}.jsonl`),
  34. JSON.stringify({ pid: process.pid, id: caseId, kind: "ready" }) + "\n",
  35. );
  36. await import(pathToFileURL(process.argv[2]).href);
  37. }
  38. void start();