Coverage for data_pipeline/net_retry.py: 100%
23 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""A download that outlives a dropped connection (V6.6.0). The owner's WLAN can drop mid-run, and a fetch that fails must never read as "no data".
3Only a status the server chose (404, or 403 where a dated file doesn't exist) means absent. Anything else is retried, waiting out an outage; when the
4wait runs out it raises `NetworkOutage`, so the run stops with what it saved and resumes later instead of recording a hole.
5"""
7from __future__ import annotations
9import time as _time
10from collections.abc import Callable
13class NetworkOutage(RuntimeError):
14 """The network stayed down, or the server kept failing, for longer than the caller will wait."""
17def fetch(
18 url: str, *, get: Callable, absent_codes: tuple[int, ...] = (404,), max_wait_seconds: float = 3600.0, sleep: Callable[[float], None] = _time.sleep,
19 timeout: float = 120.0, **request_kwargs,
20):
21 """The response, or None when the server says the file doesn't exist. `get` is `requests.get` or a session's."""
22 waited = 0.0
23 delay = 5.0
24 last_problem = ""
25 while True:
26 try:
27 response = get(url, timeout=timeout, **request_kwargs)
28 except Exception as error: # requests raises several types for a dropped connection, and so do its dependencies
29 last_problem = f"{type(error).__name__}"
30 else:
31 if response.status_code in absent_codes:
32 return None
33 if response.ok:
34 return response
35 last_problem = f"HTTP {response.status_code}"
36 if waited >= max_wait_seconds:
37 raise NetworkOutage(f"{url}: {last_problem} after {waited:.0f} s")
38 sleep(delay)
39 waited += delay
40 delay = min(delay * 2.0, 120.0)