fix: read goatcounter hits in weekly windows

Paging the whole span with exclude_paths grew the address past what the
server accepts. Windows add up since GoatCounter keeps hourly counts; a
long rate-limit wait now ends the run with its reason.
This commit is contained in:
Abdessamad Derraz committed 2026-11-19 16:44:03 +01:00
1 parent 022591a67e
commit 070a5a1ba6
2 files changed
+163 -13

No files matched your search

+80 -13
View File
@@ -10,6 +10,7 @@ import re
import subprocess
import tempfile
import time
import urllib.error
import urllib.parse
import urllib.request
from collections import defaultdict
@@ -24,6 +25,12 @@ SITE_PROPERTY = "https://abdess.github.io/retrobios/"
GOATCOUNTER = "https://retrobios.goatcounter.com/api/v0"
REPOSITORY = "Abdess/retrobios"
SOURCES = ("gsc", "goatcounter", "github")
# Paths excluded before a window is cut in two: about 10 KB of address.
GOAT_MAX_EXCLUDED = 1000
# GoatCounter answers four requests a second and 500 per window, and says
# when to come back: a short wait is waited, a long one ends the run.
RATE_LIMIT_TRIES = 8
RATE_LIMIT_LONGEST_WAIT = 60
# A word of a search that names a file: "scph5501.bin", "prod.keys".
FILE_TOKEN = re.compile(r"\b[\w.+-]+\.(?:bin|rom|zip|pup|keys|img|dat|bios|ic\d+|u\d+|sys|nvm|mec|"
@@ -51,6 +58,18 @@ def _get_json(url: str, headers: dict[str, str] | None = None, body: dict | None
request = urllib.request.Request(url, data=data, headers={
"User-Agent": "retrobios-site-insights", **({"Content-Type": "application/json"} if data else {}),
**(headers or {})})
for _ in range(RATE_LIMIT_TRIES - 1):
try:
with urllib.request.urlopen(request, timeout=60) as response:
return json.load(response)
except urllib.error.HTTPError as error:
if error.code != 429:
raise
wait = int(error.headers.get("X-Rate-Limit-Reset") or 1) + 1
if wait > RATE_LIMIT_LONGEST_WAIT:
raise SystemExit(f"{urllib.parse.urlsplit(url).hostname} refuses requests for "
f"{wait} s (rate limit); run again then, or --skip that source") from error
time.sleep(wait)
with urllib.request.urlopen(request, timeout=60) as response:
return json.load(response)
@@ -98,23 +117,71 @@ def fetch_queries(start: dt.date, end: dt.date) -> list[Query]:
return rows
def _goat_object(url: str, auth: dict[str, str]) -> dict:
answer = _get_json(url, auth)
if not isinstance(answer, dict):
raise SystemExit("GoatCounter answered with something other than an object")
return answer
def _goat_span(start: dt.datetime, end: dt.datetime) -> dict[str, str]:
"""The hours from start up to end, end excluded: GoatCounter keeps hourly
counts and reads an end at hh:59:59 as the last hour included."""
last = end - dt.timedelta(seconds=1)
return {"start": start.strftime("%Y-%m-%dT%H:00:00Z"), "end": last.strftime("%Y-%m-%dT%H:59:59Z")}
def _goat_window(start: dt.datetime, end: dt.datetime, auth: dict[str, str]) -> dict[str, int] | None:
"""Every path of one window with its count, or None once the window
holds too many paths to page through."""
counts: dict[str, int] = {}
exclude: list[str] = []
while True:
params = urllib.parse.urlencode({**_goat_span(start, end), "limit": 100,
"exclude_paths": ",".join(exclude)}, safe=",")
answer = _goat_object(f"{GOATCOUNTER}/stats/hits?{params}", auth)
for hit in answer.get("hits", []):
counts[hit["path"] + (" [404]" if hit.get("title") == "404" else "")] = int(hit["count"])
exclude.append(str(hit["path_id"]))
if not answer.get("more"):
return counts
if len(exclude) >= GOAT_MAX_EXCLUDED:
return None
def _goat_hits(start: dt.datetime, end: dt.datetime, auth: dict[str, str]) -> list[tuple[str, int]]:
"""Counts by path over the whole span, summed week by week: GoatCounter
keeps hourly counts, so windows add up. The API pages with
exclude_paths, which lengthens the address by every path already read,
and the run of 2026-11-19 failed past 2,800 of them. A window with too
many paths is read again in halves, down to one hour."""
totals: dict[str, int] = defaultdict(int)
week = dt.timedelta(days=7)
pending = [(low, min(low + week, end)) for low in
(start + n * week for n in range(-(-(end - start) // week)))]
while pending:
low, high = pending.pop()
counts = _goat_window(low, high, auth)
if counts is None:
hours = int((high - low).total_seconds()) // 3600
if hours <= 1:
raise SystemExit(f"GoatCounter holds more than {GOAT_MAX_EXCLUDED} paths in the hour from {low}")
middle = low + dt.timedelta(hours=hours // 2)
pending += [(low, middle), (middle, high)]
continue
for path, count in counts.items():
totals[path] += count
return list(totals.items())
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()
auth = {"Authorization": f"Bearer {token}"}
span = {"start": f"{start.isoformat()}T00:00:00Z", "end": f"{end.isoformat()}T23:59:59Z"}
hits: list[tuple[str, int]] = []
exclude: list[str] = []
while True:
params = urllib.parse.urlencode({**span, "limit": 100, "exclude_paths": ",".join(exclude)})
answer = _get_json(f"{GOATCOUNTER}/stats/hits?{params}", auth)
if not isinstance(answer, dict):
raise SystemExit("GoatCounter answered with something other than an object")
for hit in answer.get("hits", []):
hits.append((hit["path"] + (" [404]" if hit.get("title") == "404" else ""), int(hit["count"])))
exclude.append(str(hit["path_id"]))
if not answer.get("more"):
break
first = dt.datetime.combine(start, dt.time(), dt.timezone.utc)
after = dt.datetime.combine(end + dt.timedelta(days=1), dt.time(), dt.timezone.utc)
span = _goat_span(first, after)
hits = _goat_hits(first, after, auth)
refs = _get_json(f"{GOATCOUNTER}/stats/toprefs?{urllib.parse.urlencode({**span, 'limit': 50})}", auth)
total = _get_json(f"{GOATCOUNTER}/stats/total?{urllib.parse.urlencode(span)}", auth)
if not isinstance(refs, dict) or not isinstance(total, dict):
+83
View File
@@ -4,7 +4,13 @@ from __future__ import annotations
import tests
import datetime as dt
import email.message
import io
import json
import unittest
import urllib.error
import urllib.parse
from unittest import mock
from sitegen import insights
@@ -61,5 +67,82 @@ class TheReport(unittest.TestCase):
self.assertEqual(declared, {"dsp1b.rom", "dsp1b.bin"})
class FakeGoatCounter:
"""Hourly counts by path, paged the way /stats/hits pages: by count,
a hundred at most, past the ids in exclude_paths."""
def __init__(self, hourly: dict[tuple[str, dt.datetime], int]) -> None:
self.hourly = hourly
self.ids = {path: n for n, path in enumerate(sorted({path for path, _ in hourly}), 1)}
self.calls = 0
def __call__(self, url: str, headers: dict[str, str] | None = None) -> dict:
self.calls += 1
query = urllib.parse.parse_qs(urllib.parse.urlsplit(url).query)
start = dt.datetime.strptime(query["start"][0], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc)
end = dt.datetime.strptime(query["end"][0], "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=dt.timezone.utc)
excluded = {int(i) for i in query.get("exclude_paths", [""])[0].split(",") if i}
counts: dict[str, int] = {}
for (path, hour), count in self.hourly.items():
if start <= hour <= end and self.ids[path] not in excluded:
counts[path] = counts.get(path, 0) + count
ranked = sorted(counts.items(), key=lambda row: (-row[1], row[0]))
limit = int(query["limit"][0])
return {"hits": [{"path": path, "path_id": self.ids[path], "count": count,
"title": "404" if path.startswith("/gone") else ""} for path, count in ranked[:limit]],
"more": len(ranked) > limit}
class GoatCounterPaging(unittest.TestCase):
START = dt.datetime(2026, 10, 20, tzinfo=dt.timezone.utc)
END = dt.datetime(2026, 11, 17, tzinfo=dt.timezone.utc)
def hits(self, server: FakeGoatCounter) -> dict[str, int]:
with mock.patch.object(insights, "_get_json", server):
return dict(insights._goat_hits(self.START, self.END, {}))
def test_windows_add_up_without_counting_an_hour_twice(self) -> None:
# One visit at the last hour of each day, the hour a window boundary falls on.
hourly = {(f"/page{day}", self.START + dt.timedelta(days=day, hours=23)): 1 for day in range(28)}
hourly[("/gone/link/", self.START + dt.timedelta(days=7))] = 3
hourly[("search-none/kenji", self.END - dt.timedelta(hours=1))] = 2
hourly[("/late", self.END)] = 9
got = self.hits(FakeGoatCounter(hourly))
self.assertEqual(sum(got.values()), 28 + 3 + 2)
self.assertEqual(got["/gone/link/ [404]"], 3)
self.assertEqual(got["search-none/kenji"], 2)
self.assertNotIn("/late", got)
def test_a_window_with_too_many_paths_is_read_in_halves(self) -> None:
hourly = {(f"/p{n}", self.START + dt.timedelta(hours=n % 300)): n + 1 for n in range(250)}
server = FakeGoatCounter(hourly)
with mock.patch.object(insights, "GOAT_MAX_EXCLUDED", 100):
got = self.hits(server)
self.assertEqual(got, {f"/p{n}": n + 1 for n in range(250)})
self.assertGreater(server.calls, 4)
def test_a_long_rate_limit_ends_the_run_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,
"Too Many Requests", headers, io.BytesIO(b""))
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=refusal), \
mock.patch.object(insights.time, "sleep") as sleep, \
self.assertRaisesRegex(SystemExit, "2356 s"):
insights._get_json("https://retrobios.goatcounter.com/api/v0/stats/hits")
sleep.assert_not_called()
def test_a_short_rate_limit_is_waited(self) -> None:
headers = email.message.Message()
headers["X-Rate-Limit-Reset"] = "1"
refusal = urllib.error.HTTPError("https://x/api", 429, "Too Many Requests", headers, io.BytesIO(b""))
answer = mock.MagicMock()
answer.__enter__.return_value = io.BytesIO(json.dumps({"ok": 1}).encode())
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=[refusal, answer]), \
mock.patch.object(insights.time, "sleep") as sleep:
self.assertEqual(insights._get_json("https://x/api"), {"ok": 1})
sleep.assert_called_once_with(2)
if __name__ == "__main__":
unittest.main()