py76 lines2.8 KB
| 1 | """Polite read-only client for the public auction API.""" |
| 2 | |
| 3 | from __future__ import annotations |
| 4 | |
| 5 | import gzip |
| 6 | import json |
| 7 | import random |
| 8 | import time |
| 9 | from datetime import UTC, datetime |
| 10 | from pathlib import Path |
| 11 | from typing import Any |
| 12 | |
| 13 | import requests |
| 14 | |
| 15 | BASE_URL = "https://buyerapi.shopgoodwill.com" |
| 16 | MIN_SLEEP = 2.0 |
| 17 | MAX_SLEEP = 5.0 |
| 18 | BACKOFF_BASE = 5.0 |
| 19 | MAX_CONSECUTIVE_FAILURES = 3 |
| 20 | |
| 21 | |
| 22 | class AuctionApiError(RuntimeError): |
| 23 | """Raised after consecutive request failures exhaust the retry budget.""" |
| 24 | |
| 25 | |
| 26 | class AuctionApi: |
| 27 | """Single-worker client that only reads public auction data.""" |
| 28 | |
| 29 | def __init__( |
| 30 | self, |
| 31 | *, |
| 32 | cache_dir: Path, |
| 33 | session: requests.Session | None = None, |
| 34 | sleep: Any = time.sleep, |
| 35 | rng: random.Random | None = None, |
| 36 | timeout: float = 30.0, |
| 37 | ) -> None: |
| 38 | self.cache_dir = cache_dir |
| 39 | self.session = session or requests.Session() |
| 40 | self.sleep = sleep |
| 41 | self.rng = rng or random.Random() |
| 42 | self.timeout = timeout |
| 43 | self.consecutive_failures = 0 |
| 44 | |
| 45 | def _cache(self, label: str, content: bytes) -> Path: |
| 46 | now = datetime.now(UTC) |
| 47 | target = self.cache_dir / now.strftime("%Y-%m-%d") |
| 48 | target.mkdir(parents=True, exist_ok=True) |
| 49 | path = target / f"{now.strftime('%H%M%S_%f')}_{label}.json.gz" |
| 50 | with gzip.open(path, "wb") as handle: |
| 51 | handle.write(content) |
| 52 | return path |
| 53 | |
| 54 | def request(self, method: str, path: str, *, label: str, payload: dict[str, Any] | None = None) -> dict[str, Any]: |
| 55 | """Read one JSON endpoint with pacing and bounded exponential retries.""" |
| 56 | while True: |
| 57 | self.sleep(self.rng.uniform(MIN_SLEEP, MAX_SLEEP)) |
| 58 | try: |
| 59 | response = self.session.request(method, BASE_URL + path, json=payload, timeout=self.timeout) |
| 60 | if response.status_code != 200: |
| 61 | raise AuctionApiError(f"HTTP {response.status_code} for {label}") |
| 62 | self._cache(label, response.content) |
| 63 | result = json.loads(response.content) |
| 64 | except Exception as exc: # Each failure is paced before retrying. |
| 65 | self.consecutive_failures += 1 |
| 66 | if self.consecutive_failures >= MAX_CONSECUTIVE_FAILURES: |
| 67 | raise AuctionApiError(f"stopping after {self.consecutive_failures} failures: {exc}") from exc |
| 68 | delay = BACKOFF_BASE * (2 ** (self.consecutive_failures - 1)) |
| 69 | self.sleep(delay + self.rng.uniform(0, MIN_SLEEP)) |
| 70 | continue |
| 71 | self.consecutive_failures = 0 |
| 72 | return result |
| 73 | |
| 74 | def item_detail(self, item_id: int | str) -> dict[str, Any]: |
| 75 | """Read public listing details; this client has no write operation.""" |
| 76 | return self.request("GET", f"/api/ItemDetail/GetItemDetailModelByItemId/{item_id}", label=f"detail_{item_id}") |