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
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,12 @@ except ProoflineError as error:
print(error.detail)
```

For an HTTP 429 or 503, `error.retry_after_seconds` exposes the server's
`Retry-After` delay as a nonnegative number of seconds. A past HTTP date gives
`0.0`. A missing or invalid header gives `None`, as do other statuses. A caller
that schedules reads can use a valid delay even when it exceeds the SDK's
60-second automatic retry limit. The hint does not authorize replaying a write.

## Holding a wait to a commit

`request_review` names a pull request, and its response names no commit: the review belongs to the head the pull request has when the request arrives. To accept a result only for the commit you hold, pass that commit to `wait_for_review`.
Expand Down
33 changes: 26 additions & 7 deletions proofline/_transport.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,8 @@ class ProoflineError(Exception):
title names the server's problem class. A refused review request also
carries the typed refusal, whose reason names the setting to change, and
the repository_name it refers to.

retry_after_seconds is the server's parsed delay on a 429 or 503 response.
"""

def __init__(
Expand All @@ -96,13 +98,15 @@ def __init__(
title: str | None = None,
refusal: RunNowRefusal | None = None,
repository_name: str | None = None,
retry_after_seconds: float | None = None,
) -> None:
self.status = status
self.type = type
self.detail = detail
self.title = title
self.refusal = refusal
self.repository_name = repository_name
self.retry_after_seconds = retry_after_seconds
super().__init__(f"Proofline request failed (HTTP {status}).")

def __repr__(self) -> str:
Expand Down Expand Up @@ -195,10 +199,9 @@ def limit_timeout(request: httpx2.Request) -> None:
}


def retry_delay(value: str | None, attempt: int) -> float | None:
"""An invalid or longer Retry-After returns the problem without an early retry."""
def parse_retry_after(value: str | None) -> float | None:
if value is None:
return float(2**attempt)
return None
value = value.strip()
if value.isascii() and value.isdigit():
try:
Expand Down Expand Up @@ -229,7 +232,15 @@ def retry_delay(value: str | None, attempt: int) -> float | None:
delay = max(0.0, (date - now).total_seconds())
except (ValueError, TypeError, OverflowError):
return None
return delay if math.isfinite(delay) and delay <= 60 else None
return delay if math.isfinite(delay) else None


def retry_delay(response: httpx2.Response, error: ProoflineError, attempt: int) -> float | None:
"""An invalid or longer Retry-After returns the problem without an early retry."""
if "Retry-After" not in response.headers:
return float(2**attempt)
delay = error.retry_after_seconds
return delay if delay is not None and delay <= 60 else None


def redacted(value: object, raw: str) -> object:
Expand Down Expand Up @@ -277,6 +288,11 @@ def text(value: object) -> bool:


def problem(response: httpx2.Response, token: SecretStr) -> ProoflineError:
retry_after_seconds = (
parse_retry_after(response.headers.get("Retry-After"))
if response.status_code in (429, 503)
else None
)
try:
body = response.json()
except (ValueError, UnicodeError):
Expand All @@ -286,6 +302,7 @@ def problem(response: httpx2.Response, token: SecretStr) -> ProoflineError:
response.status_code,
"about:blank",
"Proofline returned an HTTP error without a problem document.",
retry_after_seconds=retry_after_seconds,
)
body = cast(dict[str, Any], redacted(body, token.get_secret_value()))
kind = body["type"] if isinstance(body.get("type"), str) else "about:blank"
Expand All @@ -300,7 +317,9 @@ def problem(response: httpx2.Response, token: SecretStr) -> ProoflineError:
# The contract types a refusal only as a review request's 400. The 402 a
# credit refusal answers is undocumented, so it stays a plain problem.
if response.status_code != 400 or "refusal" not in body:
return ProoflineError(response.status_code, kind, detail, title=title)
return ProoflineError(
response.status_code, kind, detail, title=title, retry_after_seconds=retry_after_seconds
)
try:
view = body["refusal"]
shape = isinstance(view, dict) and REFUSAL_SHAPES.get(str(view.get("reason")))
Expand Down Expand Up @@ -468,7 +487,7 @@ def handle_request(self, request: httpx2.Request) -> httpx2.Response:
error = unreadable_problem(response.status_code)
finally:
response.close()
delay = retry_delay(response.headers.get("Retry-After"), attempt)
delay = retry_delay(response, error, attempt)
if (
request.method != "GET"
or response.status_code not in (429, 503)
Expand Down Expand Up @@ -519,7 +538,7 @@ async def handle_async_request(self, request: httpx2.Request) -> httpx2.Response
error = unreadable_problem(response.status_code)
finally:
await response.aclose()
delay = retry_delay(response.headers.get("Retry-After"), attempt)
delay = retry_delay(response, error, attempt)
if (
request.method != "GET"
or response.status_code not in (429, 503)
Expand Down
34 changes: 33 additions & 1 deletion tests/test_http.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,6 +841,7 @@ async def test_retry_count_is_bounded_for_rate_limit_and_provider_unavailable(
with pytest.raises(ProoflineError) as raised:
await call(client, "get_finding", ORG, FINDING)
assert raised.value.status == status
assert raised.value.retry_after_seconds == 0
assert len(server.requests) == 4
with Server(
lambda request, index: Reply(status, {"detail": "Unavailable."}, {"Retry-After": "0"})
Expand All @@ -849,6 +850,7 @@ async def test_retry_count_is_bounded_for_rate_limit_and_provider_unavailable(
with pytest.raises(ProoflineError) as raised:
await call(client, "rerun_review", ORG, REVIEW)
assert raised.value.status == status
assert raised.value.retry_after_seconds == 0
assert len(server.requests) == 1
assert server.requests[0].method == "POST"
assert server.requests[0].path.endswith(f"/reviews/{REVIEW}/rerun")
Expand Down Expand Up @@ -885,14 +887,21 @@ def now(cls, tz: Any = None) -> datetime:

monkeypatch.setattr(_transport, "datetime", Calendar)
future = datetime(2069, 11, 6, 8, 49, 37, tzinfo=UTC)
for header in ["61", future.strftime("%A, %d-%b-%y %H:%M:%S GMT")]:
for header, expected in [
("61", 61.0),
(
future.strftime("%A, %d-%b-%y %H:%M:%S GMT"),
(future - Calendar.now()).total_seconds(),
),
]:
with Server(
lambda request, index: Reply(503, {"detail": "Unavailable."}, {"Retry-After": header})
) as server:
async with session(mode, server.url) as client:
with pytest.raises(ProoflineError) as raised:
await call(client, "get_finding", ORG, FINDING)
assert raised.value.status == 503
assert raised.value.retry_after_seconds == expected
assert len(server.requests) == 1
# An obsolete year more than fifty years ahead belongs to the past, not a later century.
for header in [
Expand Down Expand Up @@ -932,9 +941,32 @@ async def test_malformed_retry_after_refuses_retry_without_interpreting_number_a
with pytest.raises(ProoflineError) as raised:
await call(client, "get_finding", ORG, FINDING)
assert raised.value.status == 429
assert raised.value.retry_after_seconds is None
assert len(server.requests) == 1


@MODES
@pytest.mark.parametrize(
("status", "headers", "expected"),
[
(429, {}, None),
(503, {"Retry-After": "120"}, 120.0),
(403, {"Retry-After": "120"}, None),
],
)
async def test_retry_after_metadata_on_non_json_write_errors(
mode: str, status: int, headers: dict[str, str], expected: float | None
) -> None:
with Server(lambda request, index: Reply(status, b"proxy error", headers)) as server:
async with session(mode, server.url) as client:
with pytest.raises(ProoflineError) as raised:
await call(client, "rerun_review", ORG, REVIEW)
assert raised.value.status == status
assert raised.value.retry_after_seconds == expected
assert repr(raised.value) == f"ProoflineError(status={status})"
assert len(server.requests) == 1


@MODES
async def test_success_and_authority_problems_bound_wire_and_encoded_response_bodies(
mode: str, caplog: pytest.LogCaptureFixture
Expand Down