wrapkit 0.4.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
wrapkit/http.py ADDED
@@ -0,0 +1,819 @@
1
+ """
2
+ HTTP helpers: retries with backoff, a request-rate throttle, a User-Agent.
3
+
4
+ :func:`get_with_retries` (``requests``) and :func:`aget_with_retries`
5
+ (``httpx``) retry rate limits (429), server hiccups (500, 502, 503, 504) and
6
+ transport failures (refused or dropped connections, timeouts, truncated
7
+ bodies). The wait doubles each time, with jitter, capped at ``max_wait``. A
8
+ numeric ``Retry-After`` header on a 429 or 503 wins and is honoured in full up
9
+ to ``max_retry_after``; a longer one is not retried early: the answer is
10
+ returned at once, so the client never comes back before the server allows.
11
+ Every other
12
+ answer is returned at once, whatever its status: the caller decides what an
13
+ error looks like for its API.
14
+
15
+ Retry lines are logged at WARNING with only a caller-chosen label and a short
16
+ reason (``HTTP 503`` or the exception class name), never the URL, so a key in
17
+ the query string cannot leak through them.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import asyncio
23
+ import json
24
+ import os
25
+ import random
26
+ import ssl
27
+ import tempfile
28
+ import threading
29
+ import time
30
+ from dataclasses import dataclass
31
+ from pathlib import Path
32
+ from typing import TYPE_CHECKING, Any
33
+
34
+ import httpx
35
+ import requests
36
+
37
+ if TYPE_CHECKING:
38
+ import logging
39
+
40
+ __all__ = [
41
+ "ASYNC_RETRY_ERRORS",
42
+ "RETRY_ERRORS",
43
+ "AsyncThrottle",
44
+ "QuotaExhausted",
45
+ "RateLimit",
46
+ "RateLimitError",
47
+ "RetryPolicy",
48
+ "Throttle",
49
+ "aget_with_retries",
50
+ "get_with_retries",
51
+ "user_agent",
52
+ ]
53
+
54
+ #: ``requests`` transport failures worth another try. Anything else, such as a
55
+ #: malformed URL, fails at once, and so does a failed certificate check (an
56
+ #: ``SSLError`` is a ``ConnectionError``; see :func:`_cannot_heal`).
57
+ RETRY_ERRORS: tuple[type[Exception], ...] = (
58
+ requests.ConnectionError,
59
+ requests.Timeout,
60
+ requests.exceptions.ChunkedEncodingError,
61
+ )
62
+
63
+ #: ``httpx`` transport failures worth another try.
64
+ ASYNC_RETRY_ERRORS: tuple[type[Exception], ...] = (
65
+ httpx.TimeoutException,
66
+ httpx.NetworkError,
67
+ httpx.RemoteProtocolError,
68
+ )
69
+
70
+
71
+ def _cannot_heal(exc: BaseException) -> bool:
72
+ """
73
+ Tell whether a transport error is a certificate failure a retry won't fix.
74
+
75
+ ``requests`` and ``httpx`` wrap :class:`ssl.SSLCertVerificationError` a few
76
+ layers deep (as an argument, a ``reason`` or the cause). Other SSL errors,
77
+ such as a connection dropped mid-handshake, can be transient and are still
78
+ retried.
79
+
80
+ Args:
81
+ exc (BaseException): The error a request raised.
82
+
83
+ Returns:
84
+ bool: ``True`` when a certificate check failed somewhere in the chain.
85
+ """
86
+ seen: set[int] = set()
87
+ pending: list[object] = [exc]
88
+ while pending:
89
+ err = pending.pop()
90
+ if not isinstance(err, BaseException) or id(err) in seen:
91
+ continue
92
+ seen.add(id(err))
93
+ if isinstance(err, ssl.SSLCertVerificationError):
94
+ return True
95
+ pending.extend((err.__cause__, err.__context__, getattr(err, "reason", None)))
96
+ pending.extend(err.args)
97
+ return False
98
+
99
+
100
+ def _jitter() -> float:
101
+ """
102
+ Return a random factor that spreads retry waits by plus or minus 20%.
103
+
104
+ Clients that failed together would otherwise retry together. Tests patch
105
+ this (or pass ``jitter=False``) to get exact waits.
106
+
107
+ Returns:
108
+ float: A factor between 0.8 and 1.2.
109
+ """
110
+ return random.uniform(0.8, 1.2) # ruff: ignore[suspicious-non-cryptographic-random-usage] - jitter, not cryptography
111
+
112
+
113
+ @dataclass(frozen=True)
114
+ class RetryPolicy:
115
+ """
116
+ When to retry a request and how long to wait.
117
+
118
+ Attributes:
119
+ max_retries (int): Retries after the first attempt (``0`` disables
120
+ retrying).
121
+ statuses (frozenset[int]): HTTP statuses that are retried.
122
+ retry_after_statuses (frozenset[int]): Statuses whose numeric
123
+ ``Retry-After`` header sets the wait.
124
+ backoff (float): First wait in seconds, doubled for each further retry.
125
+ max_wait (float): Cap on any single backoff wait.
126
+ max_retry_after (float): Longest server ``Retry-After`` that is waited
127
+ out (it is not cut to ``max_wait``). A longer one ends the retries:
128
+ :func:`get_with_retries` returns that answer at once.
129
+ jitter (bool): Spread waits by plus or minus 20%.
130
+ """
131
+
132
+ max_retries: int = 4
133
+ statuses: frozenset[int] = frozenset({429, 500, 502, 503, 504})
134
+ retry_after_statuses: frozenset[int] = frozenset({429, 503})
135
+ backoff: float = 1.0
136
+ max_wait: float = 30.0
137
+ max_retry_after: float = 120.0
138
+ jitter: bool = True
139
+
140
+ def retry_after(self, status: int | None, header: str | None) -> float | None:
141
+ """
142
+ Return the server's numeric ``Retry-After`` in seconds, if it applies.
143
+
144
+ Only statuses in ``retry_after_statuses`` count. HTTP-date values,
145
+ negative numbers and NaN are ignored.
146
+
147
+ Args:
148
+ status (int | None): The HTTP status, or ``None`` for a transport
149
+ error.
150
+ header (str | None): The ``Retry-After`` header, if any.
151
+
152
+ Returns:
153
+ float | None: Seconds the server asks for, or ``None``.
154
+ """
155
+ if status not in self.retry_after_statuses or not header:
156
+ return None
157
+ try:
158
+ seconds = float(header.strip())
159
+ except ValueError:
160
+ return None
161
+ return seconds if seconds >= 0 else None # also None for NaN
162
+
163
+ def gives_up(self, status: int | None, header: str | None) -> bool:
164
+ """
165
+ Tell whether the server asks for a longer wait than will be honoured.
166
+
167
+ Args:
168
+ status (int | None): The HTTP status.
169
+ header (str | None): The ``Retry-After`` header, if any.
170
+
171
+ Returns:
172
+ bool: True when ``Retry-After`` exceeds ``max_retry_after``.
173
+ """
174
+ seconds = self.retry_after(status, header)
175
+ return seconds is not None and seconds > self.max_retry_after
176
+
177
+ def wait(
178
+ self, attempt: int, status: int | None = None, retry_after: str | None = None
179
+ ) -> float:
180
+ """
181
+ Return how long to wait after failed attempt ``attempt``.
182
+
183
+ A numeric ``Retry-After`` on a 429 or 503 is returned as is, up to
184
+ ``max_retry_after``; the backoff is capped at ``max_wait``. HTTP-date
185
+ ``Retry-After`` values are not parsed and fall back to the backoff.
186
+
187
+ Args:
188
+ attempt (int): The attempt that just failed, starting at 1.
189
+ status (int | None): Its HTTP status, or ``None`` for a transport
190
+ error.
191
+ retry_after (str | None): Its ``Retry-After`` header, if any.
192
+
193
+ Returns:
194
+ float: Seconds to wait.
195
+ """
196
+ seconds = self.retry_after(status, retry_after)
197
+ if seconds is not None:
198
+ return min(seconds, self.max_retry_after)
199
+ factor = _jitter() if self.jitter else 1.0
200
+ return min(self.backoff * 2.0 ** (attempt - 1) * factor, self.max_wait)
201
+
202
+
203
+ class RateLimitError(ValueError):
204
+ """A caller asked for a faster rate than the provider's limit allows."""
205
+
206
+
207
+ class QuotaExhausted(RuntimeError): # ruff: ignore[error-suffix-on-exception-name] - reads as a state, like StopIteration
208
+ """A provider's daily request quota is used up; no request was sent."""
209
+
210
+
211
+ @dataclass(frozen=True)
212
+ class RateLimit:
213
+ """
214
+ A provider's published request limit, enforced by :class:`Throttle`.
215
+
216
+ The spacing between requests is the strictest of ``requests_per_second``,
217
+ ``per_minute`` and ``per_hour`` (``per_hour=1000`` means one request every
218
+ 3.6 s), so no window can ever be exceeded. ``per_day`` is a rolling 24-hour
219
+ count: when it is reached the throttle raises :class:`QuotaExhausted`
220
+ instead of sleeping for hours.
221
+
222
+ Attributes:
223
+ requests_per_second (float | None): Fastest rate allowed.
224
+ per_minute (int | None): Most requests in any 60 seconds.
225
+ per_hour (int | None): Most requests in any hour.
226
+ per_day (int | None): Most requests in any 24 hours.
227
+ source (str): Where the limit is stated (a URL, a robots.txt
228
+ ``Crawl-delay``, or "no published limit" for a chosen default).
229
+ """
230
+
231
+ requests_per_second: float | None = None
232
+ per_minute: int | None = None
233
+ per_hour: int | None = None
234
+ per_day: int | None = None
235
+ source: str = ""
236
+
237
+ def __post_init__(self) -> None:
238
+ """
239
+ Reject non-positive limits.
240
+
241
+ Raises:
242
+ ValueError: If any given limit is zero or negative.
243
+ """
244
+ for name in ("requests_per_second", "per_minute", "per_hour", "per_day"):
245
+ value = getattr(self, name)
246
+ if value is not None and not value > 0:
247
+ msg = f"RateLimit.{name} must be positive, got {value!r}."
248
+ raise ValueError(msg)
249
+
250
+ @property
251
+ def interval(self) -> float:
252
+ """
253
+ Minimum seconds between two requests (``0.0`` for no spacing).
254
+
255
+ Returns:
256
+ float: The strictest spacing implied by the per-second, per-minute
257
+ and per-hour limits.
258
+ """
259
+ gaps = [0.0]
260
+ if self.requests_per_second:
261
+ gaps.append(1.0 / self.requests_per_second)
262
+ if self.per_minute:
263
+ gaps.append(60.0 / self.per_minute)
264
+ if self.per_hour:
265
+ gaps.append(3600.0 / self.per_hour)
266
+ return max(gaps)
267
+
268
+ def describe(self) -> str:
269
+ """
270
+ Return the limit in words, for README tables and error messages.
271
+
272
+ Returns:
273
+ str: For example ``"1 request every 2 s; 25 per day"``.
274
+ """
275
+ parts = []
276
+ if self.interval:
277
+ parts.append(f"1 request every {self.interval:g} s")
278
+ if self.per_day:
279
+ parts.append(f"{self.per_day} per day")
280
+ text = "; ".join(parts) or "no limit"
281
+ return f"{text} ({self.source})" if self.source else text
282
+
283
+
284
+ class _SharedState:
285
+ """Request history shared by every throttle with the same key."""
286
+
287
+ def __init__(self) -> None:
288
+ """Start with no request recorded."""
289
+ self.last: float | None = None
290
+ self.lock = threading.Lock()
291
+ # One daily ledger per key, so every client counts against one quota.
292
+ self.ledger: _DayLedger | None = None
293
+ # One asyncio lock per event loop, shared by every AsyncThrottle of
294
+ # the key, so two clients in one loop cannot send at the same instant.
295
+ self.async_locks: dict[int, tuple[asyncio.AbstractEventLoop, asyncio.Lock]] = {}
296
+
297
+ def async_lock(self, loop: asyncio.AbstractEventLoop) -> asyncio.Lock:
298
+ """
299
+ Return the key's asyncio lock for ``loop``, creating it once.
300
+
301
+ Args:
302
+ loop (asyncio.AbstractEventLoop): The running loop.
303
+
304
+ Returns:
305
+ asyncio.Lock: The lock every throttle of this key uses in ``loop``.
306
+ """
307
+ with self.lock:
308
+ entry = self.async_locks.get(id(loop))
309
+ if entry is None or entry[0] is not loop:
310
+ # Drop locks of closed loops so the map does not grow.
311
+ self.async_locks = {
312
+ k: v for k, v in self.async_locks.items() if not v[0].is_closed()
313
+ }
314
+ entry = (loop, asyncio.Lock())
315
+ self.async_locks[id(loop)] = entry
316
+ return entry[1]
317
+
318
+
319
+ #: One state per throttle key, so every client of a provider in this process
320
+ #: (and every thread) draws on the same budget.
321
+ _SHARED: dict[str, _SharedState] = {}
322
+ _SHARED_LOCK = threading.Lock()
323
+
324
+
325
+ def _shared_state(key: str | None) -> _SharedState:
326
+ """
327
+ Return the state for ``key``, or a private one when ``key`` is ``None``.
328
+
329
+ Args:
330
+ key (str | None): Throttle key, usually the provider's host.
331
+
332
+ Returns:
333
+ _SharedState: The state to use.
334
+ """
335
+ if key is None:
336
+ return _SharedState()
337
+ with _SHARED_LOCK:
338
+ return _SHARED.setdefault(key, _SharedState())
339
+
340
+
341
+ class _DayLedger:
342
+ """
343
+ Rolling 24-hour request count, kept on disk so it survives restarts.
344
+
345
+ The file holds the epoch times of the requests of the last 24 hours. It is
346
+ rewritten atomically after each request. Processes running at the same time
347
+ do not lock it, so they can undercount; the in-process count stays exact.
348
+ """
349
+
350
+ def __init__(self, limit: int, path: Path | None) -> None:
351
+ """
352
+ Load the times still inside the window.
353
+
354
+ Args:
355
+ limit (int): Most requests in any 24 hours.
356
+ path (Path | None): The ledger file, or ``None`` to keep the count
357
+ in memory only.
358
+ """
359
+ self.limit = limit
360
+ self.path = path
361
+ self.times: list[float] = []
362
+ if path is not None and path.exists():
363
+ try:
364
+ raw = json.loads(path.read_text(encoding="utf-8"))
365
+ self.times = [float(t) for t in raw]
366
+ except (ValueError, TypeError, OSError):
367
+ self.times = [] # an unreadable ledger starts afresh
368
+ self._prune()
369
+
370
+ def _prune(self) -> None:
371
+ """Drop times older than 24 hours."""
372
+ cutoff = time.time() - _DAY
373
+ self.times = [t for t in self.times if t > cutoff]
374
+
375
+ def check(self) -> None:
376
+ """
377
+ Raise when the quota is used up.
378
+
379
+ Raises:
380
+ QuotaExhausted: If ``limit`` requests were made in the last 24 h.
381
+ """
382
+ self._prune()
383
+ if len(self.times) >= self.limit:
384
+ free_in = self.times[0] + _DAY - time.time()
385
+ msg = (
386
+ f"Daily quota of {self.limit} requests used up; the next "
387
+ f"request is allowed in {free_in / 3600:.1f} h."
388
+ )
389
+ raise QuotaExhausted(msg)
390
+
391
+ def record(self) -> None:
392
+ """Add a request now and save the ledger."""
393
+ self.times.append(time.time())
394
+ if self.path is None:
395
+ return
396
+ self.path.parent.mkdir(parents=True, exist_ok=True)
397
+ fd, tmp = tempfile.mkstemp(dir=self.path.parent, suffix=".tmp")
398
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
399
+ json.dump(self.times, fh)
400
+ Path(tmp).replace(self.path)
401
+
402
+
403
+ _DAY = 86400.0
404
+
405
+
406
+ def _ledger_path(key: str | None, ledger_dir: Path | None) -> Path | None:
407
+ """
408
+ Return where a key's daily ledger lives.
409
+
410
+ Args:
411
+ key (str | None): Throttle key; without one the count stays in memory.
412
+ ledger_dir (Path | None): Directory; ``~/.cache/wrapkit/rate_limits``
413
+ when ``None``.
414
+
415
+ Returns:
416
+ Path | None: The ledger file, or ``None`` when there is no key.
417
+ """
418
+ if key is None:
419
+ return None
420
+ base = ledger_dir or Path.home() / ".cache" / "wrapkit" / "rate_limits"
421
+ safe = "".join(c if c.isalnum() or c in "-._" else "_" for c in key)
422
+ return base / f"{safe}.json"
423
+
424
+
425
+ class Throttle:
426
+ """
427
+ Keep requests within a rate, and within a provider's limit if one is given.
428
+
429
+ Call :meth:`wait` right before each network request (never for cache hits).
430
+ The first request never waits.
431
+
432
+ Without ``limit`` it keeps ``1 / requests_per_second`` seconds between
433
+ requests, and ``None`` or ``0`` turns it off. With ``limit`` the provider's
434
+ limit is a hard ceiling: ``requests_per_second`` may only slow it down,
435
+ ``None`` or ``0`` means "as fast as the limit allows", and asking for more
436
+ raises :class:`RateLimitError`. Throttles built with the same ``key`` share
437
+ one request history in this process, across instances and threads.
438
+ """
439
+
440
+ def __init__(
441
+ self,
442
+ requests_per_second: float | None = None,
443
+ logger: logging.Logger | None = None,
444
+ *,
445
+ limit: RateLimit | None = None,
446
+ key: str | None = None,
447
+ ledger_dir: Path | None = None,
448
+ ) -> None:
449
+ """
450
+ Set the rate.
451
+
452
+ Args:
453
+ requests_per_second (float | None): The caller's rate; ``None`` or
454
+ ``0`` for no throttle (or, with ``limit``, the limit's rate).
455
+ logger (logging.Logger | None): Receives a DEBUG line per sleep.
456
+ limit (RateLimit | None): The provider's limit, never exceeded.
457
+ key (str | None): Shares the request history (and the daily
458
+ ledger) with every throttle of the same key.
459
+ ledger_dir (Path | None): Where daily ledgers are kept.
460
+
461
+ Raises:
462
+ RateLimitError: If ``requests_per_second`` is faster than
463
+ ``limit`` allows.
464
+ """
465
+ asked = 1.0 / requests_per_second if requests_per_second else 0.0
466
+ if limit is not None and asked and asked < limit.interval - 1e-9:
467
+ msg = (
468
+ f"requests_per_second={requests_per_second} exceeds the "
469
+ f"provider's limit: {limit.describe()}."
470
+ )
471
+ raise RateLimitError(msg)
472
+ self.limit = limit
473
+ self.interval = max(asked, limit.interval if limit else 0.0)
474
+ self.logger = logger
475
+ self._state = _shared_state(key)
476
+ self._ledger = (
477
+ self._shared_ledger(limit.per_day, _ledger_path(key, ledger_dir))
478
+ if limit is not None and limit.per_day
479
+ else None
480
+ )
481
+
482
+ def _shared_ledger(self, per_day: int, path: Path | None) -> _DayLedger:
483
+ """
484
+ Return the key's daily ledger, creating it on first use.
485
+
486
+ Every throttle of a key counts against one ledger; if two of them
487
+ state different daily limits, the stricter one applies.
488
+
489
+ Args:
490
+ per_day (int): Most requests in any 24 hours.
491
+ path (Path | None): The ledger file.
492
+
493
+ Returns:
494
+ _DayLedger: The shared ledger.
495
+ """
496
+ with self._state.lock:
497
+ ledger = self._state.ledger
498
+ if ledger is None:
499
+ ledger = self._state.ledger = _DayLedger(per_day, path)
500
+ else:
501
+ ledger.limit = min(ledger.limit, per_day)
502
+ return ledger
503
+
504
+ def _shortfall(self) -> float:
505
+ """
506
+ Return how long the next request must wait (``0.0`` for none).
507
+
508
+ Returns:
509
+ float: Seconds still to wait.
510
+ """
511
+ last = self._state.last
512
+ if not self.interval or last is None:
513
+ return 0.0
514
+ return self.interval - (time.monotonic() - last)
515
+
516
+ def _log(self, wait: float) -> None:
517
+ """
518
+ Log a sleep at DEBUG.
519
+
520
+ Args:
521
+ wait (float): The sleep in seconds.
522
+ """
523
+ if self.logger is not None:
524
+ self.logger.debug("Throttling: sleeping %.3fs", wait)
525
+
526
+ def _admit(self) -> None:
527
+ """Record the request in the shared history and the daily ledger."""
528
+ if self._ledger is not None:
529
+ self._ledger.record()
530
+ self._state.last = time.monotonic()
531
+
532
+ def wait(self) -> None:
533
+ """
534
+ Sleep just enough to respect the rate, then record the request.
535
+
536
+ When a daily quota is used up, :class:`QuotaExhausted` propagates from
537
+ the ledger and nothing is recorded or sent.
538
+ """
539
+ if not self.interval and self._ledger is None:
540
+ return
541
+ with self._state.lock:
542
+ if self._ledger is not None:
543
+ self._ledger.check()
544
+ wait = self._shortfall()
545
+ if wait > 0:
546
+ self._log(wait)
547
+ time.sleep(wait)
548
+ self._admit()
549
+
550
+
551
+ class AsyncThrottle(Throttle):
552
+ """
553
+ The async twin of :class:`Throttle`; its waits do not block the loop.
554
+
555
+ One throttle can serve several event loops in turn (one ``asyncio.run`` per
556
+ call, for example): its lock is made for the loop that is running, and
557
+ shared by every throttle with the same key in that loop.
558
+ """
559
+
560
+ def __init__(
561
+ self,
562
+ requests_per_second: float | None = None,
563
+ logger: logging.Logger | None = None,
564
+ *,
565
+ limit: RateLimit | None = None,
566
+ key: str | None = None,
567
+ ledger_dir: Path | None = None,
568
+ ) -> None:
569
+ """
570
+ Set the rate.
571
+
572
+ Args:
573
+ requests_per_second (float | None): As for :class:`Throttle`.
574
+ logger (logging.Logger | None): Receives a DEBUG line per sleep.
575
+ limit (RateLimit | None): The provider's limit, never exceeded.
576
+ key (str | None): Shares the request history with every throttle
577
+ of the same key.
578
+ ledger_dir (Path | None): Where daily ledgers are kept.
579
+ """
580
+ super().__init__(
581
+ requests_per_second, logger, limit=limit, key=key, ledger_dir=ledger_dir
582
+ )
583
+
584
+ async def await_turn(self) -> None:
585
+ """
586
+ Sleep just enough to respect the rate; concurrent callers queue up.
587
+
588
+ When a daily quota is used up, :class:`QuotaExhausted` propagates from
589
+ the ledger and nothing is recorded or sent.
590
+ """
591
+ if not self.interval and self._ledger is None:
592
+ return
593
+ # The key's lock for this loop: every AsyncThrottle of the key queues
594
+ # on it. A lock that once had a waiter belongs to that loop for good.
595
+ async with self._state.async_lock(asyncio.get_running_loop()):
596
+ if self._ledger is not None:
597
+ self._ledger.check()
598
+ wait = self._shortfall()
599
+ if wait > 0:
600
+ self._log(wait)
601
+ await asyncio.sleep(wait)
602
+ self._admit()
603
+
604
+
605
+ def _log_retry(
606
+ logger: logging.Logger | None,
607
+ label: str,
608
+ wait: float,
609
+ attempt: int,
610
+ attempts: int,
611
+ reason: str,
612
+ ) -> None:
613
+ """
614
+ Log at WARNING that a request is about to be retried.
615
+
616
+ Args:
617
+ logger (logging.Logger | None): Where to log, if anywhere.
618
+ label (str): What is being requested, without any secret.
619
+ wait (float): Seconds until the retry.
620
+ attempt (int): The attempt about to be made, starting at 2.
621
+ attempts (int): Total attempts allowed.
622
+ reason (str): Why the previous attempt failed.
623
+ """
624
+ if logger is not None:
625
+ logger.warning(
626
+ "Retrying GET %s in %.1fs (attempt %d/%d): %s",
627
+ label,
628
+ wait,
629
+ attempt,
630
+ attempts,
631
+ reason,
632
+ )
633
+
634
+
635
+ def _log_gave_up(
636
+ logger: logging.Logger | None, name: str, retry_after: str | None
637
+ ) -> None:
638
+ """
639
+ Warn that a server's ``Retry-After`` is too long to wait out.
640
+
641
+ Args:
642
+ logger (logging.Logger | None): The logger; nothing is logged when
643
+ ``None``.
644
+ name (str): Secret-free name of the request.
645
+ retry_after (str | None): The ``Retry-After`` header.
646
+ """
647
+ if logger is not None:
648
+ logger.warning(
649
+ "%s: server asks to retry after %ss, longer than the retry policy "
650
+ "allows; not retrying",
651
+ name,
652
+ retry_after,
653
+ )
654
+
655
+
656
+ def get_with_retries(
657
+ session: requests.Session,
658
+ url: str,
659
+ *,
660
+ policy: RetryPolicy | None = None,
661
+ throttle: Throttle | None = None,
662
+ logger: logging.Logger | None = None,
663
+ label: str | None = None,
664
+ **kwargs: Any,
665
+ ) -> requests.Response:
666
+ """
667
+ GET ``url`` with ``session``, retrying transient failures.
668
+
669
+ Args:
670
+ session (requests.Session): The session to use.
671
+ url (str): The URL.
672
+ policy (RetryPolicy | None): Retry rules; the default
673
+ :class:`RetryPolicy` when ``None``.
674
+ throttle (Throttle | None): Waited on before every attempt.
675
+ logger (logging.Logger | None): Receives retry warnings and a DEBUG
676
+ line per answer.
677
+ label (str | None): Secret-free name of the request for log lines;
678
+ the URL when ``None`` (only safe when the URL holds no key).
679
+ **kwargs (Any): Passed to ``session.get`` (``params``, ``timeout``,
680
+ ``headers``, ...).
681
+
682
+ Returns:
683
+ requests.Response: The final answer, whatever its status.
684
+
685
+ Raises:
686
+ requests.RequestException: The last transport error, once retries are
687
+ used up, or at once when it is not worth retrying. Its message may
688
+ contain the full URL: redact before showing it.
689
+ """
690
+ policy = policy or RetryPolicy()
691
+ name = url if label is None else label
692
+ attempts = policy.max_retries + 1
693
+ attempt = 1
694
+ while True:
695
+ if throttle is not None:
696
+ throttle.wait()
697
+ started = time.monotonic()
698
+ try:
699
+ resp = session.get(url, **kwargs)
700
+ except requests.RequestException as exc:
701
+ if (
702
+ attempt >= attempts
703
+ or not isinstance(exc, RETRY_ERRORS)
704
+ or _cannot_heal(exc)
705
+ ):
706
+ raise
707
+ reason = type(exc).__name__
708
+ wait = policy.wait(attempt)
709
+ else:
710
+ if logger is not None:
711
+ logger.debug(
712
+ "HTTP %s for %s in %.2fs",
713
+ resp.status_code,
714
+ name,
715
+ time.monotonic() - started,
716
+ )
717
+ if attempt >= attempts or resp.status_code not in policy.statuses:
718
+ return resp
719
+ if policy.gives_up(resp.status_code, resp.headers.get("Retry-After")):
720
+ _log_gave_up(logger, name, resp.headers.get("Retry-After"))
721
+ return resp
722
+ reason = f"HTTP {resp.status_code}"
723
+ wait = policy.wait(
724
+ attempt, resp.status_code, resp.headers.get("Retry-After")
725
+ )
726
+ attempt += 1
727
+ _log_retry(logger, name, wait, attempt, attempts, reason)
728
+ time.sleep(wait)
729
+
730
+
731
+ async def aget_with_retries(
732
+ client: httpx.AsyncClient,
733
+ url: str,
734
+ *,
735
+ policy: RetryPolicy | None = None,
736
+ throttle: AsyncThrottle | None = None,
737
+ logger: logging.Logger | None = None,
738
+ label: str | None = None,
739
+ **kwargs: Any,
740
+ ) -> httpx.Response:
741
+ """
742
+ The async twin of :func:`get_with_retries`, for ``httpx``.
743
+
744
+ Args:
745
+ client (httpx.AsyncClient): The client to use.
746
+ url (str): The URL.
747
+ policy (RetryPolicy | None): Retry rules; the default
748
+ :class:`RetryPolicy` when ``None``.
749
+ throttle (AsyncThrottle | None): Awaited before every attempt.
750
+ logger (logging.Logger | None): Receives retry warnings and a DEBUG
751
+ line per answer.
752
+ label (str | None): Secret-free name of the request for log lines;
753
+ the URL when ``None``.
754
+ **kwargs (Any): Passed to ``client.get``.
755
+
756
+ Returns:
757
+ httpx.Response: The final answer, whatever its status.
758
+
759
+ Raises:
760
+ httpx.HTTPError: The last transport error, once retries are used up,
761
+ or at once when it is not worth retrying.
762
+ """
763
+ policy = policy or RetryPolicy()
764
+ name = url if label is None else label
765
+ attempts = policy.max_retries + 1
766
+ attempt = 1
767
+ while True:
768
+ if throttle is not None:
769
+ await throttle.await_turn()
770
+ started = time.monotonic()
771
+ try:
772
+ resp = await client.get(url, **kwargs)
773
+ except httpx.HTTPError as exc:
774
+ if (
775
+ attempt >= attempts
776
+ or not isinstance(exc, ASYNC_RETRY_ERRORS)
777
+ or _cannot_heal(exc)
778
+ ):
779
+ raise
780
+ reason = type(exc).__name__
781
+ wait = policy.wait(attempt)
782
+ else:
783
+ if logger is not None:
784
+ logger.debug(
785
+ "HTTP %s for %s in %.2fs",
786
+ resp.status_code,
787
+ name,
788
+ time.monotonic() - started,
789
+ )
790
+ if attempt >= attempts or resp.status_code not in policy.statuses:
791
+ return resp
792
+ if policy.gives_up(resp.status_code, resp.headers.get("Retry-After")):
793
+ _log_gave_up(logger, name, resp.headers.get("Retry-After"))
794
+ return resp
795
+ reason = f"HTTP {resp.status_code}"
796
+ wait = policy.wait(
797
+ attempt, resp.status_code, resp.headers.get("Retry-After")
798
+ )
799
+ attempt += 1
800
+ _log_retry(logger, name, wait, attempt, attempts, reason)
801
+ await asyncio.sleep(wait)
802
+
803
+
804
+ def user_agent(product: str, version: str, url: str) -> str:
805
+ """
806
+ Build the browser-like User-Agent the wrappers send.
807
+
808
+ Some APIs reject requests without a browser-like User-Agent and answer with
809
+ an error page instead of data.
810
+
811
+ Args:
812
+ product (str): Product token, such as ``"eia-api-wrapper"``.
813
+ version (str): Its version.
814
+ url (str): A URL identifying the data source or the project.
815
+
816
+ Returns:
817
+ str: ``Mozilla/5.0 (compatible; <product>/<version>; +<url>)``.
818
+ """
819
+ return f"Mozilla/5.0 (compatible; {product}/{version}; +{url})"