Skip to content

Commit e82f40a

Browse files
committed
Handle PyPI outages in the version check
Retry unreadable responses, honor bounded Retry-After delays, and report PyPI lookup failures in PR comments. Add regression coverage for retry and failure paths.
1 parent b66d0b1 commit e82f40a

4 files changed

Lines changed: 196 additions & 51 deletions

File tree

‎.github/workflows/version-check.yml‎

Lines changed: 14 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -42,15 +42,11 @@ jobs:
4242
4343
# Compare against the latest published PyPI release.
4444
python3 <<'PY'
45-
import http.client
46-
import json
4745
import os
4846
import subprocess
49-
import time
5047
import tomllib
51-
import urllib.error
52-
import urllib.request
5348
from packaging import version
49+
from scripts.ci.pypi_lookup import PyPILookupError, fetch_pypi_releases
5450
5551
pr_ver = version.parse(os.environ["PR_VERSION"])
5652
main_ver = version.parse(os.environ["MAIN_VERSION"])
@@ -75,50 +71,16 @@ jobs:
7571
)
7672
raise SystemExit(1)
7773
78-
# This is a required check, so a dropped connection to PyPI would
79-
# otherwise block the merge until someone reruns the job. Retry
80-
# network errors, timeouts, rate limits (429) and 5xx responses, and
81-
# if PyPI still can't be read, say so instead of failing with a bare
82-
# traceback that looks like a version problem. OSError covers
83-
# URLError, timeouts and SSL errors; HTTPException covers a response
84-
# cut off mid-read, which urllib doesn't wrap in URLError.
85-
pypi_url = "https://pypi.org/pypi/socketsecurity/json"
86-
attempts = 4
87-
pypi_data = None
88-
for attempt in range(1, attempts + 1):
89-
try:
90-
with urllib.request.urlopen(pypi_url, timeout=15) as response:
91-
pypi_data = json.load(response)
92-
break
93-
except urllib.error.HTTPError as exc:
94-
if exc.code < 500 and exc.code != 429:
95-
print(
96-
f"❌ PyPI returned HTTP {exc.code} for {pypi_url}, so the "
97-
f"latest published version couldn't be read. This is "
98-
f"not a problem with the version in this PR."
99-
)
100-
raise SystemExit(1)
101-
error = exc
102-
except (OSError, http.client.HTTPException) as exc:
103-
error = exc
104-
if attempt < attempts:
105-
delay = 2 ** attempt
106-
print(
107-
f"⚠️ PyPI request failed (attempt {attempt}/{attempts}): "
108-
f"{error!r}. Retrying in {delay}s."
109-
)
110-
time.sleep(delay)
111-
112-
if pypi_data is None:
113-
print(
114-
f"❌ Couldn't reach PyPI ({pypi_url}) after {attempts} attempts; "
115-
f"last error: {error!r}. This is a network problem, not a "
116-
f"problem with the version in this PR. Rerun the job."
117-
)
74+
try:
75+
releases = fetch_pypi_releases()
76+
except PyPILookupError as exc:
77+
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
78+
print("pypi_lookup_failed=true", file=output)
79+
print(f"❌ {exc}")
11880
raise SystemExit(1)
11981
12082
published_versions = []
121-
for raw in pypi_data.get("releases", {}).keys():
83+
for raw in releases:
12284
parsed = version.parse(raw)
12385
if not parsed.is_prerelease and not parsed.is_devrelease:
12486
published_versions.append(parsed)
@@ -191,9 +153,13 @@ jobs:
191153
MAIN_VERSION: ${{ env.MAIN_VERSION }}
192154
PR_VERSION: ${{ env.PR_VERSION }}
193155
CHECK_RESULT: ${{ steps.version_check.outcome }}
156+
PYPI_LOOKUP_FAILED: ${{ steps.version_check.outputs.pypi_lookup_failed }}
194157
with:
195158
script: |
196159
const success = process.env.CHECK_RESULT === 'success';
160+
const failureBody = process.env.PYPI_LOOKUP_FAILED === 'true'
161+
? '❌ **Version Check Failed**\n\nThe job could not read the latest release from PyPI. See the job log for details and rerun the check once PyPI is available.'
162+
: '❌ **Version Check Failed**\n\nSee the Version Check job log for details.';
197163
const prNumber = context.payload.pull_request.number;
198164
const owner = context.repo.owner;
199165
const repo = context.repo.repo;
@@ -222,7 +188,7 @@ jobs:
222188
owner: owner,
223189
repo: repo,
224190
comment_id: versionComment.id,
225-
body: `❌ **Version Check Failed**\n\nPlease increment...`
191+
body: failureBody
226192
});
227193
}
228194
} else if (!success) {
@@ -231,6 +197,6 @@ jobs:
231197
owner: owner,
232198
repo: repo,
233199
issue_number: prNumber,
234-
body: `❌ **Version Check Failed**\n\nPlease increment...`
200+
body: failureBody
235201
});
236202
}

‎CHANGELOG.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,9 +4,10 @@
44

55
### Changed: retry the PyPI lookup in the version check
66

7-
- The `check_version` CI job now retries the PyPI request on connection
8-
errors, timeouts, HTTP 429 and HTTP 5xx, and says when a failure is PyPI's
9-
rather than the PR's version. No change to the CLI itself.
7+
- The `check_version` CI job retries connection errors, timeouts, unreadable
8+
responses, HTTP 429, and HTTP 5xx. It honors PyPI's `Retry-After` header
9+
within its retry limits and reports PyPI lookup failures in the job log
10+
and PR comment.
1011

1112
## 2.16.0
1213

‎scripts/ci/pypi_lookup.py‎

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import http.client
2+
import json
3+
import time
4+
import urllib.error
5+
import urllib.request
6+
from datetime import UTC
7+
from email.utils import parsedate_to_datetime
8+
9+
PYPI_URL = "https://pypi.org/pypi/socketsecurity/json"
10+
ATTEMPTS = 4
11+
MAX_RETRY_WAIT = 60
12+
13+
14+
class PyPILookupError(Exception):
15+
pass
16+
17+
18+
def retry_after_seconds(value: str | None) -> float:
19+
if not value:
20+
return 0
21+
value = value.strip()
22+
try:
23+
if value.isascii() and value.isdecimal():
24+
return float(value)
25+
date = parsedate_to_datetime(value)
26+
if date.tzinfo is None:
27+
date = date.replace(tzinfo=UTC)
28+
return max(0, date.timestamp() - time.time())
29+
except (ValueError, OverflowError):
30+
return 0
31+
32+
33+
def fetch_pypi_releases() -> dict:
34+
for attempt in range(1, ATTEMPTS + 1):
35+
retry_after = 0
36+
try:
37+
with urllib.request.urlopen(PYPI_URL, timeout=15) as response:
38+
data = json.load(response)
39+
if not isinstance(data, dict) or not isinstance(data.get("releases"), dict):
40+
raise ValueError("Expected a PyPI response with a releases object")
41+
return data["releases"]
42+
except urllib.error.HTTPError as exc:
43+
exc.close()
44+
if exc.code != 429 and not 500 <= exc.code < 600:
45+
raise PyPILookupError(
46+
f"PyPI returned HTTP {exc.code} for {PYPI_URL}."
47+
) from exc
48+
error = exc
49+
if exc.headers is not None:
50+
retry_after = retry_after_seconds(exc.headers.get("Retry-After"))
51+
except (OSError, http.client.HTTPException, ValueError) as exc:
52+
error = exc
53+
54+
if attempt == ATTEMPTS:
55+
raise PyPILookupError(
56+
f"Could not read releases from PyPI ({PYPI_URL}) after {attempt} attempts. "
57+
f"Last error: {error!r}. Rerun the check once PyPI is available."
58+
) from error
59+
60+
delay = max(2**attempt, retry_after)
61+
if delay > MAX_RETRY_WAIT:
62+
raise PyPILookupError(
63+
f"PyPI requested a retry delay longer than {MAX_RETRY_WAIT} seconds "
64+
f"after {error!r}. Rerun the check once PyPI is available."
65+
) from error
66+
67+
print(
68+
f"⚠️ PyPI request failed (attempt {attempt}/{ATTEMPTS}): {error!r}. Retrying in {delay:g}s.",
69+
flush=True,
70+
)
71+
time.sleep(delay)

‎tests/unit/test_pypi_lookup.py‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import http.client
2+
from email.message import Message
3+
from email.utils import formatdate
4+
from importlib import import_module
5+
from io import BytesIO
6+
from pathlib import Path
7+
from unittest.mock import Mock
8+
from urllib.error import HTTPError, URLError
9+
10+
import pytest
11+
12+
13+
@pytest.fixture
14+
def pypi_lookup(monkeypatch):
15+
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2]))
16+
return import_module("scripts.ci.pypi_lookup")
17+
18+
19+
@pytest.fixture
20+
def pypi_request(monkeypatch, pypi_lookup):
21+
request = Mock()
22+
sleep = Mock()
23+
monkeypatch.setattr(pypi_lookup.urllib.request, "urlopen", request)
24+
monkeypatch.setattr(pypi_lookup.time, "sleep", sleep)
25+
return request, sleep
26+
27+
28+
def http_error(status, retry_after=None):
29+
headers = Message()
30+
if retry_after is not None:
31+
headers["Retry-After"] = retry_after
32+
return HTTPError("https://pypi.org", status, "test error", headers, BytesIO())
33+
34+
35+
@pytest.mark.parametrize(
36+
"failure",
37+
[
38+
pytest.param(lambda: URLError("connection reset"), id="connection"),
39+
pytest.param(TimeoutError, id="timeout"),
40+
pytest.param(lambda: http.client.IncompleteRead(b"{"), id="incomplete-read"),
41+
pytest.param(lambda: BytesIO(b'{"releases":'), id="truncated-json"),
42+
pytest.param(lambda: BytesIO(b'{"releases":null}'), id="invalid-releases"),
43+
pytest.param(lambda: http_error(429), id="rate-limit"),
44+
pytest.param(lambda: http_error(503), id="service-unavailable"),
45+
],
46+
)
47+
def test_pypi_lookup_recovers_after_retry(pypi_lookup, pypi_request, failure):
48+
request, sleep = pypi_request
49+
request.side_effect = [failure(), BytesIO(b'{"releases":{"2.16.0":[]}}')]
50+
51+
assert pypi_lookup.fetch_pypi_releases() == {"2.16.0": []}
52+
assert request.call_count == 2
53+
request.assert_called_with(pypi_lookup.PYPI_URL, timeout=15)
54+
sleep.assert_called_once_with(2)
55+
56+
57+
def test_pypi_lookup_reports_exhausted_retries(pypi_lookup, pypi_request):
58+
request, sleep = pypi_request
59+
request.side_effect = TimeoutError("read timed out")
60+
61+
with pytest.raises(pypi_lookup.PyPILookupError, match="after 4 attempts"):
62+
pypi_lookup.fetch_pypi_releases()
63+
64+
assert request.call_count == 4
65+
assert [call.args[0] for call in sleep.call_args_list] == [2, 4, 8]
66+
67+
68+
def test_pypi_lookup_does_not_retry_permanent_http_error(pypi_lookup, pypi_request):
69+
request, sleep = pypi_request
70+
request.side_effect = http_error(404)
71+
72+
with pytest.raises(pypi_lookup.PyPILookupError, match="HTTP 404"):
73+
pypi_lookup.fetch_pypi_releases()
74+
75+
assert request.call_count == 1
76+
sleep.assert_not_called()
77+
78+
79+
@pytest.mark.parametrize(
80+
("status", "header", "delay"),
81+
[
82+
(429, "30", 30),
83+
(503, formatdate(1_030, usegmt=True), 30),
84+
(429, "invalid", 2),
85+
(429, "1", 2),
86+
],
87+
)
88+
def test_pypi_lookup_honors_retry_after(
89+
pypi_lookup, pypi_request, monkeypatch, status, header, delay
90+
):
91+
request, sleep = pypi_request
92+
monkeypatch.setattr(pypi_lookup.time, "time", lambda: 1_000)
93+
request.side_effect = [http_error(status, header), BytesIO(b'{"releases":{}}')]
94+
95+
assert pypi_lookup.fetch_pypi_releases() == {}
96+
sleep.assert_called_once_with(delay)
97+
98+
99+
def test_pypi_lookup_stops_when_retry_after_exceeds_limit(pypi_lookup, pypi_request):
100+
request, sleep = pypi_request
101+
request.side_effect = http_error(429, "120")
102+
103+
with pytest.raises(pypi_lookup.PyPILookupError, match="longer than 60 seconds"):
104+
pypi_lookup.fetch_pypi_releases()
105+
106+
assert request.call_count == 1
107+
sleep.assert_not_called()

0 commit comments

Comments
 (0)