diff --git a/scripts/ai-accounts/ai-accounts b/scripts/ai-accounts/ai-accounts index 5f8ebcf5..ece6a37c 100755 --- a/scripts/ai-accounts/ai-accounts +++ b/scripts/ai-accounts/ai-accounts @@ -55,6 +55,7 @@ import math import os import re import shutil +import signal import subprocess import sys import threading @@ -267,12 +268,34 @@ def with_accounts(providers: str, base: dict[str, str], # ----------------------------------------------------------------- probes -def _http(req: urllib.request.Request, timeout: int = 30) -> tuple[int, dict[str, str], bytes]: +class _RequestDeadline(Exception): + """Skip transport handlers that treat OSError as retryable.""" + + +def _http(req: urllib.request.Request, timeout: float = 30) -> tuple[int, dict[str, str], bytes]: + """Read the response within the account command main thread deadline.""" + def expire(_signum, _frame): + raise _RequestDeadline() + + if timeout <= 0 or any(signal.getitimer(signal.ITIMER_REAL)): + raise TimeoutError("provider HTTP request cannot start without an available time budget") + handler = signal.signal(signal.SIGALRM, expire) try: - with urllib.request.urlopen(req, timeout=timeout) as resp: - return resp.status, {k.lower(): v for k, v in resp.headers.items()}, resp.read() - except urllib.error.HTTPError as exc: - return exc.code, {k.lower(): v for k, v in exc.headers.items()}, exc.read() + try: + signal.setitimer(signal.ITIMER_REAL, timeout) + try: + with urllib.request.urlopen(req, timeout=timeout) as resp: + return resp.status, {k.lower(): v for k, v in resp.headers.items()}, resp.read() + except urllib.error.HTTPError as exc: + with exc: + return exc.code, {k.lower(): v for k, v in exc.headers.items()}, exc.read() + finally: + try: + signal.setitimer(signal.ITIMER_REAL, 0) + finally: + signal.signal(signal.SIGALRM, handler) + except _RequestDeadline: + raise TimeoutError("provider HTTP request timed out") from None def reset_timestamp(value) -> float | None: diff --git a/src/loopzero/mergify.py b/src/loopzero/mergify.py index 347ea599..af4eb5f8 100644 --- a/src/loopzero/mergify.py +++ b/src/loopzero/mergify.py @@ -7,11 +7,13 @@ import json import os import re +import signal import stat import ssl import time import urllib.error import urllib.request +from contextlib import contextmanager from dataclasses import dataclass from pathlib import Path from urllib.parse import quote @@ -20,6 +22,7 @@ from .types import LoopZeroError API = "https://api.mergify.com/v1" +REQUEST_TIMEOUT = 30.0 REQUEST = "loopzero:mergify-request" CONFIRMED = "loopzero:mergify-confirmed" @@ -73,12 +76,36 @@ def redirect_request(self, *_args, **_kwargs): _retry_sleep = time.sleep +class _RequestDeadline(Exception): + """Skip transport handlers that treat OSError as retryable.""" + + +@contextmanager def _open(request: urllib.request.Request): + """Keep the CLI main thread deadline armed through response consumption.""" + def expire(_signum, _frame): + raise _RequestDeadline() + + if any(signal.getitimer(signal.ITIMER_REAL)): + raise TimeoutError("Mergify HTTP request cannot start with an active alarm") + handler = signal.signal(signal.SIGALRM, expire) try: - return urllib.request.build_opener(_NoRedirect).open(request, timeout=30) - except ValueError: - # The HTTP client can include the Authorization value in a header error. - raise MergifyError("Mergify API request has an invalid URL or header") from None + try: + signal.setitimer(signal.ITIMER_REAL, REQUEST_TIMEOUT) + try: + response = urllib.request.build_opener(_NoRedirect).open(request, timeout=REQUEST_TIMEOUT) + except ValueError: + # The HTTP client can include the Authorization value in a header error. + raise MergifyError("Mergify API request has an invalid URL or header") from None + with response: + yield response + finally: + try: + signal.setitimer(signal.ITIMER_REAL, 0) + finally: + signal.signal(signal.SIGALRM, handler) + except _RequestDeadline: + raise TimeoutError("Mergify HTTP request timed out") from None def api_get(repo: str, suffix: str) -> object | None: diff --git a/tests/test_ai_accounts.py b/tests/test_ai_accounts.py index a3133441..559e6f9e 100644 --- a/tests/test_ai_accounts.py +++ b/tests/test_ai_accounts.py @@ -491,3 +491,28 @@ def test_status_prints_account_email_after_plan(helper, capsys, provider, email, result = {'tier': 0, 'plan': 'max', 'email': email, 'windows': [], 'unknown_reason': 'no data'} helper.print_status({'checked_at': helper.now(), 'providers': {provider: {'active': 'a', 'accounts': {'a': result}}}}) assert shown in capsys.readouterr().out + + +def test_provider_deadline_covers_http_error_body(helper, monkeypatch): + signal = helper.signal + handler = signal.getsignal(signal.SIGALRM) + + class ErrorBody: + closed = False + + def read(self): + assert 0 < signal.getitimer(signal.ITIMER_REAL)[0] <= 1 + signal.raise_signal(signal.SIGALRM) + + def close(self): + pass + + def open_error(request, *, timeout): + error = helper.urllib.error.HTTPError(request.full_url, 503, "Busy", {}, ErrorBody()) + raise error + + monkeypatch.setattr(helper.urllib.request, "urlopen", open_error) + with pytest.raises(TimeoutError, match="provider HTTP request timed out"): + helper._http(helper.urllib.request.Request("https://example.invalid"), timeout=1) + assert signal.getsignal(signal.SIGALRM) is handler + assert signal.getitimer(signal.ITIMER_REAL) == (0, 0) diff --git a/tests/test_mergify.py b/tests/test_mergify.py index 7666e7a9..8b079f19 100644 --- a/tests/test_mergify.py +++ b/tests/test_mergify.py @@ -4,10 +4,13 @@ import http.client import io import json +import signal +import socket import ssl import subprocess import sys import traceback +from types import SimpleNamespace import urllib.error import urllib.request @@ -250,3 +253,74 @@ def fail(_request): with pytest.raises(mergify.MergifyError, match="transport failed") as info: mergify.api_get("acme/widgets", "/merge-queue/status") assert str(reason) in str(info.value) and sleeps == expected_sleeps + + +@pytest.mark.parametrize("phase", ["headers", "body"]) +def test_request_deadline_covers_headers_and_body(monkeypatch, phase): + handler = signal.getsignal(signal.SIGALRM) + + def expire(): + assert 0 < signal.getitimer(signal.ITIMER_REAL)[0] <= 30 + signal.raise_signal(signal.SIGALRM) + + def open_(*args, **kwargs): + if phase == "headers": + expire() + return io.BytesIO(b"{}") + + monkeypatch.setattr(mergify.urllib.request, "build_opener", lambda *_: SimpleNamespace(open=open_)) + with ( + pytest.raises(TimeoutError, match="Mergify HTTP request timed out"), + mergify._open(urllib.request.Request("https://example.invalid")), + ): + expire() + assert signal.getsignal(signal.SIGALRM) is handler + assert signal.getitimer(signal.ITIMER_REAL) == (0, 0) + + + +def test_request_deadline_stops_address_fallback(monkeypatch): + addresses = [("192.0.2.1", 443), ("192.0.2.2", 443)] + attempted = [] + + def connect(address): + attempted.append(address) + if len(attempted) == 1: + signal.raise_signal(signal.SIGALRM) + + def open_(*args, **kwargs): + socket.create_connection(("example.invalid", 443)) + return io.BytesIO(b"{}") + + monkeypatch.setattr(socket, "getaddrinfo", lambda *_: [ + (socket.AF_INET, socket.SOCK_STREAM, 0, "", address) for address in addresses + ]) + monkeypatch.setattr(socket, "socket", lambda *_: SimpleNamespace(connect=connect, close=lambda: None)) + monkeypatch.setattr(mergify.urllib.request, "build_opener", lambda *_: SimpleNamespace(open=open_)) + with ( + pytest.raises(TimeoutError, match="Mergify HTTP request timed out"), + mergify._open(urllib.request.Request("https://example.invalid")), + ): + pytest.fail("address fallback swallowed the deadline") + assert attempted == addresses[:1] + + +def test_request_deadline_restores_handler_when_disarming_is_interrupted(monkeypatch): + handler = signal.getsignal(signal.SIGALRM) + setitimer = signal.setitimer + + def interrupt(timer, seconds): + result = setitimer(timer, seconds) + if seconds == 0: + signal.raise_signal(signal.SIGALRM) + return result + + monkeypatch.setattr(signal, "setitimer", interrupt) + monkeypatch.setattr(mergify.urllib.request, "build_opener", + lambda *_: SimpleNamespace(open=lambda *_, **__: io.BytesIO(b"{}"))) + with ( + pytest.raises(TimeoutError, match="Mergify HTTP request timed out"), + mergify._open(urllib.request.Request("https://example.invalid")), + ): + pass + assert signal.getsignal(signal.SIGALRM) is handler