diff --git a/proofline/_sync_http.py b/proofline/_sync_http.py index 0ef0b5b0..424e5a7e 100644 --- a/proofline/_sync_http.py +++ b/proofline/_sync_http.py @@ -3,6 +3,10 @@ Operating-system name resolution cannot be interrupted, so it runs on a daemon thread and the request stops waiting for it at the deadline. An abandoned lookup finishes on its own thread and its result is discarded. + +A host name with several addresses races its connection attempts (RFC 8305): each starts +250 ms after the previous one, or at once when it fails, and the first connection wins. An +address that silently drops packets then costs one attempt delay instead of the deadline. """ from __future__ import annotations @@ -11,9 +15,10 @@ import socket import ssl import threading -from collections.abc import Iterable, Iterator +from collections.abc import Callable, Iterable, Iterator from contextlib import contextmanager from contextvars import ContextVar +from functools import partial from time import monotonic from typing import Any @@ -100,6 +105,98 @@ def get_extra_info(self, info: str) -> Any: return self._inner.get_extra_info(info) +# RFC 8305 recommends 250 ms between connection attempts, as anyio uses for the async client. +ATTEMPT_DELAY = 0.25 + + +def interleaved(addresses: list[str]) -> list[str]: + """Alternate address families, starting with the resolver's first preference (RFC 8305 ยง4).""" + families: dict[bool, list[str]] = {True: [], False: []} + for address in addresses: + families[":" in address].append(address) + first = ":" in addresses[0] + preferred, other = families[first], families[not first] + ordered: list[str] = [] + for index in range(max(len(preferred), len(other))): + ordered.extend(family[index] for family in (preferred, other) if index < len(family)) + return ordered + + +class Race: + """Concurrent connection attempts. The first stream wins; later streams are closed.""" + + def __init__(self) -> None: + self._changed = threading.Condition() + self._running = 0 + self._settled = False + self.winner: httpcore2.NetworkStream | None = None + self.failure: Exception | None = None + self.failures = 0 + + def start(self, connect: Callable[[], httpcore2.NetworkStream], address: str = "") -> None: + with self._changed: + self._running += 1 + try: + threading.Thread( + target=self._attempt, + args=(connect,), + name=f"proofline-connect {address}".rstrip(), + daemon=True, + ).start() + except BaseException: + with self._changed: + self._running -= 1 + self._changed.notify_all() + raise + + def _attempt(self, connect: Callable[[], httpcore2.NetworkStream]) -> None: + try: + stream = connect() + except Exception as error: + with self._changed: + self._running -= 1 + self.failure = error + self.failures += 1 + self._changed.notify_all() + return + with self._changed: + self._running -= 1 + if not self._settled and self.winner is None: + self.winner = stream + self._changed.notify_all() + return + # The request already has a connection or stopped waiting for one. + stream.close() + + def wait(self, timeout: float | None, *, failures: int | None = None) -> int: + """Wait for a winner or for every attempt to fail; or for more than `failures` failures. + + Returns the failure count observed under the lock, so the caller acts on exactly the + failures this wait saw rather than on ones that arrive after it returns. + """ + with self._changed: + self._changed.wait_for( + lambda: ( + self.winner is not None + or self._running == 0 + or (failures is not None and self.failures > failures) + ), + timeout, + ) + return self.failures + + def settle(self) -> httpcore2.NetworkStream | None: + """Stop accepting streams; a stream that connects later is closed by its attempt.""" + with self._changed: + self._settled = True + return self.winner + + @property + def running(self) -> int: + with self._changed: + return self._running + + class NetworkBackend(httpcore2.SyncBackend): def connect_tcp( self, @@ -109,17 +206,73 @@ def connect_tcp( local_address: str | None = None, socket_options: Iterable[Any] | None = None, ) -> httpcore2.NetworkStream: - failure: httpcore2.ConnectError | httpcore2.ConnectTimeout | None = None - for address in resolve(host, port, bounded_timeout(timeout)): - try: - stream = super().connect_tcp( - address, port, bounded_timeout(timeout), local_address, socket_options - ) - except (httpcore2.ConnectError, httpcore2.ConnectTimeout) as error: - failure = error - else: - return NetworkStream(stream) - raise failure or httpcore2.ConnectError("The host name did not resolve.") + addresses = resolve(host, port, bounded_timeout(timeout)) + if len(addresses) == 1: + stream = super().connect_tcp( + addresses[0], port, bounded_timeout(timeout), local_address, socket_options + ) + return NetworkStream(stream) + # One address that silently drops packets must not spend the whole request deadline + # while the next address would answer, so attempts overlap ATTEMPT_DELAY apart. + budget = bounded_timeout(timeout) + deadline = None if budget is None else monotonic() + budget + options = list(socket_options or ()) + connect = super().connect_tcp + + def attempt(address: str) -> httpcore2.NetworkStream: + # Measure the budget when the thread runs, not when it was scheduled, so an + # attempt whose thread starts late still cannot connect past the deadline. + left = None if deadline is None else deadline - monotonic() + if left is not None and left <= 0: + raise httpcore2.ConnectTimeout("The request deadline expired.") + return connect(address, port, left, local_address, options) + + race = Race() + # Failures that have already started an attempt. Each failure starts at most one, + # so one that arrives while an attempt is being started still starts the next. + answered = 0 + # Set only here, so a worker that fails after the deadline cannot change the outcome. + expired = False + try: + for index, address in enumerate(interleaved(addresses)): + if index: + # Start the next attempt after the delay, or as soon as any attempt fails. + seen = race.wait( + ATTEMPT_DELAY + if deadline is None + else min(ATTEMPT_DELAY, deadline - monotonic()), + failures=answered, + ) + if race.winner is not None: + break + if deadline is not None and monotonic() >= deadline: + expired = True + break + if seen > answered: + answered += 1 + race.start(partial(attempt, address), address) + while not expired and race.winner is None and race.running: + if deadline is None: + race.wait(None) + continue + if (left := deadline - monotonic()) > 0: + race.wait(left) + # Judge the deadline before rereading worker state that may change after it. + expired = monotonic() >= deadline + except BaseException: + # The request is failing anyway; release a connection that won in the meantime. + if (late := race.settle()) is not None: + late.close() + raise + winner = race.settle() + # A stream that won is used even if the deadline passed while it was handed over: each + # attempt connects within the budget left when it runs, so it connected before the + # deadline, and later I/O stays bounded by it. Only failures defer to the timeout. + if winner is not None: + return NetworkStream(winner) + if expired: + raise httpcore2.ConnectTimeout("No resolved address connected in time.") + raise race.failure or httpcore2.ConnectError("The host name did not resolve.") @contextmanager diff --git a/tests/test_sync_connect.py b/tests/test_sync_connect.py new file mode 100644 index 00000000..f3234593 --- /dev/null +++ b/tests/test_sync_connect.py @@ -0,0 +1,427 @@ +"""The sync transport races resolved addresses so one silent address cannot spend the deadline.""" + +from __future__ import annotations + +import socket +import threading +import time +from collections.abc import Callable, Iterator +from dataclasses import dataclass, field +from typing import Any + +import httpcore2 +import httpx2 +import pytest + +from proofline import ProoflineClient, _sync_http + +from .fixtures import FINDING, ORG, REVIEW, TOKEN, finding +from .http_server import Reply, Server + +# Documentation addresses (RFC 5737, RFC 3849) stand in for hosts that drop every SYN. +SILENT = "192.0.2.1" +SILENT_V6 = "2001:db8::1" +# These answer every SYN with a reset, as a host with nothing listening does. +REFUSED = "198.51.100.1" +REFUSED_V6 = "2001:db8::2" + + +def until(condition: Callable[[], bool], what: str) -> None: + """Poll a condition a worker thread sets; fail instead of hanging if it never holds.""" + deadline = time.monotonic() + 5 + while not condition(): + if time.monotonic() > deadline: + pytest.fail(f"Timed out waiting for {what}.") + time.sleep(0.001) + + +@dataclass +class Network: + hosts: dict[str, list[str]] = field(default_factory=dict) + # Attempts in the order the scheduler launched them, recorded on the scheduler thread. + launches: list[tuple[str, float]] = field(default_factory=list) + # Each address's connect call, recorded by its worker: when it ran and its timeout. + runs: dict[str, tuple[float, float | None]] = field(default_factory=dict) + silence: threading.Event = field(default_factory=threading.Event) + + @property + def tried(self) -> list[str]: + return [address for address, _ in self.launches] + + @property + def gaps(self) -> list[float]: + """Seconds between consecutive launches: the scheduler's launch decisions.""" + starts = [at for _, at in self.launches] + return [later - earlier for earlier, later in zip(starts, starts[1:], strict=False)] + + @property + def timeouts(self) -> list[float | None]: + return [self.runs[address][1] for address in self.tried] + + +@pytest.fixture +def network(monkeypatch: pytest.MonkeyPatch) -> Iterator[Network]: + """Resolve test hosts to chosen addresses. A silent address never answers its SYN. + + Like an unanswered SYN, a silent attempt waits out its whole connect timeout and then + raises ConnectTimeout; a refused attempt fails at once. Loopback is real TCP. + """ + state = Network() + resolve = socket.getaddrinfo + connect = httpcore2.SyncBackend.connect_tcp + + def getaddrinfo(host: Any, port: Any, *args: Any, **kwargs: Any) -> Any: + if host not in state.hosts: + return resolve(host, port, *args, **kwargs) + return [ + (socket.AF_INET6, socket.SOCK_STREAM, 6, "", (address, port, 0, 0)) + if ":" in address + else (socket.AF_INET, socket.SOCK_STREAM, 6, "", (address, port)) + for address in state.hosts[host] + ] + + launch = _sync_http.Race.start + + def start( + race: _sync_http.Race, connect: Callable[[], httpcore2.NetworkStream], address: str = "" + ) -> None: + state.launches.append((address, time.monotonic())) + launch(race, connect, address) + + def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: + state.runs[host] = (time.monotonic(), timeout) + if host in (SILENT, SILENT_V6): + state.silence.wait(timeout) + raise httpcore2.ConnectTimeout("timed out") + if host in (REFUSED, REFUSED_V6): + raise httpcore2.ConnectError("Connection refused") + return connect(self, host, port, timeout, *args) + + monkeypatch.setattr(socket, "getaddrinfo", getaddrinfo) + monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + monkeypatch.setattr(_sync_http.Race, "start", start) + try: + yield state + finally: + # End silent attempts that are still waiting so their threads finish with the test. + state.silence.set() + + +def test_a_silent_first_address_falls_back_to_the_next_one(network: Network) -> None: + network.hosts["dual.proofline.invalid"] = [SILENT_V6, SILENT, "127.0.0.1"] + with Server(lambda request, index: Reply(body=finding())) as server: + port = server.url.rsplit(":", 1)[1] + with httpx2.Client(transport=_sync_http.Transport(), timeout=5) as client: + started = time.monotonic() + response = client.get(f"http://dual.proofline.invalid:{port}/finding") + elapsed = time.monotonic() - started + assert response.json()["id"] == str(FINDING) + assert server.requests[0].headers["Host"] == f"dual.proofline.invalid:{port}" + assert network.tried == [SILENT_V6, SILENT, "127.0.0.1"] + # Each silent address costs one attempt delay, not the 5 second connect timeout. + assert elapsed < 2 + assert all(gap >= _sync_http.ATTEMPT_DELAY * 0.8 for gap in network.gaps) + + +def test_the_client_reads_through_a_silent_address( + network: Network, monkeypatch: pytest.MonkeyPatch +) -> None: + with Server(lambda request, index: Reply(body=finding())) as server: + # The origin must be a loopback literal, which resolves to itself; give it a silent + # address first, as a dual-stack name with broken IPv6 resolves. + monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, "127.0.0.1"]) + with ProoflineClient(TOKEN, base_url=server.url, timeout=5) as client: + started = time.monotonic() + result = client.get_finding(ORG, FINDING) + elapsed = time.monotonic() - started + assert result.id == FINDING + assert len(server.requests) == 1 + assert network.tried == [SILENT, "127.0.0.1"] + # Before the race, this read raised urn:proofline:sdk:timeout after 5 seconds. + assert elapsed < 2 + + +def test_a_refused_address_starts_the_next_attempt_at_once(network: Network) -> None: + network.hosts["refused.proofline.invalid"] = [REFUSED, "127.0.0.1"] + with Server(lambda request, index: Reply(body=finding())) as server: + port = server.url.rsplit(":", 1)[1] + with httpx2.Client(transport=_sync_http.Transport(), timeout=5) as client: + response = client.get(f"http://refused.proofline.invalid:{port}/finding") + assert response.json()["id"] == str(FINDING) + assert network.tried == [REFUSED, "127.0.0.1"] + # The refusal started the next attempt without waiting out the stagger. + assert network.gaps[0] < _sync_http.ATTEMPT_DELAY / 2 + + +def test_every_silent_address_ends_at_the_request_deadline(network: Network) -> None: + network.hosts["dark.proofline.invalid"] = [SILENT_V6, SILENT] + with httpx2.Client(transport=_sync_http.Transport(), timeout=0.6) as client: + started = time.monotonic() + with pytest.raises(httpx2.TimeoutException): + client.get("http://dark.proofline.invalid:443/finding") + elapsed = time.monotonic() - started + assert 0.5 < elapsed < 1.5 + assert network.tried == [SILENT_V6, SILENT] + # The second attempt starts one delay later and gets only what is left of the budget. + first, second = network.timeouts + assert first is not None and second is not None + assert first <= 0.6 + assert second <= 0.6 - _sync_http.ATTEMPT_DELAY * 0.8 + + +def test_the_wait_deadline_still_bounds_the_race( + network: Network, monkeypatch: pytest.MonkeyPatch +) -> None: + monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, SILENT_V6]) + with ProoflineClient(TOKEN, base_url="http://127.0.0.1:9", timeout=30) as client: + started = time.monotonic() + result = client.wait_for_review(ORG, REVIEW, timeout=0.4) + elapsed = time.monotonic() - started + assert result.status == "TIMED_OUT" + assert network.tried == [SILENT, SILENT_V6] + assert elapsed < 1.5 + # Each attempt is bounded by the 0.4 second wait, not the 30 second HTTP timeout. + first, second = network.timeouts + assert first is not None and second is not None + assert first <= 0.4 + assert second <= 0.4 - _sync_http.ATTEMPT_DELAY * 0.8 + + +def test_an_attempt_whose_thread_starts_late_still_ends_at_the_deadline( + network: Network, monkeypatch: pytest.MonkeyPatch +) -> None: + # Every worker thread starts 0.3 s after it is launched. The second is launched at about + # 0.25 s and runs at about 0.55 s, so only about 0.05 s of the 0.6 s budget is left then. + network.hosts["late.proofline.invalid"] = [SILENT, SILENT_V6] + launch = _sync_http.Race.start + + def start_late( + race: _sync_http.Race, connect: Callable[[], httpcore2.NetworkStream], address: str = "" + ) -> None: + def late() -> httpcore2.NetworkStream: + time.sleep(0.3) + return connect() + + launch(race, late, address) + + monkeypatch.setattr(_sync_http.Race, "start", start_late) + with httpx2.Client(transport=_sync_http.Transport(), timeout=0.6) as client: + started = time.monotonic() + with pytest.raises(httpx2.TimeoutException): + client.get("http://late.proofline.invalid:443/finding") + assert network.runs + for ran, timeout in network.runs.values(): + # No connect call may run past the request deadline, however late its thread started. + assert timeout is not None + assert ran + timeout <= started + 0.6 + 0.05 + + +def test_every_refused_address_raises_a_connect_error(network: Network) -> None: + network.hosts["closed.proofline.invalid"] = [REFUSED, REFUSED_V6] + with httpx2.Client(transport=_sync_http.Transport(), timeout=5) as client: + with pytest.raises(httpx2.TransportError) as raised: + client.get("http://closed.proofline.invalid:443/finding") + assert not isinstance(raised.value, httpx2.TimeoutException) + assert network.tried == [REFUSED, REFUSED_V6] + assert network.gaps[0] < _sync_http.ATTEMPT_DELAY / 2 + + +class Stream(httpcore2.MockStream): + def __init__(self) -> None: + super().__init__([]) + self.closed = threading.Event() + + def close(self) -> None: + self.closed.set() + + +def test_a_stream_that_connects_after_the_race_settles_is_closed() -> None: + release = threading.Event() + late = Stream() + + def connect_late() -> httpcore2.NetworkStream: + release.wait(5) + return late + + race = _sync_http.Race() + race.start(connect_late) + assert race.settle() is None + release.set() + assert late.closed.wait(5) + assert race.winner is None + + +@pytest.mark.parametrize("settled", [False, True], ids=["before-settle", "after-settle"]) +def test_a_losing_stream_is_closed_and_the_winner_kept(settled: bool) -> None: + # The loser connects after the winner is published, either while the caller is still + # handing the winner over or after it has settled the race. + release = threading.Event() + winner, loser = Stream(), Stream() + + def connect_loser() -> httpcore2.NetworkStream: + release.wait(5) + return loser + + race = _sync_http.Race() + race.start(connect_loser) + race.start(lambda: winner) + race.wait(5) + assert race.winner is winner + if settled: + assert race.settle() is winner + release.set() + assert loser.closed.wait(5) + assert race.settle() is winner + assert not winner.closed.is_set() + + +def test_a_failure_while_an_attempt_starts_still_starts_the_next( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Four silent addresses. The first fails just after the wait before the third attempt + # times out, so that failure has started nothing yet: the fourth attempt starts at once. + first_fails = threading.Event() + silence = threading.Event() + launches: dict[str, float] = {} + original_wait = _sync_http.Race.wait + original_start = _sync_http.Race.start + calls = 0 + + def start( + race: _sync_http.Race, connect: Callable[[], httpcore2.NetworkStream], address: str = "" + ) -> None: + launches[address] = time.monotonic() + original_start(race, connect, address) + + def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: + if host == "192.0.2.1": + first_fails.wait(5) + raise httpcore2.ConnectError("Connection reset") + silence.wait(timeout) + raise httpcore2.ConnectTimeout("timed out") + + def wait(race: _sync_http.Race, timeout: float | None, **kwargs: Any) -> int: + nonlocal calls + seen = original_wait(race, timeout, **kwargs) + calls += 1 + if calls == 2: + failures = race.failures + first_fails.set() + until(lambda: race.failures > failures, "the first attempt to fail") + return seen + + addresses = ["192.0.2.1", "192.0.2.2", "192.0.2.3", "192.0.2.4"] + monkeypatch.setattr(_sync_http, "resolve", lambda *_: addresses) + monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + monkeypatch.setattr(_sync_http.Race, "wait", wait) + monkeypatch.setattr(_sync_http.Race, "start", start) + try: + with pytest.raises(httpcore2.ConnectTimeout): + _sync_http.NetworkBackend().connect_tcp("dark.proofline.invalid", 443, 1.2) + finally: + silence.set() + assert list(launches) == addresses + assert launches["192.0.2.4"] - launches["192.0.2.3"] < _sync_http.ATTEMPT_DELAY / 2 + + +def test_a_failure_after_the_deadline_still_reports_the_timeout( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # Both attempts hang past the deadline. When the final wait returns at the deadline, both + # fail with a reset before the scheduler looks again. The deadline ended the request, so + # the caller sees a timeout, not the late reset. + reset = threading.Event() + + def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: + reset.wait(10) + raise httpcore2.ConnectError("Connection reset") + + original_wait = _sync_http.Race.wait + deadline = 0.0 + + def wait(race: _sync_http.Race, timeout: float | None, **kwargs: Any) -> int: + seen = original_wait(race, timeout, **kwargs) + if time.monotonic() >= deadline and not reset.is_set(): + reset.set() + until(lambda: not race.running, "the late attempts to fail") + return seen + + monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, SILENT_V6]) + monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + monkeypatch.setattr(_sync_http.Race, "wait", wait) + deadline = time.monotonic() + 0.4 + with pytest.raises(httpcore2.ConnectTimeout): + _sync_http.NetworkBackend().connect_tcp("dark.proofline.invalid", 443, 0.4) + assert reset.is_set() + + +def test_a_winner_is_closed_when_starting_the_next_attempt_fails( + monkeypatch: pytest.MonkeyPatch, +) -> None: + # The first attempt connects just after the scheduler checked for a winner, and then + # starting the second attempt's thread fails. The error propagates; the stream is closed. + release = threading.Event() + winner = Stream() + + def connect_tcp(self: Any, host: str, port: int, timeout: float | None, *args: Any) -> Any: + release.wait(5) + return winner + + original_start = _sync_http.Race.start + starts = 0 + + def start( + race: _sync_http.Race, connect: Callable[[], httpcore2.NetworkStream], address: str = "" + ) -> None: + nonlocal starts + starts += 1 + if starts == 2: + release.set() + until(lambda: race.winner is not None, "the first attempt to connect") + raise RuntimeError("can't start new thread") + original_start(race, connect, address) + + monkeypatch.setattr(_sync_http, "resolve", lambda *_: [SILENT, SILENT_V6]) + monkeypatch.setattr(httpcore2.SyncBackend, "connect_tcp", connect_tcp) + monkeypatch.setattr(_sync_http.Race, "start", start) + with pytest.raises(RuntimeError): + _sync_http.NetworkBackend().connect_tcp("dual.proofline.invalid", 443, 5) + assert winner.closed.wait(5) + + +def test_an_attempt_whose_thread_cannot_start_is_not_counted( + monkeypatch: pytest.MonkeyPatch, +) -> None: + def refuse(thread: threading.Thread) -> None: + raise RuntimeError("can't start new thread") + + race = _sync_http.Race() + monkeypatch.setattr(threading.Thread, "start", refuse) + with pytest.raises(RuntimeError): + race.start(Stream) + assert race.running == 0 + + +def test_the_backend_alternates_address_families(network: Network) -> None: + # The resolver groups addresses by family; attempts must still alternate between them. + network.hosts["grouped.proofline.invalid"] = [SILENT_V6, REFUSED_V6, SILENT, REFUSED] + with httpx2.Client(transport=_sync_http.Transport(), timeout=0.8) as client: + with pytest.raises(httpx2.TimeoutException): + client.get("http://grouped.proofline.invalid:443/finding") + assert network.tried == [SILENT_V6, SILENT, REFUSED_V6, REFUSED] + + +@pytest.mark.parametrize( + ("resolved", "ordered"), + [ + ( + ["2001:db8::1", "2001:db8::2", "192.0.2.1", "192.0.2.2"], + ["2001:db8::1", "192.0.2.1", "2001:db8::2", "192.0.2.2"], + ), + (["192.0.2.1", "192.0.2.2", "2001:db8::1"], ["192.0.2.1", "2001:db8::1", "192.0.2.2"]), + (["192.0.2.1", "192.0.2.2"], ["192.0.2.1", "192.0.2.2"]), + (["fe80::1%41", "fe80::1%42"], ["fe80::1%41", "fe80::1%42"]), + ], +) +def test_attempts_alternate_address_families(resolved: list[str], ordered: list[str]) -> None: + assert _sync_http.interleaved(resolved) == ordered