Skip to content
Closed
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
33 changes: 28 additions & 5 deletions scripts/ai-accounts/ai-accounts
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ import math
import os
import re
import shutil
import signal
import subprocess
import sys
import threading
Expand Down Expand Up @@ -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:
Expand Down
35 changes: 31 additions & 4 deletions src/loopzero/mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"

Expand Down Expand Up @@ -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:
Expand Down
25 changes: 25 additions & 0 deletions tests/test_ai_accounts.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
74 changes: 74 additions & 0 deletions tests/test_mergify.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Exercise the success-body read through api_get

The body case raises the signal directly inside _open without reading the response. It would still pass if api_get moved json.load outside the deadline. Have the fake response raise the signal from read() and call api_get with retry sleeps stubbed out. That also checks the transport error seen by the caller.

assert signal.getsignal(signal.SIGALRM) is handler
assert signal.getitimer(signal.ITIMER_REAL) == (0, 0)



def test_request_deadline_stops_address_fallback(monkeypatch):

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Exercise both deadline regressions through the account helper

The address-fallback and interrupted-disarm tests both exercise mergify._open. The standalone account _http implements the same logic independently. Its existing error-body test would still pass if address fallback swallowed its timeout or an interruption during disarming left its handler installed. Reuse the two offline scenarios against _http, checking the attempted addresses and restored handler.

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
Loading