Debian Codegraph @

scripts/well-known-discovery.py

raw
1 #!/usr/bin/env python3
2 """Crawl and snapshot the Cookidoo `.well-known/home` endpoints we depend on.
3
4 Unlike a full recursive crawl of every Cookidoo microservice, this only
5 fetches the services/rels listed in ``cookidoo_api.well_known.ENDPOINT_RELS``
6 -- the same allow-list the library itself uses at runtime to resolve its
7 path templates -- plus a small number of rels in :data:`WATCH_ONLY_RELS`
8 that the library doesn't call but still wants a heads-up on. This keeps the
9 drift-check (and the PRs it opens) scoped to endpoints cookidoo-api cares
10 about, instead of firing on unrelated changes anywhere in Cookidoo's ~27
11 microservices.
12 """
13
14 import json
15 from pathlib import Path
16 import sys
17
18 import requests
19
20 from cookidoo_api.const import LOGIN_PATH
21 from cookidoo_api.well_known import ENDPOINT_RELS
22
23 API_ENDPOINT = "https://cookidoo.de"
24 OUT_DIR = Path("well-known-snapshots")
25 TIMEOUT = 10
26
27 # Rels the drift-check watches for a heads-up even though the library has
28 # no runtime call site for them (see well_known.ENDPOINT_RELS' docstring
29 # for why: resolve_endpoint_paths() is all-or-nothing, so an endpoint we
30 # don't actually call can't live in that runtime allow-list without making
31 # every API call depend on it). Declared in the same
32 # ``rel -> (service, shape_template)`` shape so they're handled identically
33 # by crawl()/diff_links(), just merged in separately from the runtime one.
34 WATCH_ONLY_RELS: dict[str, tuple[str, str]] = {
35 "fint:login": ("profile", LOGIN_PATH),
36 }
37
38
39 def fetch_json(url: str) -> dict:
40 """Fetch JSON document from URL."""
41 r = requests.get(url, timeout=TIMEOUT, headers={"User-Agent": "python/requests"})
42 r.raise_for_status()
43 result: dict = r.json()
44 return result
45
46
47 def crawl(old_snapshot: dict) -> dict:
48 """Fetch the services/rels declared in ENDPOINT_RELS and WATCH_ONLY_RELS.
49
50 Returns a flat mapping of ``"{rel} ({service})" -> href`` for every rel
51 we could resolve, plus an ``"_errors"`` bookkeeping entry listing
52 services that couldn't be fetched at all (not treated as an endpoint
53 change by itself, see :func:`diff_links`).
54
55 When a service's fetch fails, that service's rels are carried over
56 verbatim from ``old_snapshot`` instead of being dropped: a transient
57 outage must not make every one of that service's rels look "removed"
58 (and, once the service recovers, "added" again) to :func:`diff_links`.
59 """
60 all_rels = {**ENDPOINT_RELS, **WATCH_ONLY_RELS}
61 services = sorted({service for service, _template in all_rels.values()})
62 service_links: dict[str, dict] = {}
63 errors: dict[str, str] = {}
64
65 for service in services:
66 url = f"{API_ENDPOINT}/{service}/.well-known/home"
67 print(f"Fetching {url}")
68 try:
69 doc = fetch_json(url)
70 except Exception as e: # noqa: BLE001
71 errors[service] = str(e)
72 continue
73 service_links[service] = doc.get("_links", {})
74
75 result: dict[str, object] = {}
76 for rel, (service, _template) in sorted(all_rels.items()):
77 key = f"{rel} ({service})"
78 if service in errors:
79 if key in old_snapshot:
80 result[key] = old_snapshot[key]
81 continue
82 links = service_links.get(service)
83 if links is None:
84 continue
85 value = links.get(rel)
86 if isinstance(value, dict):
87 href = value.get("href")
88 elif isinstance(value, list) and value and isinstance(value[0], dict):
89 href = value[0].get("href")
90 else:
91 href = None
92 result[key] = href
93
94 if errors:
95 result["_errors"] = errors
96
97 return result
98
99
100 def write_snapshot(data: dict) -> None:
101 """Write the snapshot to disk."""
102 OUT_DIR.mkdir(exist_ok=True)
103 latest = OUT_DIR / "latest.json"
104 latest.write_text(json.dumps(data, indent=2, sort_keys=True), encoding="utf-8")
105 print("Snapshot updated.")
106
107
108 def diff_links(old: dict, new: dict) -> dict:
109 """Diff two name -> href mappings (ignoring the `_errors` bookkeeping key).
110
111 Transient fetch failures (which only affect ``_errors``) are not
112 considered a meaningful, actionable change on their own.
113 """
114 old = {k: v for k, v in old.items() if k != "_errors"}
115 new = {k: v for k, v in new.items() if k != "_errors"}
116
117 old_keys = set(old.keys())
118 new_keys = set(new.keys())
119
120 added = sorted(new_keys - old_keys)
121 removed = sorted(old_keys - new_keys)
122 changed = sorted(k for k in old_keys & new_keys if old[k] != new[k])
123
124 return {"added": added, "removed": removed, "changed": changed}
125
126
127 def main() -> None:
128 """Crawl and snapshot the used well-known endpoints."""
129 latest_path = OUT_DIR / "latest.json"
130 is_first_run = not latest_path.exists()
131 old_snapshot = json.loads(latest_path.read_text()) if not is_first_run else {}
132
133 snapshot = crawl(old_snapshot)
134
135 diff = diff_links(old_snapshot, snapshot)
136 Path("diff-summary.json").write_text(json.dumps(diff, indent=2), encoding="utf-8")
137
138 meaningful_change = bool(diff["added"] or diff["removed"] or diff["changed"])
139
140 # Only rewrite (and thus git-diff) the snapshot file when one of our used
141 # endpoints actually changed, or on the very first run. A snapshot
142 # rewrite caused solely by `_errors` fluctuating (a transient outage)
143 # must not by itself trigger a PR.
144 if meaningful_change or is_first_run:
145 write_snapshot(snapshot)
146 else:
147 print("No changes detected.")
148
149 sys.exit(1 if meaningful_change else 0)
150
151
152 if __name__ == "__main__":
153 main()