java_contract_parity.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. r"""P12-A:Java 后端迁移的**裁判**——契约端点逐一比对 Java 与 Python 的响应。
  4. 用途(与前端对拍门同思路:门禁当裁判,逐条收敛):
  5. · 读冻契约 `app_backEnd/.../contract/http_api_v1.json`(42 条);
  6. · 对每条端点,分别请求 Python 侧与 Java 侧,做**深度相等**比较(JSON 归一化后);
  7. · 输出计分板:`已一致 / 有差异 / Java 未实现`,并把"必须一致"的端点清单交给 `--require` 用于门禁。
  8. 用法:
  9. python scripts/java_contract_parity.py [--gateway URL] [--python-base /detail] [--java-base /java]
  10. [--require kpi,fleet,...] [--limit N]
  11. [--java-kinds detail_api]
  12. ★预热:比对前两侧各 GET 一次(丢弃结果)再取第二次 —— 带"按窗重算/进程内缓存"的端点(如 /api/fleet)
  13. 冷启时点不同会报假差异(实逮 13≠15,预热后均 15)。
  14. """
  15. from __future__ import annotations
  16. import argparse
  17. import json
  18. import pathlib
  19. import sys
  20. import urllib.error
  21. import urllib.request
  22. ROOT = pathlib.Path(__file__).resolve().parents[1]
  23. CONTRACT = ROOT / 'app_backEnd/app_backEnd_guanlan/contract/http_api_v1.json'
  24. def get(url: str, timeout: float = 60.0):
  25. req = urllib.request.Request(url, headers={'Accept': 'application/json'})
  26. try:
  27. with urllib.request.urlopen(req, timeout=timeout) as r:
  28. body = r.read().decode('utf-8', 'replace')
  29. try:
  30. return r.status, json.loads(body)
  31. except Exception:
  32. return r.status, body[:400]
  33. except urllib.error.HTTPError as e:
  34. return e.code, (e.read().decode('utf-8', 'replace')[:200])
  35. except Exception as e: # noqa: BLE001
  36. return 0, f'{type(e).__name__}: {e}'
  37. def norm(x):
  38. """比较用归一化:字典按键排序;列表保序(顺序也是行为)。"""
  39. if isinstance(x, dict):
  40. return {k: norm(v) for k, v in sorted(x.items())}
  41. if isinstance(x, list):
  42. return [norm(v) for v in x]
  43. return x
  44. def first_diff(a, b, path='$', depth=0):
  45. if depth > 6:
  46. return None
  47. if type(a) is not type(b) and not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
  48. return f'{path}: 类型 {type(a).__name__} ≠ {type(b).__name__}'
  49. if isinstance(a, dict):
  50. for k in sorted(set(a) | set(b)):
  51. if k not in a:
  52. return f'{path}.{k}: Java 多键'
  53. if k not in b:
  54. return f'{path}.{k}: Java 缺键'
  55. d = first_diff(a[k], b[k], f'{path}.{k}', depth + 1)
  56. if d:
  57. return d
  58. return None
  59. if isinstance(a, list):
  60. if len(a) != len(b):
  61. return f'{path}: 长度 {len(a)} ≠ {len(b)}'
  62. for i, (x, y) in enumerate(zip(a, b)):
  63. d = first_diff(x, y, f'{path}[{i}]', depth + 1)
  64. if d:
  65. return d
  66. return None
  67. if a != b:
  68. sa, sb = str(a), str(b)
  69. return f'{path}: {sa[:60]!r} ≠ {sb[:60]!r}'
  70. return None
  71. # 登记忽略字段(每条都要写理由;只忽略"有状态"字段,不忽略实现口径)。
  72. #
  73. # `/api/reload` 的 `old_stamp` = 清缓存**前**的产物指纹 —— 取决于比对顺序与两侧各自的缓存状态:
  74. # 先被问的一侧缓存里有指纹(返回字符串),后被问的一侧可能已被其它探测清空(None)。
  75. # 其余字段(ok / files / stamp)照常严格比对。
  76. IGNORE_PATHS: dict[str, tuple[str, str]] = {
  77. '/api/reload': ('$.old_stamp', '清缓存前的指纹:取决于比对顺序与各自的缓存状态,非实现差异'),
  78. }
  79. def main() -> int:
  80. ap = argparse.ArgumentParser()
  81. ap.add_argument('--gateway', default='http://127.0.0.1:28084')
  82. ap.add_argument('--python-base', default='/detail')
  83. ap.add_argument('--java-base', default='/java')
  84. ap.add_argument('--require', default='', help='逗号分隔:这些端点必须一致,否则退出码 1')
  85. ap.add_argument('--limit', type=int, default=0)
  86. ap.add_argument('--java-kinds', default='detail_api',
  87. help='哪些 kind 属于 Java 后端迁移范围(默认 detail_api;逗号分隔)')
  88. a = ap.parse_args()
  89. contract = json.loads(CONTRACT.read_text(encoding='utf-8'))
  90. eps = contract['endpoints']
  91. rows = eps if isinstance(eps, list) else [dict(path=k, **(v if isinstance(v, dict) else {})) for k, v in eps.items()]
  92. if a.limit:
  93. rows = rows[:a.limit]
  94. java_kinds = {x.strip() for x in a.java_kinds.split(',') if x.strip()}
  95. same, diff, missing, skipped, other, unsettled, ignored = [], [], [], [], [], [], []
  96. scope_total = 0
  97. for e in rows:
  98. path = str(e.get('path') or e.get('url'))
  99. method = str(e.get('method') or 'GET').upper()
  100. kind = str(e.get('kind') or '?')
  101. if kind not in java_kinds:
  102. other.append((path, kind))
  103. continue
  104. scope_total += 1
  105. if method != 'GET':
  106. skipped.append((path, 'POST 类端点本轮不自动比(需构造请求体)'))
  107. continue
  108. # ★ 一律真的问两侧:Java 走 /java 前缀、Python 走 /detail 前缀(灰度期两个并存入口)
  109. jurl = a.gateway.rstrip('/') + a.java_base + path
  110. purl = a.gateway.rstrip('/') + a.python_base + path
  111. # ★预热:该端点可能带"按窗重算 + 进程内缓存"(如 /api/fleet、/api/curves),
  112. # 冷启时点不同会报假差异。做法:各取一次丢弃结果 → 若仍有 *_pending=true 就轮询到落定 → 再比第二次。
  113. get(jurl)
  114. get(purl)
  115. # 再各取一次:对 /api/reload 这类**清缓存副作用**端点,连比两次会让"先比的一侧"持有旧指纹、
  116. # 后比的一侧为 None(实逮 old_stamp str ≠ None)⇒ 两次预热后两侧都处于"刚清过"的稳态。
  117. get(jurl)
  118. get(purl)
  119. def pending(x):
  120. if isinstance(x, dict):
  121. if x.get('building') is True: # 曲线等服务端后台算时的"建设中"标记
  122. return True
  123. return any(str(k).endswith('_pending') and v is True for k, v in x.items()) \
  124. or any(pending(v) for v in x.values())
  125. if isinstance(x, list):
  126. return any(pending(v) for v in x)
  127. return False
  128. settled = True
  129. for _ in range(20):
  130. js, jb = get(jurl)
  131. ps, pb = get(purl)
  132. if not pending(jb) and not pending(pb):
  133. settled = True
  134. break
  135. settled = False
  136. import time as _t
  137. _t.sleep(15)
  138. if not settled:
  139. unsettled.append((path, '两侧未在等待上限内落定(按窗重算仍在跑)—— 时点问题,不计为差异'))
  140. continue
  141. # ★只按 HTTP 状态判定(曾按正文里是否有 "404" 判 ⇒ 把"已实现但正文含该字样"的端点误判为未实现)
  142. if js in (0, 404):
  143. missing.append((path, f'Java HTTP {js}'))
  144. continue
  145. if js != 200 or ps != 200:
  146. diff.append((path, f'HTTP Java {js} / Python {ps}'))
  147. continue
  148. d = first_diff(norm(jb), norm(pb))
  149. if d and path in IGNORE_PATHS and d.startswith(IGNORE_PATHS[path][0]):
  150. ignored.append((path, IGNORE_PATHS[path][0], IGNORE_PATHS[path][1]))
  151. same.append(path)
  152. elif d:
  153. diff.append((path, d))
  154. else:
  155. same.append(path)
  156. print('Java ↔ Python 契约端点比对(裁判:冻契约 %d 条;Java 范围 kind=%s 共 %d 条)'
  157. % (len(rows), ','.join(sorted(java_kinds)), scope_total))
  158. print(' 一致 %d/%d · 有差异 %d · 未实现 %d · 跳过 %d · 未落定 %d(范围外 %d 条:%s)\n'
  159. % (len(same), scope_total, len(diff), len(missing), len(skipped), len(unsettled), len(other),
  160. ', '.join(sorted({k for _, k in other})) or '-'))
  161. if same:
  162. print(' [一致] ' + ', '.join(same[:12]) + (' …' if len(same) > 12 else ''))
  163. for p, why in diff[:10]:
  164. print(' [差异] %-28s %s' % (p, why))
  165. for p, why in missing[:10]:
  166. print(' [未实现] %-26s %s' % (p, why))
  167. for p, why in skipped[:6]:
  168. print(' [跳过] %-28s %s' % (p, why))
  169. for p, why in unsettled[:6]:
  170. print(' [未落定] %-26s %s' % (p, why))
  171. for p, f, why in ignored[:6]:
  172. print(' [登记忽略] %-24s %s —— %s' % (p, f, why))
  173. need = [x.strip() for x in a.require.split(',') if x.strip()]
  174. bad = [p for p in need if p not in same]
  175. if need:
  176. print('\n门禁要求一致 %d 条 → %s' % (len(need), '通过' if not bad else '未通过: ' + ', '.join(bad)))
  177. print('\n结论: %s' % ('Java 范围端点全部一致' if not diff and not missing else
  178. '迁移进行中(%d/%d 已一致)' % (len(same), scope_total)))
  179. return 0 if not bad else 1
  180. if __name__ == '__main__':
  181. raise SystemExit(main())