ttft-otlp-fixture.ts 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { spawn } from "node:child_process";
  2. import { once } from "node:events";
  3. import { fileURLToPath } from "node:url";
  4. /** 真实 OTLP 出口的隔离接收器;不拦截应用埋点,也不与其他 worker 共用固定端口。 */
  5. export async function prepareTtftOtlpFixture(
  6. specs: string[],
  7. ): Promise<(() => Promise<void>) | null> {
  8. if (
  9. !specs.some((spec) => /conversation-session-ttft-(stages|diagnostics)\.test\.ts$/.test(spec))
  10. ) {
  11. return null;
  12. }
  13. const child = spawn(
  14. process.execPath,
  15. [fileURLToPath(new URL("../../../scripts/ttft-otlp-receiver.mjs", import.meta.url)), "0"],
  16. { stdio: ["ignore", "pipe", "pipe"] },
  17. );
  18. let stderr = "";
  19. child.stderr.on("data", (chunk) => {
  20. stderr = (stderr + String(chunk)).slice(-4000);
  21. });
  22. const endpoint = await new Promise<string>((resolve, reject) => {
  23. let output = "";
  24. child.once("error", reject);
  25. child.once("exit", (code) => reject(new Error(`OTLP receiver exited (${code}): ${stderr}`)));
  26. child.stdout.on("data", (chunk) => {
  27. output += String(chunk);
  28. const port = /OTLP receiver ready:(\d+)/.exec(output)?.[1];
  29. if (port) resolve(`http://127.0.0.1:${port}`);
  30. });
  31. });
  32. // signal 专属 endpoint/headers 优先于公共值,全部覆盖才能保证真实导出留在隔离接收器。
  33. const patch = {
  34. ZCODE_LOCAL_TTFT_ENABLED: "1",
  35. OTEL_EXPORTER_OTLP_ENDPOINT: endpoint,
  36. OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: `${endpoint}/v1/traces`,
  37. OTEL_EXPORTER_OTLP_METRICS_ENDPOINT: `${endpoint}/v1/metrics`,
  38. OTEL_EXPORTER_OTLP_HEADERS: "",
  39. OTEL_EXPORTER_OTLP_TRACES_HEADERS: "",
  40. OTEL_EXPORTER_OTLP_METRICS_HEADERS: "",
  41. };
  42. const previous = Object.fromEntries(Object.keys(patch).map((key) => [key, process.env[key]]));
  43. Object.assign(process.env, patch);
  44. return async () => {
  45. for (const [key, value] of Object.entries(previous)) {
  46. if (value === undefined) delete process.env[key];
  47. else process.env[key] = value;
  48. }
  49. if (child.exitCode !== null || child.signalCode !== null) return;
  50. const exited = once(child, "exit");
  51. child.kill("SIGTERM");
  52. await exited;
  53. };
  54. }
  55. export function ttftReceiverUrl(path: "/records" | "/reset"): string {
  56. const endpoint = process.env.OTEL_EXPORTER_OTLP_ENDPOINT;
  57. if (!endpoint) throw new Error("TTFT worker 未启动隔离 OTLP 接收器");
  58. return `${endpoint}${path}`;
  59. }