Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 17 additions & 9 deletions .github/workflows/version-check.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,23 +31,22 @@ jobs:

# Get version from current PR
PR_VERSION=$(grep -o "__version__.*" socketsecurity/__init__.py | awk '{print $3}' | tr -d "'")
echo "PR_VERSION=$PR_VERSION" >> $GITHUB_ENV
echo "PR_VERSION=$PR_VERSION" >> "$GITHUB_ENV"

# Get version from main branch
MAIN_VERSION=$(git show origin/main:socketsecurity/__init__.py | grep -o "__version__.*" | awk '{print $3}' | tr -d "'")
echo "MAIN_VERSION=$MAIN_VERSION" >> $GITHUB_ENV
echo "MAIN_VERSION=$MAIN_VERSION" >> "$GITHUB_ENV"

export PR_VERSION
export MAIN_VERSION

# Compare against the latest published PyPI release.
python3 <<'PY'
import json
import os
import subprocess
import tomllib
import urllib.request
from packaging import version
from scripts.ci.pypi_lookup import PyPILookupError, fetch_pypi_releases

pr_ver = version.parse(os.environ["PR_VERSION"])
main_ver = version.parse(os.environ["MAIN_VERSION"])
Expand All @@ -72,11 +71,16 @@ jobs:
)
raise SystemExit(1)

with urllib.request.urlopen("https://pypi.org/pypi/socketsecurity/json") as response:
pypi_data = json.load(response)
try:
releases = fetch_pypi_releases()
except PyPILookupError as exc:
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
print("pypi_lookup_failed=true", file=output)
print(f"❌ {exc}")
raise SystemExit(1)

published_versions = []
for raw in pypi_data.get("releases", {}).keys():
for raw in releases:
parsed = version.parse(raw)
if not parsed.is_prerelease and not parsed.is_devrelease:
published_versions.append(parsed)
Expand Down Expand Up @@ -149,9 +153,13 @@ jobs:
MAIN_VERSION: ${{ env.MAIN_VERSION }}
PR_VERSION: ${{ env.PR_VERSION }}
CHECK_RESULT: ${{ steps.version_check.outcome }}
PYPI_LOOKUP_FAILED: ${{ steps.version_check.outputs.pypi_lookup_failed }}
with:
script: |
const success = process.env.CHECK_RESULT === 'success';
const failureBody = process.env.PYPI_LOOKUP_FAILED === 'true'
? '❌ **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.'
: '❌ **Version Check Failed**\n\nSee the Version Check job log for details.';
const prNumber = context.payload.pull_request.number;
const owner = context.repo.owner;
const repo = context.repo.repo;
Expand Down Expand Up @@ -180,7 +188,7 @@ jobs:
owner: owner,
repo: repo,
comment_id: versionComment.id,
body: `❌ **Version Check Failed**\n\nPlease increment...`
body: failureBody
});
}
} else if (!success) {
Expand All @@ -189,6 +197,6 @@ jobs:
owner: owner,
repo: repo,
issue_number: prNumber,
body: `❌ **Version Check Failed**\n\nPlease increment...`
body: failureBody
});
}
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
# Changelog

## 2.16.1

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

- The `check_version` CI job retries connection errors, timeouts, unreadable
responses, HTTP 429, and HTTP 5xx. It honors PyPI's `Retry-After` header
within its retry limits and reports PyPI lookup failures in the job log
and PR comment.

## 2.16.0

### Added
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ build-backend = "hatchling.build"

[project]
name = "socketsecurity"
version = "2.16.0"
version = "2.16.1"
requires-python = ">= 3.11"
license = {"file" = "LICENSE"}
dependencies = [
Expand Down
71 changes: 71 additions & 0 deletions scripts/ci/pypi_lookup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import http.client
import json
import time
import urllib.error
import urllib.request
from datetime import UTC
from email.utils import parsedate_to_datetime

PYPI_URL = "https://pypi.org/pypi/socketsecurity/json"
ATTEMPTS = 4
MAX_RETRY_WAIT = 60


class PyPILookupError(Exception):
pass


def retry_after_seconds(value: str | None) -> float:
if not value:
return 0
value = value.strip()
try:
if value.isascii() and value.isdecimal():
return float(value)
date = parsedate_to_datetime(value)
if date.tzinfo is None:
date = date.replace(tzinfo=UTC)
return max(0, date.timestamp() - time.time())
except (ValueError, OverflowError):
return 0


def fetch_pypi_releases() -> dict:
for attempt in range(1, ATTEMPTS + 1):
retry_after = 0
try:
with urllib.request.urlopen(PYPI_URL, timeout=15) as response:
data = json.load(response)
if not isinstance(data, dict) or not isinstance(data.get("releases"), dict):
raise ValueError("Expected a PyPI response with a releases object")
return data["releases"]
except urllib.error.HTTPError as exc:
exc.close()
if exc.code != 429 and not 500 <= exc.code < 600:
raise PyPILookupError(
f"PyPI returned HTTP {exc.code} for {PYPI_URL}."
) from exc
error = exc
if exc.headers is not None:
retry_after = retry_after_seconds(exc.headers.get("Retry-After"))
except (OSError, http.client.HTTPException, ValueError) as exc:
error = exc

if attempt == ATTEMPTS:
raise PyPILookupError(
f"Could not read releases from PyPI ({PYPI_URL}) after {attempt} attempts. "
f"Last error: {error!r}. Rerun the check once PyPI is available."
) from error

delay = max(2**attempt, retry_after)
if delay > MAX_RETRY_WAIT:
raise PyPILookupError(
f"PyPI requested a retry delay longer than {MAX_RETRY_WAIT} seconds "
f"after {error!r}. Rerun the check once PyPI is available."
) from error

print(
f"⚠️ PyPI request failed (attempt {attempt}/{ATTEMPTS}): {error!r}. Retrying in {delay:g}s.",
flush=True,
)
time.sleep(delay)
2 changes: 1 addition & 1 deletion socketsecurity/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
__author__ = 'socket.dev'
__version__ = '2.16.0'
__version__ = '2.16.1'
USER_AGENT_NAME = 'socket-python-cli'
USER_AGENT = f'{USER_AGENT_NAME}/{__version__}'
107 changes: 107 additions & 0 deletions tests/unit/test_pypi_lookup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
import http.client
from email.message import Message
from email.utils import formatdate
from importlib import import_module
from io import BytesIO
from pathlib import Path
from unittest.mock import Mock
from urllib.error import HTTPError, URLError

import pytest


@pytest.fixture
def pypi_lookup(monkeypatch):
monkeypatch.syspath_prepend(str(Path(__file__).resolve().parents[2]))
return import_module("scripts.ci.pypi_lookup")


@pytest.fixture
def pypi_request(monkeypatch, pypi_lookup):
request = Mock()
sleep = Mock()
monkeypatch.setattr(pypi_lookup.urllib.request, "urlopen", request)
monkeypatch.setattr(pypi_lookup.time, "sleep", sleep)
return request, sleep


def http_error(status, retry_after=None):
headers = Message()
if retry_after is not None:
headers["Retry-After"] = retry_after
return HTTPError("https://pypi.org", status, "test error", headers, BytesIO())


@pytest.mark.parametrize(
"failure",
[
pytest.param(lambda: URLError("connection reset"), id="connection"),
pytest.param(TimeoutError, id="timeout"),
pytest.param(lambda: http.client.IncompleteRead(b"{"), id="incomplete-read"),
pytest.param(lambda: BytesIO(b'{"releases":'), id="truncated-json"),
pytest.param(lambda: BytesIO(b'{"releases":null}'), id="invalid-releases"),
pytest.param(lambda: http_error(429), id="rate-limit"),
pytest.param(lambda: http_error(503), id="service-unavailable"),
],
)
def test_pypi_lookup_recovers_after_retry(pypi_lookup, pypi_request, failure):
request, sleep = pypi_request
request.side_effect = [failure(), BytesIO(b'{"releases":{"2.16.0":[]}}')]

assert pypi_lookup.fetch_pypi_releases() == {"2.16.0": []}
assert request.call_count == 2
request.assert_called_with(pypi_lookup.PYPI_URL, timeout=15)
sleep.assert_called_once_with(2)


def test_pypi_lookup_reports_exhausted_retries(pypi_lookup, pypi_request):
request, sleep = pypi_request
request.side_effect = TimeoutError("read timed out")

with pytest.raises(pypi_lookup.PyPILookupError, match="after 4 attempts"):
pypi_lookup.fetch_pypi_releases()

assert request.call_count == 4
assert [call.args[0] for call in sleep.call_args_list] == [2, 4, 8]


def test_pypi_lookup_does_not_retry_permanent_http_error(pypi_lookup, pypi_request):
request, sleep = pypi_request
request.side_effect = http_error(404)

with pytest.raises(pypi_lookup.PyPILookupError, match="HTTP 404"):
pypi_lookup.fetch_pypi_releases()

assert request.call_count == 1
sleep.assert_not_called()


@pytest.mark.parametrize(
("status", "header", "delay"),
[
(429, "30", 30),
(503, formatdate(1_030, usegmt=True), 30),
(429, "invalid", 2),
(429, "1", 2),
],
)
def test_pypi_lookup_honors_retry_after(
pypi_lookup, pypi_request, monkeypatch, status, header, delay
):
request, sleep = pypi_request
monkeypatch.setattr(pypi_lookup.time, "time", lambda: 1_000)
request.side_effect = [http_error(status, header), BytesIO(b'{"releases":{}}')]

assert pypi_lookup.fetch_pypi_releases() == {}
sleep.assert_called_once_with(delay)


def test_pypi_lookup_stops_when_retry_after_exceeds_limit(pypi_lookup, pypi_request):
request, sleep = pypi_request
request.side_effect = http_error(429, "120")

with pytest.raises(pypi_lookup.PyPILookupError, match="longer than 60 seconds"):
pypi_lookup.fetch_pypi_releases()

assert request.call_count == 1
sleep.assert_not_called()
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.