telemetry-field-contract.mjs 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import { execFile } from "node:child_process";
  2. import { randomUUID } from "node:crypto";
  3. import { mkdir, open, readFile, rename, rm, writeFile } from "node:fs/promises";
  4. import { join } from "node:path";
  5. import { fileURLToPath } from "node:url";
  6. import { promisify } from "node:util";
  7. import ts from "typescript";
  8. import { format } from "oxfmt";
  9. const exec = promisify(execFile);
  10. const DEFAULT_ROOT = fileURLToPath(new URL("../../../../", import.meta.url));
  11. const DEFAULT_CONTRACT = fileURLToPath(
  12. new URL(
  13. "../../test/e2e/fixtures/telemetry/agent-step-message-scope-fields.json",
  14. import.meta.url,
  15. ),
  16. );
  17. const fieldName = /^[a-z][a-z0-9_]*$/u;
  18. const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
  19. async function loadContract(path) {
  20. const contract = JSON.parse(await readFile(path, "utf8"));
  21. if (contract.version !== 1 || !isRecord(contract.events)) throw new Error("非法埋点字段合同");
  22. for (const [event, rule] of Object.entries(contract.events)) {
  23. if (
  24. !fieldName.test(event) ||
  25. !isRecord(rule) ||
  26. !Array.isArray(rule.required) ||
  27. !Array.isArray(rule.optional) ||
  28. !isRecord(rule.additions) ||
  29. ![...rule.required, ...rule.optional, ...Object.keys(rule.additions)].every(
  30. (key) => typeof key === "string" && fieldName.test(key),
  31. )
  32. )
  33. throw new Error("非法埋点字段合同: " + event);
  34. }
  35. return contract;
  36. }
  37. function inspect(records, contract) {
  38. const errors = [];
  39. const additions = new Map();
  40. for (const [index, record] of records.entries()) {
  41. const event = record?.element_name;
  42. if (!Object.hasOwn(contract.events, event)) {
  43. errors.push("UNKNOWN_EVENT: record[" + index + "]");
  44. continue;
  45. }
  46. const rule = contract.events[event];
  47. const detail = record.event_extra_detail;
  48. if (!isRecord(detail)) {
  49. errors.push("TYPE_MISMATCH: " + event + ".event_extra_detail");
  50. continue;
  51. }
  52. for (const key of rule.required) {
  53. if (!Object.hasOwn(detail, key)) errors.push("MISSING_FIELD: " + event + "." + key);
  54. }
  55. const known = new Set([...rule.required, ...rule.optional, ...Object.keys(rule.additions)]);
  56. for (const [key, value] of Object.entries(detail)) {
  57. if (typeof value !== "string") errors.push("TYPE_MISMATCH: " + event + "." + key);
  58. if (!known.has(key))
  59. additions.set(event + "." + key, { event, field: key, status: "unverified" });
  60. }
  61. }
  62. return { errors: [...new Set(errors)].sort(), additions: [...additions.values()] };
  63. }
  64. const addedLines = (diff) =>
  65. diff
  66. .split("\n")
  67. .filter((line) => line.startsWith("+") && !line.startsWith("+++"))
  68. .map((line) => line.slice(1))
  69. .join("\n");
  70. function addedLineNumbers(diff) {
  71. const result = new Set();
  72. let line = 0;
  73. for (const text of diff.split("\n")) {
  74. const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/u.exec(text);
  75. if (hunk) line = Number(hunk[1]);
  76. else if (text.startsWith("+") && !text.startsWith("+++")) result.add(line++);
  77. else if (text.startsWith(" ")) line++;
  78. }
  79. return result;
  80. }
  81. function definitionLines(text, path, field) {
  82. const source = ts.createSourceFile(path, text, ts.ScriptTarget.Latest, true);
  83. const lines = [];
  84. const visit = (node) => {
  85. // 读取语法节点,避免注释、字符串、类型声明中的同名字段被当成生产赋值。
  86. if (
  87. (ts.isPropertyAssignment(node) || ts.isShorthandPropertyAssignment(node)) &&
  88. (ts.isIdentifier(node.name) || ts.isStringLiteral(node.name)) &&
  89. node.name.text === field
  90. ) {
  91. lines.push(source.getLineAndCharacterOfPosition(node.name.getStart(source)).line + 1);
  92. }
  93. ts.forEachChild(node, visit);
  94. };
  95. visit(source);
  96. return lines;
  97. }
  98. async function findEvidence(repoRoot, event, field) {
  99. // 字段名只作数据,不拼 shell;无法识别的动态 key 保留告知,不尝试猜测来源。
  100. if (!fieldName.test(field)) return undefined;
  101. const git = async (...args) =>
  102. (
  103. await exec("git", args, {
  104. cwd: repoRoot,
  105. timeout: 10_000,
  106. maxBuffer: 4 * 1024 * 1024,
  107. })
  108. ).stdout;
  109. const hasField = (text) => new RegExp("\\b" + field + "\\b").test(text);
  110. const documentsEvent = (text) =>
  111. text
  112. .split(/\n\s*\n/u)
  113. .some(
  114. (paragraph) => hasField(paragraph) && new RegExp("\\b" + event + "\\b").test(paragraph),
  115. );
  116. const commits = (
  117. await git(
  118. "log",
  119. "HEAD",
  120. "--no-merges",
  121. "--format=%H",
  122. "-30",
  123. "-G",
  124. field,
  125. "--",
  126. "packages/*/src",
  127. "docs/monitoring",
  128. )
  129. )
  130. .trim()
  131. .split("\n")
  132. .filter(Boolean);
  133. for (const commit of commits) {
  134. const paths = (await git("diff-tree", "--root", "--no-commit-id", "--name-only", "-r", commit))
  135. .trim()
  136. .split("\n");
  137. let source;
  138. let document;
  139. for (const path of paths) {
  140. const production =
  141. /^packages\/[^/]+\/src\/.+\.[cm]?[jt]sx?$/u.test(path) &&
  142. !/(?:^|\/)(?:test|tests|__tests__)(?:\/)|\.(?:test|spec)\./u.test(path);
  143. const spec = path.startsWith("docs/monitoring/") && path.endsWith(".md");
  144. if (!production && !spec) continue;
  145. const diff = await git("show", "--format=", "--unified=0", commit, "--", path);
  146. const added = addedLines(diff);
  147. if (!hasField(added)) continue;
  148. let current;
  149. try {
  150. current = await readFile(join(repoRoot, path), "utf8");
  151. } catch {
  152. continue;
  153. }
  154. if (production && definitionLines(current, path, field).length) {
  155. const changedLines = addedLineNumbers(diff);
  156. const original = await git("show", commit + ":" + path);
  157. if (definitionLines(original, path, field).some((line) => changedLines.has(line)))
  158. source ??= path;
  159. }
  160. if (
  161. spec &&
  162. documentsEvent(added) &&
  163. documentsEvent(await git("show", commit + ":" + path)) &&
  164. documentsEvent(current)
  165. )
  166. document ??= path;
  167. }
  168. if (source && document) return { commit, source, document };
  169. }
  170. return undefined;
  171. }
  172. async function mergeVerified(contractPath, candidates) {
  173. const verified = candidates.filter((entry) => entry.status === "verified");
  174. if (!verified.length) return;
  175. let lock;
  176. let temporary;
  177. try {
  178. // 只持锁重读后合并自己的新增项;并发运行不等待、不覆盖别人的归并结果。
  179. lock = await open(contractPath + ".lock", "wx");
  180. const contract = await loadContract(contractPath);
  181. for (const entry of verified) {
  182. const rule = contract.events[entry.event];
  183. if (
  184. !rule.required.includes(entry.field) &&
  185. !rule.optional.includes(entry.field) &&
  186. !Object.hasOwn(rule.additions, entry.field)
  187. )
  188. rule.additions[entry.field] = entry.evidence;
  189. }
  190. temporary = contractPath + "." + randomUUID() + ".tmp";
  191. const formatted = await format(contractPath, JSON.stringify(contract));
  192. if (formatted.errors.length) throw new Error("字段合同格式化失败");
  193. await writeFile(temporary, formatted.code);
  194. await rename(temporary, contractPath);
  195. for (const entry of verified) entry.status = "merged";
  196. } catch (error) {
  197. for (const entry of verified) {
  198. entry.status = "deferred";
  199. entry.reason = "合同未写入: " + (error.code ?? error.name);
  200. }
  201. } finally {
  202. if (temporary) await rm(temporary, { force: true });
  203. if (lock) {
  204. await lock.close();
  205. await rm(contractPath + ".lock", { force: true });
  206. }
  207. }
  208. }
  209. /**
  210. * 日常回归允许字段扩展;双版本严格 comparator 独立保留。
  211. * 调用方应先通过事件数量、消息关联等业务断言,避免把失败样本自动纳入合同。
  212. */
  213. export async function auditTelemetryFields({
  214. records,
  215. contractPath = DEFAULT_CONTRACT,
  216. repoRoot = DEFAULT_ROOT,
  217. artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR,
  218. sync = process.env.ZCODE_E2E_TELEMETRY_FIELD_SYNC !== "0",
  219. }) {
  220. const result = inspect(records, await loadContract(contractPath));
  221. if (!result.errors.length) {
  222. for (const entry of result.additions) {
  223. try {
  224. entry.evidence = await findEvidence(repoRoot, entry.event, entry.field);
  225. if (entry.evidence) entry.status = "verified";
  226. else entry.reason = "未找到同提交的生产字段赋值与对应事件 spec";
  227. } catch {
  228. entry.reason = "Git 历史不可用或查询失败";
  229. }
  230. }
  231. if (sync) await mergeVerified(contractPath, result.additions);
  232. }
  233. for (const entry of result.additions) {
  234. console.warn(
  235. "[telemetry-fields] 新增字段 " +
  236. entry.event +
  237. "." +
  238. entry.field +
  239. " [" +
  240. entry.status +
  241. "] " +
  242. (entry.evidence?.commit ?? entry.reason ?? "合同校验失败,未归并"),
  243. );
  244. }
  245. if (artifactDir) {
  246. await mkdir(artifactDir, { recursive: true });
  247. await writeFile(
  248. join(artifactDir, "telemetry-field-audit.json"),
  249. JSON.stringify({ version: 1, ...result }, null, 2) + "\n",
  250. );
  251. }
  252. return result;
  253. }