Spaces:
Running

MeloonTop / backend /tools /contract_diff.py
isold's picture
update
41979ae
Raw History Blame Contribute Delete
8.77 kB
#!/usr/bin/env python3
"""Frontend <-> backend route contract diff for the Meloon monorepo.
Extracts every HTTP call the three product frontends make, normalises it into a
FastAPI route template, and diffs it against the routes registered on the merged
FastAPI app (``app.main:app``). Method-aware, so a ``PUT /api/papers/{id}``
frontend call will not silently match a ``GET /api/papers/{id}`` backend route.
Supported frontend call styles:
* ``fetch(`${BASE}/api/x/${id}`, { method: 'PUT' })`` (MeloonTop, MeloonExam)
* ``fetch(url.toString())`` where ``url = new URL(`${BASE}/api/x`)``
* ``this.request<T>('/x/${id}', { method: 'DELETE' })`` (MeloonChatBI, relative
to a per-product API base)
Usage::
/Users/liwei/pri/venv/bin/python backend/tools/contract_diff.py
Exit code 0 when every frontend call maps onto a real backend route+method.
"""
from __future__ import annotations
import re
import sys
from pathlib import Path
BACKEND_DIR = Path(__file__).resolve().parents[1]
PROJECT_DIR = BACKEND_DIR.parent
sys.path.insert(0, str(BACKEND_DIR))
FRONTENDS = {
"MeloonExam": {
"roots": [PROJECT_DIR / "frontend/MeloonExam/src"],
"api_base": None,
},
"MeloonTop": {
"roots": [PROJECT_DIR / "frontend/MeloonTop"],
"api_base": None,
},
"MeloonChatBI": {
"roots": [PROJECT_DIR / "frontend/MeloonChatBI"],
"api_base": "/api/v1",
},
}
SKIP_DIRS = {"node_modules", "dist", "build", ".git", "coverage", ".next"}
SKIP_FILES = {
"vite.config.ts",
"vite.config.js",
"fastapiBackendCode.ts",
"fastapiBackendCode.js",
}
# Callee forms that issue an HTTP request.
CALL_RE = re.compile(r"(?:fetch|\.request(?:<[^>]*>)?)\s*\(")
STRING_LITERAL_RE = re.compile(r"`([^`]*)`|'([^']*)'|\"([^\"]*)\"")
API_LITERAL_RE = re.compile(r"/api/[A-Za-z0-9_\-./${}%]*")
TEMPLATE_PARAM_RE = re.compile(r"\$\{[^}]*\}")
METHOD_RE = re.compile(r"""method\s*:\s*['"](\w+)['"]""")
# ``/api/users/me/score-history${x ? `?a=b` : ''}`` -> drop the query part.
QUERY_TAIL_RE = re.compile(r"[?&].*$")
WINDOW = 1600
BACKSCAN = 700
def balanced_args(text: str, open_idx: int) -> str:
"""Return the argument text of the call whose ``(`` is at ``open_idx``."""
depth = 0
for i in range(open_idx, min(len(text), open_idx + WINDOW)):
ch = text[i]
if ch == "(":
depth += 1
elif ch == ")":
depth -= 1
if depth == 0:
return text[open_idx + 1 : i]
return text[open_idx + 1 : open_idx + WINDOW]
def normalise(raw: str, api_base: str | None) -> str | None:
"""Turn a captured URL/path literal into a route template, or None."""
url = raw.strip()
url = url.split("?")[0].split("#")[0]
if "/api/" in url:
url = url[url.index("/api/") :]
elif api_base and url.startswith("/"):
url = api_base + url
else:
return None
url = TEMPLATE_PARAM_RE.sub("{param}", url)
url = url.rstrip("/") or "/"
if url.count("{") != url.count("}"):
return None
return url
def extract_calls(text: str, api_base: str | None) -> list[tuple[str, str, int]]:
"""[(method, path, line), ...] for one source file."""
out: list[tuple[str, str, int]] = []
prev_end = 0
for call in CALL_RE.finditer(text):
open_idx = call.end() - 1
args = balanced_args(text, open_idx)
method_match = METHOD_RE.search(args)
method = (method_match.group(1) if method_match else "GET").upper()
literals: list[str] = []
for lit in STRING_LITERAL_RE.finditer(args):
raw = next(g for g in lit.groups() if g is not None)
literals.extend(API_LITERAL_RE.findall(raw))
if api_base and re.fullmatch(r"/[A-Za-z0-9_\-/${}.]*", raw):
literals.append(raw)
if not literals:
# ``const url = new URL(`${BASE}/api/x`)`` sits just above the call.
# Bound the backscan to the gap since the previous request call so
# we never attribute an earlier call's URL to this one.
back = text[max(prev_end, call.start() - BACKSCAN) : call.start()]
for lit in STRING_LITERAL_RE.finditer(back):
raw = next(g for g in lit.groups() if g is not None)
literals.extend(API_LITERAL_RE.findall(raw))
prev_end = open_idx + len(args) + 1
line = text[: call.start()].count("\n") + 1
for lit in literals:
path = normalise(lit, api_base)
if path:
out.append((method, path, line))
return out
def backend_routes() -> dict[str, set[str]]:
from app.main import app
routes: dict[str, set[str]] = {}
for route in app.routes:
methods = getattr(route, "methods", None)
if not methods:
continue
path = getattr(route, "path", "")
if not path.startswith("/api/"):
continue
routes.setdefault(path.rstrip("/") or "/", set()).update(
m for m in methods if m not in ("HEAD", "OPTIONS")
)
return routes
def frontend_calls() -> dict[str, list[tuple[str, str, str]]]:
"""product -> [(method, path, source_location), ...]"""
found: dict[str, list[tuple[str, str, str]]] = {}
for product, cfg in FRONTENDS.items():
calls: list[tuple[str, str, str]] = []
for root in cfg["roots"]:
if not root.exists():
continue
for src in sorted(root.rglob("*")):
if src.suffix not in (".ts", ".tsx", ".js", ".jsx"):
continue
if any(part in SKIP_DIRS for part in src.parts):
continue
if src.name in SKIP_FILES:
continue
try:
text = src.read_text(encoding="utf-8", errors="ignore")
except OSError:
continue
rel = src.relative_to(PROJECT_DIR)
for method, path, line in extract_calls(text, cfg["api_base"]):
calls.append((method, path, f"{rel}:{line}"))
found[product] = calls
return found
def template_matches(template: str, path: str) -> bool:
t_parts = [p for p in template.strip("/").split("/") if p]
p_parts = [p for p in path.strip("/").split("/") if p]
if len(t_parts) != len(p_parts):
return False
for t, p in zip(t_parts, p_parts):
if t.startswith("{") and t.endswith("}"):
continue
if t != p:
return False
return True
def match_route(method: str, path: str, routes: dict[str, set[str]]) -> bool:
return any(
method in methods and template_matches(t, path)
for t, methods in routes.items()
)
def is_base_prefix(path: str, routes: dict[str, set[str]]) -> bool:
"""True when ``path`` is just a base fragment, not a handler of its own."""
prefix = path.rstrip("/") + "/"
return any(t.startswith(prefix) for t in routes)
def find_missing() -> list[tuple[str, str, str, str]]:
"""Return [(product, method, path, source_location), ...] for every call
the frontends make that no backend route answers."""
routes = backend_routes()
missing: list[tuple[str, str, str, str]] = []
for product, calls in frontend_calls().items():
seen: set[tuple[str, str]] = set()
for method, path, where in calls:
key = (method, path)
if key in seen:
continue
seen.add(key)
if match_route(method, path, routes):
continue
if is_base_prefix(path, routes):
continue
missing.append((product, method, path, where))
return missing
def main() -> int:
routes = backend_routes()
missing = find_missing()
total = len(
{
(method, path)
for calls in frontend_calls().values()
for method, path, _ in calls
}
)
print(f"backend routes: {len(routes)}")
print(f"distinct frontend method+path calls: {total}")
print()
if not missing:
print("OK — every frontend call maps onto a registered backend route.")
return 0
print(f"MISSING ({len(missing)}):")
by_product: dict[str, list[tuple[str, str, str]]] = {}
for product, method, path, where in missing:
by_product.setdefault(product, []).append((method, path, where))
for product in sorted(by_product):
print(f"\n [{product}]")
for method, path, where in sorted(by_product[product]):
print(f" {method:6s} {path}")
print(f" <- {where}")
return 1
if __name__ == "__main__":
raise SystemExit(main())