java_contract_parity.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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 get_bytes(url: str, timeout: float = 900.0):
  38. """取原始字节(二进制端点用);失败返回 None。"""
  39. import urllib.error
  40. import urllib.request
  41. try:
  42. with urllib.request.urlopen(urllib.request.Request(url), timeout=timeout) as r:
  43. return r.read()
  44. except Exception: # noqa: BLE001
  45. return None
  46. def post_json(url: str, payload: dict, timeout: float = 300.0):
  47. """POST JSON(裁判的 POST 能力):返回 (status, 解析后的 JSON 或错误文本)。"""
  48. import urllib.error
  49. import urllib.request
  50. data = json.dumps(payload).encode('utf-8')
  51. req = urllib.request.Request(url, data=data, headers={'Content-Type': 'application/json'})
  52. try:
  53. with urllib.request.urlopen(req, timeout=timeout) as r:
  54. body = r.read().decode('utf-8', 'replace')
  55. try:
  56. return r.status, json.loads(body)
  57. except Exception: # noqa: BLE001
  58. return r.status, body[:300]
  59. except urllib.error.HTTPError as e:
  60. return e.code, e.read().decode('utf-8', 'replace')[:300]
  61. except Exception as e: # noqa: BLE001
  62. return 0, '%s: %s' % (type(e).__name__, e)
  63. def norm(x):
  64. """比较用归一化:字典按键排序;列表保序(顺序也是行为)。"""
  65. if isinstance(x, dict):
  66. return {k: norm(v) for k, v in sorted(x.items())}
  67. if isinstance(x, list):
  68. return [norm(v) for v in x]
  69. return x
  70. def doc_text(b: bytes) -> str | None:
  71. """Office(zip) 文档 → 归一化文本:剔除时间戳/文档属性后逐条目拼接(用于二进制端点的等价判定)。"""
  72. if not b[:2] == b'PK':
  73. return None
  74. import io
  75. import re as _re
  76. import zipfile
  77. out = []
  78. with zipfile.ZipFile(io.BytesIO(b)) as z:
  79. for name in sorted(z.namelist()):
  80. if name.endswith('.xml') or name.endswith('.rels'):
  81. s = z.read(name).decode('utf-8', 'replace')
  82. s = _re.sub(r'<dcterms:(created|modified)[^>]*>[^<]*</dcterms:\1>', '', s)
  83. s = _re.sub(r'<cp:lastModifiedBy>[^<]*</cp:lastModifiedBy>', '', s)
  84. s = _re.sub(r'<TotalTime>[^<]*</TotalTime>', '', s)
  85. out.append(name + '\n' + s)
  86. return '\n'.join(out)
  87. def first_diff(a, b, path='$', depth=0):
  88. if depth > 6:
  89. return None
  90. if type(a) is not type(b) and not (isinstance(a, (int, float)) and isinstance(b, (int, float))):
  91. return f'{path}: 类型 {type(a).__name__} ≠ {type(b).__name__}'
  92. if isinstance(a, dict):
  93. for k in sorted(set(a) | set(b)):
  94. if k not in a:
  95. return f'{path}.{k}: Java 多键'
  96. if k not in b:
  97. return f'{path}.{k}: Java 缺键'
  98. d = first_diff(a[k], b[k], f'{path}.{k}', depth + 1)
  99. if d:
  100. return d
  101. return None
  102. if isinstance(a, list):
  103. if len(a) != len(b):
  104. return f'{path}: 长度 {len(a)} ≠ {len(b)}'
  105. for i, (x, y) in enumerate(zip(a, b)):
  106. d = first_diff(x, y, f'{path}[{i}]', depth + 1)
  107. if d:
  108. return d
  109. return None
  110. if a != b:
  111. sa, sb = str(a), str(b)
  112. return f'{path}: {sa[:60]!r} ≠ {sb[:60]!r}'
  113. return None
  114. # 登记忽略字段(每条都要写理由;只忽略"有状态"字段,不忽略实现口径)。
  115. #
  116. # `/api/reload` 的 `old_stamp` = 清缓存**前**的产物指纹 —— 取决于比对顺序与两侧各自的缓存状态:
  117. # 先被问的一侧缓存里有指纹(返回字符串),后被问的一侧可能已被其它探测清空(None)。
  118. # 其余字段(ok / files / stamp)照常严格比对。
  119. IGNORE_PATHS: dict[str, tuple[str, str]] = {
  120. '/api/reload': ('$.old_stamp', '清缓存前的指纹:取决于比对顺序与各自的缓存状态,非实现差异'),
  121. }
  122. def main() -> int:
  123. ap = argparse.ArgumentParser()
  124. ap.add_argument('--gateway', default='http://127.0.0.1:28084')
  125. ap.add_argument('--python-base', default='/detail')
  126. ap.add_argument('--java-base', default='/java')
  127. ap.add_argument('--require', default='', help='逗号分隔:这些端点必须一致,否则退出码 1')
  128. ap.add_argument('--limit', type=int, default=0)
  129. ap.add_argument('--java-kinds', default='detail_api',
  130. help='哪些 kind 属于 Java 后端迁移范围(默认 detail_api;逗号分隔)')
  131. a = ap.parse_args()
  132. contract = json.loads(CONTRACT.read_text(encoding='utf-8'))
  133. eps = contract['endpoints']
  134. rows = eps if isinstance(eps, list) else [dict(path=k, **(v if isinstance(v, dict) else {})) for k, v in eps.items()]
  135. if a.limit:
  136. rows = rows[:a.limit]
  137. java_kinds = {x.strip() for x in a.java_kinds.split(',') if x.strip()}
  138. same, diff, missing, skipped, other, unsettled, ignored = [], [], [], [], [], [], []
  139. scope_total = 0
  140. for e in rows:
  141. path = str(e.get('path') or e.get('url'))
  142. method = str(e.get('method') or 'GET').upper()
  143. kind = str(e.get('kind') or '?')
  144. if kind not in java_kinds:
  145. other.append((path, kind))
  146. continue
  147. scope_total += 1
  148. # ★ 一律真的问两侧:Java 走 /java 前缀、Python 走 /detail 前缀(灰度期两个并存入口)
  149. jurl = a.gateway.rstrip('/') + a.java_base + path
  150. purl = a.gateway.rstrip('/') + a.python_base + path
  151. if method != 'GET':
  152. # ★POST 能力(P12):按"契约抓取时的最小请求"发空体 {} —— 两侧都应回同样的错误语义
  153. # (如 /api/ask 空问题 ⇒ {err: 问题为空})。请求体若将来需要参数,再按契约补。
  154. js, jb = post_json(jurl, {})
  155. ps, pb = post_json(purl, {})
  156. if js in (0, 404):
  157. missing.append((path, 'Java HTTP %s' % js))
  158. continue
  159. d = first_diff(norm(jb), norm(pb))
  160. if d:
  161. diff.append((path, d))
  162. else:
  163. same.append(path)
  164. continue
  165. # ★二进制端点(契约 ctype 非 JSON,如 /api/rpt_export 的 docx):走"字节 + 解包文本"比对
  166. ctype = str(e.get('ctype') or '')
  167. if ctype and 'json' not in ctype.lower():
  168. jb_b = get_bytes(jurl)
  169. pb_b = get_bytes(purl)
  170. if jb_b is None or pb_b is None:
  171. diff.append((path, 'Java 或 Python 未返回字节(HTTP %s/%s)' % (jb_b, pb_b)))
  172. continue
  173. tj, tp = doc_text(jb_b), doc_text(pb_b)
  174. if tj is not None and tp is not None:
  175. if tj == tp:
  176. same.append(path)
  177. else:
  178. d = first_diff({'t': tj}, {'t': tp})
  179. diff.append((path, '解包文本不一致:' + str(d)[:120]))
  180. else:
  181. diff.append((path, '非 zip 字节:Java %d B / Python %d B' % (len(jb_b), len(pb_b))))
  182. continue
  183. # ★预热:该端点可能带"按窗重算 + 进程内缓存"(如 /api/fleet、/api/curves),
  184. # 冷启时点不同会报假差异。做法:各取一次丢弃结果 → 若仍有 *_pending=true 就轮询到落定 → 再比第二次。
  185. get(jurl)
  186. get(purl)
  187. # 再各取一次:对 /api/reload 这类**清缓存副作用**端点,连比两次会让"先比的一侧"持有旧指纹、
  188. # 后比的一侧为 None(实逮 old_stamp str ≠ None)⇒ 两次预热后两侧都处于"刚清过"的稳态。
  189. get(jurl)
  190. get(purl)
  191. def pending(x):
  192. if isinstance(x, dict):
  193. if x.get('building') is True: # 曲线等服务端后台算时的"建设中"标记
  194. return True
  195. return any(str(k).endswith('_pending') and v is True for k, v in x.items()) \
  196. or any(pending(v) for v in x.values())
  197. if isinstance(x, list):
  198. return any(pending(v) for v in x)
  199. return False
  200. settled = True
  201. for _ in range(20):
  202. js, jb = get(jurl)
  203. ps, pb = get(purl)
  204. if not pending(jb) and not pending(pb):
  205. settled = True
  206. break
  207. settled = False
  208. import time as _t
  209. _t.sleep(15)
  210. if not settled:
  211. unsettled.append((path, '两侧未在等待上限内落定(按窗重算仍在跑)—— 时点问题,不计为差异'))
  212. continue
  213. # ★只按 HTTP 状态判定(曾按正文里是否有 "404" 判 ⇒ 把"已实现但正文含该字样"的端点误判为未实现)
  214. if js in (0, 404):
  215. missing.append((path, f'Java HTTP {js}'))
  216. continue
  217. if js != 200 or ps != 200:
  218. diff.append((path, f'HTTP Java {js} / Python {ps}'))
  219. continue
  220. d = first_diff(norm(jb), norm(pb))
  221. if d and path in IGNORE_PATHS and d.startswith(IGNORE_PATHS[path][0]):
  222. ignored.append((path, IGNORE_PATHS[path][0], IGNORE_PATHS[path][1]))
  223. same.append(path)
  224. elif d:
  225. diff.append((path, d))
  226. else:
  227. same.append(path)
  228. print('Java ↔ Python 契约端点比对(裁判:冻契约 %d 条;Java 范围 kind=%s 共 %d 条)'
  229. % (len(rows), ','.join(sorted(java_kinds)), scope_total))
  230. print(' 一致 %d/%d · 有差异 %d · 未实现 %d · 跳过 %d · 未落定 %d(范围外 %d 条:%s)\n'
  231. % (len(same), scope_total, len(diff), len(missing), len(skipped), len(unsettled), len(other),
  232. ', '.join(sorted({k for _, k in other})) or '-'))
  233. if same:
  234. print(' [一致] ' + ', '.join(same[:12]) + (' …' if len(same) > 12 else ''))
  235. for p, why in diff[:10]:
  236. print(' [差异] %-28s %s' % (p, why))
  237. for p, why in missing[:10]:
  238. print(' [未实现] %-26s %s' % (p, why))
  239. for p, why in skipped[:6]:
  240. print(' [跳过] %-28s %s' % (p, why))
  241. for p, why in unsettled[:6]:
  242. print(' [未落定] %-26s %s' % (p, why))
  243. for p, f, why in ignored[:6]:
  244. print(' [登记忽略] %-24s %s —— %s' % (p, f, why))
  245. need = [x.strip() for x in a.require.split(',') if x.strip()]
  246. bad = [p for p in need if p not in same]
  247. if need:
  248. print('\n门禁要求一致 %d 条 → %s' % (len(need), '通过' if not bad else '未通过: ' + ', '.join(bad)))
  249. print('\n结论: %s' % ('Java 范围端点全部一致' if not diff and not missing else
  250. '迁移进行中(%d/%d 已一致)' % (len(same), scope_total)))
  251. return 0 if not bad else 1
  252. if __name__ == '__main__':
  253. raise SystemExit(main())