Spaces:
Running

File size: 8,772 Bytes
41979ae
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
#!/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())