From 1e2c1b898f8911aab2d7f4971b22ad61221b6a17 Mon Sep 17 00:00:00 2001 From: jochen Date: Fri, 27 Nov 2026 09:46:56 +0100 Subject: [PATCH] Keep Jolpica schedules, pace the requests, never keep a failure A Kometa YAML request asks Jolpica for every season at once; Jolpica (4 requests a second, 500 an hour) answered 429 for 24 seasons on 2026-11-27 09:28, and lru_cache kept each failure as an empty schedule, so every poster and thumb of those seasons answered 404 until a restart. The service also ran two Jolpica clients, so the race lookup and the posters held different schedules. Now one client serves the whole service; a season that is over is kept on disk in the cache volume for good, one not yet over is asked again after six hours; requests are paced under the limit, a 429 is asked again after its Retry-After; a failure is never kept. The Kometa endpoint runs in the threadpool, as its first fill takes minutes. Claude-Session: https://claude.ai/code/session_01NcbgfJAa38xFpzy69BWrqh --- cdn-api.py | 13 +++++-- ergast_service.py | 86 ++++++++++++++++++++++++++++++++++++----- merge-check.sh | 5 ++- tests/test_schedules.py | 50 ++++++++++++++++++++++++ 4 files changed, 139 insertions(+), 15 deletions(-) create mode 100644 tests/test_schedules.py diff --git a/cdn-api.py b/cdn-api.py index a9a2fba..e38c9c7 100644 --- a/cdn-api.py +++ b/cdn-api.py @@ -6,8 +6,8 @@ import logging # Import our CircuitService from circuits_service import CircuitService, Format -from ergast_service import ErgastService from posters_service import PostersService, BackgroundStyle +from access_log import log_request from models.track_layout import TrackLayout # Initialize FastAPI app @@ -30,9 +30,13 @@ app.add_middleware( logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) +# One line per request (uvicorn's own access log is off: --no-access-log) +app.middleware("http")(log_request) + # Initialize CircuitService circuit_service = CircuitService() -ergast_service = ErgastService(circuit_service) +# One Jolpica client for the whole service, so its schedules and its pacing are shared +ergast_service = circuit_service.ergast_service posters_service = PostersService(circuit_service, ergast_service) def get_content_disposition(format: Format) -> str: @@ -129,7 +133,7 @@ async def get_session_thumb(grand_prix_name: str, season: int, session_slug: str @app.get("/kometa/formula-1-metadata.yml") -async def get_kometa_metadata(): +def get_kometa_metadata(): """Generate a Kometa-compatible metadata YAML for the Formula 1 library. One entry per F1 season from 1950..current+1. Each entry: @@ -140,6 +144,9 @@ async def get_kometa_metadata(): Kometa harmlessly skips shows / seasons that don't exist in the Plex library, so we can emit the full schedule and let Kometa do the matching. + + A plain def, not async: the first call asks Jolpica for every season, paced under its rate + limit (about 25 s), and runs in the threadpool instead of holding up every other request. """ yaml = posters_service.render_kometa_metadata() return PlainTextResponse( diff --git a/ergast_service.py b/ergast_service.py index 0dd5909..b3b8aa2 100644 --- a/ergast_service.py +++ b/ergast_service.py @@ -1,8 +1,12 @@ import re import logging +import threading +import time +import urllib.error import urllib.request import json -from functools import lru_cache +from datetime import date +from pathlib import Path from typing import Optional, TYPE_CHECKING if TYPE_CHECKING: @@ -25,6 +29,12 @@ def slugify(text: str) -> str: class ErgastService: JOLPICA_BASE = 'https://api.jolpi.ca/ergast/f1' + # Jolpica allows 4 requests a second and 500 an hour without a token, and asks its clients to cache + # (https://github.com/jolpica/jolpica-f1/blob/main/docs/rate_limits.md). + REQUEST_INTERVAL = 0.3 # seconds between two requests: under the 4 a second + RETRIES = 3 # a throttled request (429) is asked again after a pause, at most this often + OPEN_SEASON_TTL = 6 * 3600 # a season not yet over is asked again after six hours + # Country name normalization: Jolpica country → our country slug country_map = { 'UK': 'uk', @@ -33,10 +43,14 @@ class ErgastService: 'Korea': 'korea', } - def __init__(self, circuits_service: 'CircuitService' = None): + def __init__(self, circuits_service: 'CircuitService' = None, cache_dir: Path = Path("cache/jolpica")): self.circuits_service = circuits_service self.logger = logging.getLogger(__name__) self._circuit_id_index = self._build_circuit_id_index() + self.cache_dir = cache_dir + self._schedules: dict[int, tuple[float, list[dict]]] = {} # season → (fetched at, races) + self._fetch_lock = threading.Lock() + self._last_request = 0.0 def _build_circuit_id_index(self) -> dict[str, tuple[str, str, str]]: """Build a lookup from Jolpica's circuitId → (country_slug, locality_slug, circuit_slug). @@ -55,17 +69,69 @@ class ErgastService: index[circuit.ergast_id] = (country_slug, locality_slug, circuit_slug) return index - @lru_cache(maxsize=128) def _fetch_season_schedule(self, season: int) -> list[dict]: - """Fetch and cache the race schedule for a season from Jolpica.""" + """The race schedule of a season: from memory, then from disk, then from Jolpica. + + A season that is over never changes, so it is kept on disk for good; a season not yet over is + asked again after OPEN_SEASON_TTL. A failed fetch is never kept: the next call asks again, and + until it succeeds the schedule kept last is answered, or none.""" + with self._fetch_lock: + kept = self._schedules.get(season) or self._read_kept(season) + if kept and (season < date.today().year or time.time() - kept[0] < self.OPEN_SEASON_TTL): + self._schedules[season] = kept + return kept[1] + races = self._ask_jolpica(season) + if races is None: + return kept[1] if kept else [] + kept = (time.time(), races) + self._schedules[season] = kept + self._write_kept(season, kept) + return races + + def _ask_jolpica(self, season: int) -> Optional[list[dict]]: + """Ask Jolpica for a season's races, paced under its rate limit; None when it does not answer.""" url = f'{self.JOLPICA_BASE}/{season}.json?limit=100' + for attempt in range(1, self.RETRIES + 1): + wait = self._last_request + self.REQUEST_INTERVAL - time.monotonic() + if wait > 0: + time.sleep(wait) + self._last_request = time.monotonic() + try: + with urllib.request.urlopen(url, timeout=10) as resp: + return json.loads(resp.read())['MRData']['RaceTable']['Races'] + except urllib.error.HTTPError as e: + if e.code != 429 or attempt == self.RETRIES: + self.logger.error(f"Failed to fetch Jolpica schedule for {season}: {e}") + return None + retry_after = e.headers.get('Retry-After', '') if e.headers else '' + pause = min(float(retry_after), 30.0) if retry_after.isdigit() else 2.0 ** attempt + self.logger.warning(f"Jolpica throttled the schedule for {season} (429): asking again in {pause:.0f}s") + time.sleep(pause) + except Exception as e: + self.logger.error(f"Failed to fetch Jolpica schedule for {season}: {e}") + return None + return None + + def _read_kept(self, season: int) -> Optional[tuple[float, list[dict]]]: + path = self.cache_dir / f'{season}.json' try: - resp = urllib.request.urlopen(url, timeout=10) - data = json.loads(resp.read()) - return data['MRData']['RaceTable']['Races'] - except Exception as e: - self.logger.error(f"Failed to fetch Jolpica schedule for {season}: {e}") - return [] + kept = json.loads(path.read_text(encoding='utf-8')) + return kept['fetched'], kept['races'] + except FileNotFoundError: + return None + except (OSError, ValueError, KeyError) as e: + self.logger.warning(f"Could not read the kept Jolpica schedule {path}: {e}") + return None + + def _write_kept(self, season: int, kept: tuple[float, list[dict]]) -> None: + path = self.cache_dir / f'{season}.json' + try: + self.cache_dir.mkdir(parents=True, exist_ok=True) + partial = path.with_suffix('.partial') + partial.write_text(json.dumps({'fetched': kept[0], 'races': kept[1]}), encoding='utf-8') + partial.replace(path) + except OSError as e: + self.logger.warning(f"Could not keep the Jolpica schedule {path}: {e}") def find_slugs_for_grand_prix(self, grand_prix_name: str, season: int) -> Optional[tuple[str, str, str]]: """Resolve a grand prix name + season to (country_slug, locality_slug, circuit_slug).""" diff --git a/merge-check.sh b/merge-check.sh index 589faee..85c1cce 100644 --- a/merge-check.sh +++ b/merge-check.sh @@ -10,14 +10,15 @@ # What the image ships, compiled before the merge: every Python file the service's image copies, and the # models it imports. Then the tests in tests/, which need the standard library only: every circuit in # circuits/circuits.json carries one unique ergastId, and a race's circuit resolves by that id, never by -# its name. +# its name; a failed Jolpica fetch is never kept, a season that is over is read from disk, a throttled +# request is asked again. # # **Said, never passed silently**: the service's dependencies (service/requirements.txt) are the image's to # install, so the service is not started. set -eu # Parsed, not compiled to files: a check leaves the tree as it found it. -find cdn-api.py circuits_service.py ergast_service.py posters_service.py models -name '*.py' -print0 | +find cdn-api.py access_log.py circuits_service.py ergast_service.py posters_service.py models -name '*.py' -print0 | xargs -0 python3 -c 'import ast, sys for f in sys.argv[1:]: ast.parse(open(f, encoding="utf-8").read(), f) diff --git a/tests/test_schedules.py b/tests/test_schedules.py new file mode 100644 index 0000000..fae7000 --- /dev/null +++ b/tests/test_schedules.py @@ -0,0 +1,50 @@ +"""A season's schedule: a failed fetch is never kept, a season that is over is read from disk, and a +request Jolpica throttles is asked again.""" +import io +import json +import tempfile +import unittest +import urllib.error +from pathlib import Path +from unittest import mock + +from ergast_service import ErgastService + +RACES = [{"raceName": "Monaco Grand Prix", "Circuit": {"circuitId": "monaco", "circuitName": "Circuit de Monaco"}}] + + +class ScheduleTest(unittest.TestCase): + def setUp(self): + kept = tempfile.TemporaryDirectory() + self.addCleanup(kept.cleanup) + self.cache_dir = Path(kept.name) + + def service(self) -> ErgastService: + service = ErgastService(cache_dir=self.cache_dir) + service.REQUEST_INTERVAL = 0 + return service + + def test_a_failed_fetch_is_not_kept(self): + service = self.service() + with mock.patch.object(service, "_ask_jolpica", side_effect=[None, RACES]) as ask: + self.assertEqual(service._fetch_season_schedule(2019), []) + self.assertEqual(service._fetch_season_schedule(2019), RACES) + self.assertEqual(ask.call_count, 2) + + def test_a_season_that_is_over_is_read_from_disk(self): + with mock.patch.object(ErgastService, "_ask_jolpica", return_value=RACES): + self.service()._fetch_season_schedule(2019) + with mock.patch.object(ErgastService, "_ask_jolpica") as ask: + self.assertEqual(self.service()._fetch_season_schedule(2019), RACES) + ask.assert_not_called() + + def test_a_throttled_request_is_asked_again(self): + throttled = urllib.error.HTTPError("url", 429, "Too Many Requests", {"Retry-After": "0"}, None) + answer = io.BytesIO(json.dumps({"MRData": {"RaceTable": {"Races": RACES}}}).encode()) + with mock.patch("urllib.request.urlopen", side_effect=[throttled, answer]) as urlopen: + self.assertEqual(self.service()._ask_jolpica(2019), RACES) + self.assertEqual(urlopen.call_count, 2) + + +if __name__ == "__main__": + unittest.main()