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
156 lines
7.2 KiB
Python
156 lines
7.2 KiB
Python
import re
|
|
import logging
|
|
import threading
|
|
import time
|
|
import urllib.error
|
|
import urllib.request
|
|
import json
|
|
from datetime import date
|
|
from pathlib import Path
|
|
from typing import Optional, TYPE_CHECKING
|
|
|
|
if TYPE_CHECKING:
|
|
from circuits_service import CircuitService
|
|
|
|
|
|
def slugify(text: str) -> str:
|
|
text = text.lower().strip()
|
|
replacements = {
|
|
'ü': 'u', 'ö': 'o', 'ä': 'a', 'é': 'e', 'è': 'e', 'ê': 'e', 'ë': 'e',
|
|
'à': 'a', 'â': 'a', 'î': 'i', 'ï': 'i', 'ô': 'o', 'û': 'u', 'ñ': 'n',
|
|
'ã': 'a', 'á': 'a', 'í': 'i', 'ó': 'o', 'ú': 'u',
|
|
}
|
|
for k, v in replacements.items():
|
|
text = text.replace(k, v)
|
|
text = re.sub(r'[^a-z0-9]+', '-', text)
|
|
return text.strip('-')
|
|
|
|
|
|
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',
|
|
'UAE': 'united-arab-emirates',
|
|
'USA': 'united-states',
|
|
'Korea': 'korea',
|
|
}
|
|
|
|
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).
|
|
|
|
A race's circuit is matched on its circuitId, never on its name: Jolpica renames
|
|
circuits (Losail became Lusail) while the id stays the same."""
|
|
index = {}
|
|
if not self.circuits_service:
|
|
return index
|
|
for country_slug, country in self.circuits_service.circuit_data.items():
|
|
for locality_slug, locality in country.localities.items():
|
|
for circuit_slug, circuit in locality.circuits.items():
|
|
if not circuit.ergast_id:
|
|
self.logger.error(f"Circuit '{circuit_slug}' has no ergastId: no race can resolve to it")
|
|
continue
|
|
index[circuit.ergast_id] = (country_slug, locality_slug, circuit_slug)
|
|
return index
|
|
|
|
def _fetch_season_schedule(self, season: int) -> list[dict]:
|
|
"""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:
|
|
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)."""
|
|
races = self._fetch_season_schedule(season)
|
|
|
|
# Find the matching race
|
|
race = next((r for r in races if r['raceName'] == grand_prix_name), None)
|
|
if not race:
|
|
self.logger.error(f"Race '{grand_prix_name}' not found in {season} schedule")
|
|
return None, None, None
|
|
|
|
return self.find_slugs_for_circuit(race["Circuit"])
|
|
|
|
def find_slugs_for_circuit(self, circuit: dict) -> tuple[Optional[str], Optional[str], Optional[str]]:
|
|
"""Resolve a Jolpica race's Circuit object to (country_slug, locality_slug, circuit_slug)."""
|
|
slugs = self._circuit_id_index.get(circuit.get('circuitId'))
|
|
if slugs:
|
|
return slugs
|
|
self.logger.warning(f"Circuit '{circuit.get('circuitName')}' (circuitId: {circuit.get('circuitId')}) "
|
|
f"has no circuit with that ergastId in circuits.json")
|
|
return None, None, None
|