diff --git a/src/prepush_ci/github_api.py b/src/prepush_ci/github_api.py index b97ee843..c7cf5e50 100644 --- a/src/prepush_ci/github_api.py +++ b/src/prepush_ci/github_api.py @@ -18,6 +18,8 @@ from prepush_ci.core.report import ReportError, Repository TIMEOUT_SECONDS = 30 +# the most each shortcut (`GET /user`, `GET /repos//`) takes from the shared deadline +SHORTCUT_SECONDS = 10.0 PER_PAGE = 100 SHORTEST_WAIT = 0.001 # a request is never given no time at all @@ -227,7 +229,8 @@ def _authored(comment: Any) -> Comment: class PullRequestClient: """The requests about the pull request of a pushed branch. All of them together end by one deadline: `timeout` bounds each step of a request, not the request, so a server that sends a - byte a second would never be given up on.""" + byte a second would never be given up on. The shortcuts (`GET /user`, `GET /repos//`) end + sooner, each after `SHORTCUT_SECONDS`, so a stall there leaves the others the rest of the time.""" def __init__( self, api_url: str, repository: Repository, token: str | None, seconds: float @@ -237,14 +240,26 @@ def __init__( self._token = token self._ends = time.monotonic() + seconds - def _left(self) -> float: - return max(self._ends - time.monotonic(), SHORTEST_WAIT) - - def _call(self, method: str, path: str, payload: object = None) -> bytes: - """The answer's body, or an `ApiError` (`timed_out`) when the deadline comes first. The - request runs in a thread that is left behind when it is given up on.""" + def _shortcut_ends(self) -> float: + return min(self._ends, time.monotonic() + SHORTCUT_SECONDS) + + def _left(self, ends: float | None = None) -> float: + return max( + (self._ends if ends is None else ends) - time.monotonic(), SHORTEST_WAIT + ) + + def _call( + self, + method: str, + path: str, + payload: object = None, + ends: float | None = None, + ) -> bytes: + """The answer's body, or an `ApiError` (`timed_out`) when the deadline (`ends`, or the one of + all the requests) comes first. The request runs in a thread that is left behind when it is + given up on.""" answers: queue.SimpleQueue[bytes | ApiError] = queue.SimpleQueue() - left = self._left() + left = self._left(ends) def work() -> None: try: @@ -312,7 +327,7 @@ def permission(self, login: str) -> str: def user(self) -> str: """The login of the user the token acts for.""" - found = self._call("GET", "/user") + found = self._call("GET", "/user", ends=self._shortcut_ends()) try: login = json.loads(text_io.decode(found))["login"] except (ValueError, KeyError, TypeError, RecursionError) as error: @@ -324,7 +339,7 @@ def user(self) -> str: def can_push(self) -> bool: """Whether the repository says the token may push (`permissions.push`).""" path = _repo_path(self._repository) - found = self._call("GET", path) + found = self._call("GET", path, ends=self._shortcut_ends()) try: push = json.loads(text_io.decode(found))["permissions"]["push"] except (ValueError, KeyError, TypeError, RecursionError) as error: diff --git a/tests/integration/land_spec.py b/tests/integration/land_spec.py index d8a29f01..f2c2d5b3 100644 --- a/tests/integration/land_spec.py +++ b/tests/integration/land_spec.py @@ -7,6 +7,7 @@ import subprocess import sys import threading +import time from collections.abc import Callable, Iterator, Sequence from dataclasses import dataclass, field, replace from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer @@ -1116,6 +1117,8 @@ class Api: answers: list[tuple[str, int, str]] = field(default_factory=list) user: tuple[int, str] = (404, '{"message": "Not Found"}') # the answer to `/user` repository: tuple[int, str] = (404, '{"message": "Not Found"}') + hang_on: str | None = None # a request whose path ends with this is never answered + release: threading.Event = field(default_factory=threading.Event) def proxy(self, login: str = "alice", push: bool = True) -> None: """Answer as Claude Code's proxy does: the permission path is refused, the token's own user @@ -1185,6 +1188,9 @@ def _serve(self) -> None: {key.lower(): value for key, value in self.headers.items()}, ) served.requests.append(request) + if served.hang_on is not None and request.path.endswith(served.hang_on): + served.release.wait() # until the test ends: the lander gives up first + return status, body = served.respond(request) data = body.encode("utf-8") self.send_response(status) @@ -1203,6 +1209,7 @@ def log_message(self, format: str, *args: object) -> None: # noqa: A002 thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() yield served + served.release.set() server.shutdown() server.server_close() thread.join() @@ -1687,6 +1694,26 @@ def test_a_comment_of_the_token_s_user_lands_when_the_proxy_refuses_the_permissi assert api.permission_asked_for() == [] +@pytest.mark.parametrize("stalled", ["/user", "/repos/acme/widgets"]) +def test_a_stalled_shortcut_does_not_use_up_the_time_to_ask_for_the_permission( + unrecorded: World, api: Api, git: Git, stalled: str +) -> None: + api.user = (200, json.dumps(by("alice"))) + api.repository = (200, json.dumps({"permissions": {"push": True}})) + api.hang_on = stalled + api.comment(report_comment(unrecorded)) + started = time.monotonic() + + result = land(unrecorded, env=github(api)) + + assert landed(result) == f"landed: {unrecorded.head} on main" + assert main_of(unrecorded, git) == unrecorded.head + assert api.permission_asked_for() == ["alice"] + assert time.monotonic() - started < 30, ( + "the stall of a shortcut is bounded by its own budget" + ) + + def test_another_user_s_comment_does_not_land_through_the_proxy( unrecorded: World, api: Api ) -> None: