From 0617598e210087bf81dc80d14622b77d7182e6e6 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:41:09 +0100 Subject: [PATCH] fix: keep insights readings when one source fails sitegen.insights raised SystemExit with CLI text from inside its fetch functions: a GitHub rate limit after Search Console and GoatCounter had been read ended the run with no report. It now raises SourceUnavailable, also for a missing credential file. site_insights names the source in the report and on stderr and exits 1. A damaged downloads snapshot is a SourceUnreadable, read before any source is fetched. --- scripts/site_insights.py | 29 ++++++++++++++++++---- scripts/sitegen/insights.py | 44 +++++++++++++++++++++++++-------- tests/test_site_insights.py | 49 +++++++++++++++++++++++++++++++++---- wiki/tools.md | 2 +- 4 files changed, 103 insertions(+), 21 deletions(-) diff --git a/scripts/site_insights.py b/scripts/site_insights.py index 63d139089..41ef0d443 100644 --- a/scripts/site_insights.py +++ b/scripts/site_insights.py @@ -45,6 +45,7 @@ from core.paths import DB_FILE, EMULATORS_DIR, REPO_ROOT from sitegen.insights import ( SOURCES, Readings, + SourceUnavailable, collection_names, downloads_snapshot, fetch_github, @@ -76,14 +77,30 @@ def main() -> int: held, declared = collection_names(load_database(str(REPO_ROOT / DB_FILE)), load_emulator_profiles(str(REPO_ROOT / EMULATORS_DIR))) now = dt.datetime.now(dt.timezone.utc) + # Read before any source: a damaged snapshot ended the run after the + # others had been fetched, and their readings were lost. + snapshot = load_snapshot(args.downloads_snapshot) if "github" not in skip else None readings = Readings(start, end, now, held, declared) + # A source that cannot be read is left out and named, the others kept: + # a GitHub rate limit threw away what Search Console had given. + left_out: list[str] = [] if "gsc" not in skip: - readings = replace(readings, queries=fetch_queries(start, end), - previous=fetch_queries(*readings.previous_span)) + try: + readings = replace(readings, queries=fetch_queries(start, end), + previous=fetch_queries(*readings.previous_span)) + except SourceUnavailable as error: + left_out.append(f"Search Console: {error}") if "goatcounter" not in skip: - readings = replace(readings, goat=fetch_goatcounter(start, now.date()), goat_end=now.date()) + try: + readings = replace(readings, goat=fetch_goatcounter(start, now.date()), goat_end=now.date()) + except SourceUnavailable as error: + left_out.append(f"GoatCounter: {error}") if "github" not in skip: - readings = replace(readings, github=fetch_github(), snapshot=load_snapshot(args.downloads_snapshot)) + try: + readings = replace(readings, github=fetch_github(), snapshot=snapshot) + except SourceUnavailable as error: + left_out.append(f"GitHub: {error}") + readings = replace(readings, left_out=tuple(left_out)) text = report(readings) if args.output: args.output.write_text(text, encoding="utf-8") @@ -92,7 +109,9 @@ def main() -> int: sys.stdout.write(text) if readings.github is not None: save_snapshot(args.downloads_snapshot, downloads_snapshot(readings.github["downloads"], now)) - return 0 + for line in left_out: + print(f"Not read, {line}", file=sys.stderr) + return 1 if left_out else 0 if __name__ == "__main__": diff --git a/scripts/sitegen/insights.py b/scripts/sitegen/insights.py index e97644351..703972eb5 100644 --- a/scripts/sitegen/insights.py +++ b/scripts/sitegen/insights.py @@ -21,6 +21,7 @@ from pathlib import Path from core import upstream from core.artifacts import write_text_atomic +from core.cli import SourceUnreadable from core.github import github_token @@ -68,6 +69,18 @@ class Query: # Reading the sources +class SourceUnavailable(Exception): + """A source that could not be read this run, and how long until it answers again. + + The command leaves the source out of the report and says why, instead of + losing what the other sources already gave. + """ + + def __init__(self, reason: str, wait: float | None = None) -> None: + super().__init__(reason) + self.wait = wait + + def _open(request: urllib.request.Request) -> tuple[int, bytes]: """Status and body of a request, retried by core.upstream.open_retrying: a dropped connection or a 5xx is asked again, a rate limit waited out.""" @@ -79,8 +92,8 @@ def _open(request: urllib.request.Request) -> tuple[int, bytes]: headers = error.headers if isinstance(error, urllib.error.HTTPError) else None wait = upstream.requested_wait(headers) delay = f" for {wait:.0f} s" if wait is not None else "" - raise SystemExit(f"{urllib.parse.urlsplit(request.full_url).hostname} refuses requests{delay} " - "(rate limit); run again then, or --skip that source") from error + raise SourceUnavailable(f"{urllib.parse.urlsplit(request.full_url).hostname} refuses requests" + f"{delay} (rate limit); run again then", wait) from error def _fetch(url: str, headers: dict[str, str] | None = None, body: dict | None = None) -> tuple[int, bytes]: @@ -118,8 +131,15 @@ def _google_token(key_file: Path) -> str: return json.loads(_open(request)[1])["access_token"] +def _credential(path: Path, source: str) -> Path: + """A credential file of the configuration folder, or the source is unavailable.""" + if not path.is_file(): + raise SourceUnavailable(f"{source} needs {path}") + return path + + def fetch_queries(start: dt.date, end: dt.date) -> list[Query]: - token = _google_token(CONFIG / "gsc-service-account.json") + token = _google_token(_credential(CONFIG / "gsc-service-account.json", "Search Console")) url = ("https://www.googleapis.com/webmasters/v3/sites/" f"{urllib.parse.quote(SITE_PROPERTY, safe='')}/searchAnalytics/query") rows: list[Query] = [] @@ -128,7 +148,7 @@ def fetch_queries(start: dt.date, end: dt.date) -> list[Query]: "startDate": start.isoformat(), "endDate": end.isoformat(), "dimensions": ["query", "page"], "rowLimit": 25000, "startRow": len(rows)}) if not isinstance(answer, dict): - raise SystemExit("Search Console answered with something other than an object") + raise SourceUnavailable("Search Console answered with something other than an object") batch = answer.get("rows", []) rows += [Query(r["keys"][0], r["keys"][1], int(r["clicks"]), int(r["impressions"]), float(r["position"])) for r in batch] @@ -144,13 +164,13 @@ def _goat_export(first: dt.datetime, auth: dict[str, str]) -> bytes: export = _get_json(f"{GOATCOUNTER}/export", auth, {"format": "json", "start_from_day": first.strftime("%Y-%m-%dT00:00:00Z")}) if not isinstance(export, dict) or "id" not in export: - raise SystemExit("GoatCounter did not start an export") + raise SourceUnavailable("GoatCounter did not start an export") for _ in range(EXPORT_TRIES): time.sleep(EXPORT_POLL) status, raw = _fetch(f"{GOATCOUNTER}/export/{export['id']}/download", auth) if status == 200: return raw - raise SystemExit(f"GoatCounter export {export['id']} not ready after {EXPORT_POLL * EXPORT_TRIES} s") + raise SourceUnavailable(f"GoatCounter export {export['id']} not ready after {EXPORT_POLL * EXPORT_TRIES} s") def read_export(raw: bytes, first: dt.datetime, after: dt.datetime) -> dict: @@ -187,7 +207,7 @@ def read_export(raw: bytes, first: dt.datetime, after: dt.datetime) -> dict: def fetch_goatcounter(start: dt.date, end: dt.date) -> dict: """Paths and events with their visit counts, and the referring domains.""" - token = (CONFIG / "goatcounter-api-token.txt").read_text(encoding="utf-8").strip() + token = _credential(CONFIG / "goatcounter-api-token.txt", "GoatCounter").read_text(encoding="utf-8").strip() first = dt.datetime.combine(start, dt.time(), dt.timezone.utc) after = dt.datetime.combine(end + dt.timedelta(days=1), dt.time(), dt.timezone.utc) return read_export(_goat_export(first, {"Authorization": f"Bearer {token}"}), first, after) @@ -197,7 +217,7 @@ def fetch_github() -> dict: # Traffic figures are only served to the owner: without a token there # is nothing to read, not a smaller quota. if not github_token(): - raise SystemExit("GitHub traffic needs a token: GITHUB_TOKEN, or gh auth login") + raise SourceUnavailable("GitHub traffic needs a token: GITHUB_TOKEN, or gh auth login") api = f"https://api.github.com/repos/{REPOSITORY}" auth = upstream.forge_headers(api, "application/vnd.github+json", USER_AGENT) releases = _get_json(f"{api}/releases?per_page=10", auth) @@ -349,9 +369,9 @@ def load_snapshot(path: Path) -> dict | None: try: snapshot = json.loads(path.read_text(encoding="utf-8")) except json.JSONDecodeError as error: - raise SystemExit(f"{path} is not a download snapshot ({error}); move it away to start again") from error + raise SourceUnreadable(f"{path} is not a download snapshot ({error}); move it away to start again") from error if not isinstance(snapshot, dict) or not isinstance(snapshot.get("counts"), dict) or "taken" not in snapshot: - raise SystemExit(f"{path} is not a download snapshot; move it away to start again") + raise SourceUnreadable(f"{path} is not a download snapshot; move it away to start again") return snapshot @@ -390,6 +410,8 @@ class Readings: goat_end: dt.date | None = None github: dict | None = None snapshot: dict | None = None + # Each source that could not be read, with why: "GitHub: ... needs a token". + left_out: tuple[str, ...] = () @property def previous_span(self) -> tuple[dt.date, dt.date]: @@ -533,6 +555,8 @@ def _github(readings: Readings, github: dict) -> list[str]: def report(readings: Readings) -> str: out = ["# Site insights", "", f"Written {readings.now.strftime('%Y-%m-%d %H:%M UTC')}. " "Each section gives its own period.", ""] + if readings.left_out: + out += ["Not read this run:", "", *(f"- {line}" for line in readings.left_out), ""] if readings.queries is not None: out += _google(readings, readings.queries) if readings.goat is not None: diff --git a/tests/test_site_insights.py b/tests/test_site_insights.py index 21b730bc2..29d904ece 100644 --- a/tests/test_site_insights.py +++ b/tests/test_site_insights.py @@ -176,7 +176,7 @@ class Downloads(unittest.TestCase): self.assertEqual(snapshot, {"taken": "2026-11-19 10:30 UTC", "counts": {"v1/A.zip": 120, "v1/B.zip": 40, "v2/C.zip": 7}}) path.write_text("{", encoding="utf-8") - with self.assertRaisesRegex(SystemExit, "not a download snapshot"): + with self.assertRaisesRegex(insights.SourceUnreadable, "not a download snapshot"): insights.load_snapshot(path) @@ -277,15 +277,15 @@ class GoatCounterExport(unittest.TestCase): {"format": "json", "start_from_day": "2026-10-20T00:00:00Z"})) self.assertEqual([url for url, _ in calls[1:]], [f"{insights.GOATCOUNTER}/export/7/download"] * 3) - def test_an_export_never_ready_ends_the_run(self) -> None: + def test_an_export_never_ready_leaves_the_source_out(self) -> None: def fetch(url: str, headers: dict[str, str] | None = None, body: dict | None = None) -> tuple[int, bytes]: return 202, json.dumps({"id": 7}).encode() with mock.patch.object(insights, "_fetch", fetch), mock.patch.object(insights.time, "sleep"), \ - self.assertRaisesRegex(SystemExit, "export 7 not ready"): + self.assertRaisesRegex(insights.SourceUnavailable, "export 7 not ready"): insights._goat_export(self.FIRST, {}) - def test_a_long_rate_limit_ends_the_run_instead_of_sleeping(self) -> None: + def test_a_long_rate_limit_leaves_the_source_out_instead_of_sleeping(self) -> None: headers = email.message.Message() headers["X-Rate-Limit-Reset"] = "2355" refusal = urllib.error.HTTPError("https://retrobios.goatcounter.com/api/v0/stats/hits", 429, @@ -293,9 +293,10 @@ class GoatCounterExport(unittest.TestCase): with mock.patch.object(insights.urllib.request, "urlopen", side_effect=refusal), \ mock.patch.object(insights.upstream, "_sleep") as sleep, \ mock.patch.object(insights.upstream, "_exhausted_hosts", set()), \ - self.assertRaisesRegex(SystemExit, "2356 s"): + self.assertRaisesRegex(insights.SourceUnavailable, "2356 s") as caught: insights._get_json("https://retrobios.goatcounter.com/api/v0/stats/hits") sleep.assert_not_called() + self.assertEqual(caught.exception.wait, 2356) def test_a_short_rate_limit_is_waited(self) -> None: headers = email.message.Message() @@ -338,5 +339,43 @@ class GoatCounterExport(unittest.TestCase): self.assertEqual(headers["User-Agent"], insights.USER_AGENT) +class AnUnavailableSource(unittest.TestCase): + """A GitHub rate limit after Search Console and GoatCounter had been read + ended the run on SystemExit: no report, the other readings lost.""" + + def test_the_others_are_reported_and_the_source_named(self) -> None: + import contextlib + import sys + + import site_insights + + goat = {"hits": [("/emulators/mgba/", 4)], "referrers": [], "visits": 4, "actions": 0} + with tempfile.TemporaryDirectory() as scratch: + config = Path(scratch) + # GoatCounter's token is there, Search Console's key is not. + (config / "goatcounter-api-token.txt").write_text("t\n", encoding="utf-8") + output = config / "report.md" + argv = ["site_insights.py", "--skip", "github", "--output", str(output)] + stderr = io.StringIO() + with mock.patch.object(sys, "argv", argv), \ + mock.patch.object(insights, "CONFIG", config), \ + mock.patch.object(insights, "_goat_export", return_value=b""), \ + mock.patch.object(insights, "read_export", return_value=goat), \ + contextlib.redirect_stderr(stderr): + code = site_insights.main() + text = output.read_text(encoding="utf-8") + reason = f"Search Console needs {config / 'gsc-service-account.json'}" + self.assertEqual(code, 1) + self.assertIn("## On the site", text) + self.assertNotIn("## Google searches", text) + self.assertIn(f"- Search Console: {reason}", text) + self.assertIn(f"Not read, Search Console: {reason}", stderr.getvalue()) + + def test_a_missing_credential_is_an_unavailable_source(self) -> None: + with mock.patch.object(insights, "CONFIG", Path("/nonexistent")), \ + self.assertRaisesRegex(insights.SourceUnavailable, "GoatCounter needs"): + insights.fetch_goatcounter(dt.date(2026, 10, 1), dt.date(2026, 10, 28)) + + if __name__ == "__main__": unittest.main() diff --git a/wiki/tools.md b/wiki/tools.md index 6f577acb3..cc5f05cbc 100644 --- a/wiki/tools.md +++ b/wiki/tools.md @@ -1396,7 +1396,7 @@ before a release (wiki/release-process.md). Its lines stay in | `generate_site.py` | Generate the site (this documentation) into the Starlight project in `website/` | | `sitesources.py` | Record which cited source paths each pinned upstream tree holds, for the site's source links (`--fetch` reads a tree no cache holds) | | `site_markdown.py` | Write each built page as Markdown beside its HTML (`/index.md`, named in every page's head) and `llms-full.txt`, the guides and every setup's page in one file, for the assistants that read the site. The Astro build runs it once the pages are written | -| `site_insights.py` | What readers look for and do not find, from totals only, each section with its period: Google searches by page against the period of the same length before (anchors merged into their page), ranked by the clicks lost against the site's own click rate at each position, searches clicked less than half that rate, searched file names the collection does not hold, site searches that found nothing, broken addresses, "Did this page help?" answers, GitHub traffic (14 days) and release downloads since the previous run (`--days`, `--skip gsc,goatcounter,github`, `--output`, `--downloads-snapshot`, default `.cache/insights/downloads.json`). Reads Search Console, GoatCounter and GitHub with credentials kept outside the repository. [What the site counts](privacy.md) | +| `site_insights.py` | What readers look for and do not find, from totals only, each section with its period: Google searches by page against the period of the same length before (anchors merged into their page), ranked by the clicks lost against the site's own click rate at each position, searches clicked less than half that rate, searched file names the collection does not hold, site searches that found nothing, broken addresses, "Did this page help?" answers, GitHub traffic (14 days) and release downloads since the previous run (`--days`, `--skip gsc,goatcounter,github`, `--output`, `--downloads-snapshot`, default `.cache/insights/downloads.json`). Reads Search Console, GoatCounter and GitHub with credentials kept outside the repository. A source it cannot read (rate limit, missing credential) is named at the top of the report instead of ending the run, which then exits 1. [What the site counts](privacy.md) | | `make_demo.py` | Record the installer demos of the README and the site into `docs_assets/demo/`. An ArkOS card with six games is built under `tmp/demo/` in a mount namespace of the user, this checkout is served on loopback, and VHS runs one tape per variant: `default` (`install.tape`, the one-line command in a terminal, the card at `/media/EASYROMS`, needs `unshare`) and `handheld` (`install-handheld.tape`, the full-screen interface at 640x480 on an ArkOS root made with `bwrap`, as its Tools menu starts it, driven by the keys gptokeyb sends for the buttons). `--variant NAME` records one (repeatable), every variant by default, the others kept. Each needs `vhs`, `ttyd` and `ffmpeg`. The default gets the README's GIF, each gets a WebM, an MP4 and a poster, held to their size targets, and an entry in `demo.json` with what it shows and its alt text. No Windows variant: under pwsh on Linux the installer's summary gives `--dest /mnt/e/bios` back. Never run by the build | | `validate_site.py` | Validate rendered metadata, heading order, image alternatives, JSON-LD, local resources, links and fragments, and the page size and search index budgets | | `indexnow.py` | List the pages a deploy changes, read against the `digests.json` the live site serves, as the IndexNow request the deploy posts once the new site is live. `--dist` names the built site, `--output` appends the request to a step output |