"""Polite read-only client for the public auction API.""" from __future__ import annotations import gzip import json import random import time from datetime import UTC, datetime from pathlib import Path from typing import Any import requests BASE_URL = "https://buyerapi.shopgoodwill.com" MIN_SLEEP = 2.0 MAX_SLEEP = 5.0 BACKOFF_BASE = 5.0 MAX_CONSECUTIVE_FAILURES = 3 class AuctionApiError(RuntimeError): """Raised after consecutive request failures exhaust the retry budget.""" class AuctionApi: """Single-worker client that only reads public auction data.""" def __init__( self, *, cache_dir: Path, session: requests.Session | None = None, sleep: Any = time.sleep, rng: random.Random | None = None, timeout: float = 30.0, ) -> None: self.cache_dir = cache_dir self.session = session or requests.Session() self.sleep = sleep self.rng = rng or random.Random() self.timeout = timeout self.consecutive_failures = 0 def _cache(self, label: str, content: bytes) -> Path: now = datetime.now(UTC) target = self.cache_dir / now.strftime("%Y-%m-%d") target.mkdir(parents=True, exist_ok=True) path = target / f"{now.strftime('%H%M%S_%f')}_{label}.json.gz" with gzip.open(path, "wb") as handle: handle.write(content) return path def request(self, method: str, path: str, *, label: str, payload: dict[str, Any] | None = None) -> dict[str, Any]: """Read one JSON endpoint with pacing and bounded exponential retries.""" while True: self.sleep(self.rng.uniform(MIN_SLEEP, MAX_SLEEP)) try: response = self.session.request(method, BASE_URL + path, json=payload, timeout=self.timeout) if response.status_code != 200: raise AuctionApiError(f"HTTP {response.status_code} for {label}") self._cache(label, response.content) result = json.loads(response.content) except Exception as exc: # Each failure is paced before retrying. self.consecutive_failures += 1 if self.consecutive_failures >= MAX_CONSECUTIVE_FAILURES: raise AuctionApiError(f"stopping after {self.consecutive_failures} failures: {exc}") from exc delay = BACKOFF_BASE * (2 ** (self.consecutive_failures - 1)) self.sleep(delay + self.rng.uniform(0, MIN_SLEEP)) continue self.consecutive_failures = 0 return result def item_detail(self, item_id: int | str) -> dict[str, Any]: """Read public listing details; this client has no write operation.""" return self.request("GET", f"/api/ItemDetail/GetItemDetailModelByItemId/{item_id}", label=f"detail_{item_id}")