|
| 1 | +"""TCP keepalive configuration and transport integration.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import socket |
| 5 | +from contextlib import contextmanager |
| 6 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 7 | +from threading import Thread |
| 8 | +from unittest.mock import patch |
| 9 | + |
| 10 | +import httpcore |
| 11 | +import httpx |
| 12 | +import pytest |
| 13 | + |
| 14 | +from unstructured_client import UnstructuredClient |
| 15 | +from unstructured_client._hooks.custom import http_transport as transport |
| 16 | + |
| 17 | + |
| 18 | +@pytest.fixture(autouse=True) |
| 19 | +def clean_env(monkeypatch): |
| 20 | + for suffix in ("", "_IDLE", "_INTERVAL", "_COUNT"): |
| 21 | + monkeypatch.delenv("UNSTRUCTURED_CLIENT_TCP_KEEPALIVE" + suffix, raising=False) |
| 22 | + monkeypatch.setenv("NO_PROXY", "*") |
| 23 | + |
| 24 | + |
| 25 | +DEFAULTS = transport.TCPKeepAlive(enabled=True) |
| 26 | +BASE_OPTIONS = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] |
| 27 | + |
| 28 | + |
| 29 | +def _close(client): |
| 30 | + if isinstance(client, httpx.AsyncClient): |
| 31 | + asyncio.run(client.aclose()) |
| 32 | + else: |
| 33 | + client.close() |
| 34 | + |
| 35 | + |
| 36 | +@contextmanager |
| 37 | +def local_server(handler): |
| 38 | + server = ThreadingHTTPServer(("127.0.0.1", 0), handler) |
| 39 | + thread = Thread(target=server.serve_forever, daemon=True) |
| 40 | + thread.start() |
| 41 | + try: |
| 42 | + yield server.server_port |
| 43 | + finally: |
| 44 | + server.shutdown() |
| 45 | + server.server_close() |
| 46 | + thread.join() |
| 47 | + |
| 48 | + |
| 49 | +@pytest.mark.parametrize("attrs_to_set,expected_options", [ |
| 50 | + ({"TCP_KEEPIDLE": 100, "TCP_KEEPINTVL": 101, "TCP_KEEPCNT": 102}, |
| 51 | + [(socket.IPPROTO_TCP, 100, DEFAULTS.idle), |
| 52 | + (socket.IPPROTO_TCP, 101, DEFAULTS.interval), |
| 53 | + (socket.IPPROTO_TCP, 102, DEFAULTS.count)]), |
| 54 | + ({"TCP_KEEPALIVE": 100, "TCP_KEEPINTVL": 101, "TCP_KEEPCNT": 102}, |
| 55 | + [(socket.IPPROTO_TCP, 100, DEFAULTS.idle), |
| 56 | + (socket.IPPROTO_TCP, 101, DEFAULTS.interval), |
| 57 | + (socket.IPPROTO_TCP, 102, DEFAULTS.count)]), |
| 58 | + ({"TCP_KEEPALIVE": 100}, [(socket.IPPROTO_TCP, 100, DEFAULTS.idle)]), |
| 59 | + ({}, []), |
| 60 | +], ids=["linux", "macos", "macos_old", "windows"]) |
| 61 | +def test_unit_platform_options(monkeypatch, attrs_to_set, expected_options): |
| 62 | + for name in ("TCP_KEEPIDLE", "TCP_KEEPALIVE", "TCP_KEEPINTVL", "TCP_KEEPCNT"): |
| 63 | + monkeypatch.delattr(socket, name, raising=False) |
| 64 | + for name, value in attrs_to_set.items(): |
| 65 | + monkeypatch.setattr(socket, name, value, raising=False) |
| 66 | + assert transport.resolve_tcp_keepalive().socket_options() == BASE_OPTIONS + expected_options |
| 67 | + |
| 68 | + |
| 69 | +@pytest.mark.parametrize("value", ["0", "false", "False", " FALSE "]) |
| 70 | +def test_unit_disabled(monkeypatch, caplog, value): |
| 71 | + monkeypatch.setenv("UNSTRUCTURED_CLIENT_TCP_KEEPALIVE", value) |
| 72 | + for suffix in ("IDLE", "INTERVAL", "COUNT"): |
| 73 | + monkeypatch.setenv("UNSTRUCTURED_CLIENT_TCP_KEEPALIVE_" + suffix, "invalid") |
| 74 | + settings = transport.resolve_tcp_keepalive() |
| 75 | + assert settings.socket_options() == [] |
| 76 | + assert settings.describe() == "off" |
| 77 | + assert not caplog.records |
| 78 | + |
| 79 | + |
| 80 | +@pytest.mark.parametrize("suffix,value,expected", [ |
| 81 | + (suffix, value, expected) |
| 82 | + for suffix, maximum in ( |
| 83 | + ("IDLE", transport.MAX_IDLE), |
| 84 | + ("INTERVAL", transport.MAX_INTERVAL), |
| 85 | + ("COUNT", transport.MAX_COUNT), |
| 86 | + ) |
| 87 | + for value, expected in ( |
| 88 | + *[(invalid, getattr(DEFAULTS, suffix.lower())) |
| 89 | + for invalid in ("0", "-1", "bad", "1.5", "", str(maximum + 1))], |
| 90 | + ("1", 1), |
| 91 | + (str(maximum), maximum), |
| 92 | + ) |
| 93 | +]) |
| 94 | +def test_unit_value_bounds(monkeypatch, caplog, suffix, value, expected): |
| 95 | + monkeypatch.setenv("UNSTRUCTURED_CLIENT_TCP_KEEPALIVE_" + suffix, value) |
| 96 | + assert getattr(transport.resolve_tcp_keepalive(), suffix.lower()) == expected |
| 97 | + assert ("using default" in caplog.text) == (value != str(expected)) |
| 98 | + |
| 99 | + |
| 100 | +@pytest.mark.parametrize("asynchronous", [False, True]) |
| 101 | +def test_unit_missing_proxy_helper_client_options(monkeypatch, asynchronous): |
| 102 | + monkeypatch.setattr(transport, "get_environment_proxies", None) |
| 103 | + if asynchronous: |
| 104 | + options = {"verify": False, "cert": "client.pem", "limits": httpx.Limits(max_connections=3)} |
| 105 | + with patch.object(httpx, "AsyncClient") as constructor: |
| 106 | + transport.create_async_http_client(timeout=42, **options) |
| 107 | + constructor.assert_called_once_with(timeout=42, **options) |
| 108 | + else: |
| 109 | + with patch.object(httpx, "Client") as constructor: |
| 110 | + transport.create_http_client() |
| 111 | + constructor.assert_called_once_with() |
| 112 | + |
| 113 | + |
| 114 | +def test_unit_custom_values(monkeypatch): |
| 115 | + for suffix, value in (("IDLE", "5"), ("INTERVAL", "6"), ("COUNT", "7")): |
| 116 | + monkeypatch.setenv("UNSTRUCTURED_CLIENT_TCP_KEEPALIVE_" + suffix, value) |
| 117 | + settings = transport.resolve_tcp_keepalive() |
| 118 | + assert settings == transport.TCPKeepAlive(True, 5, 6, 7) |
| 119 | + assert settings.describe() == "idle=5s interval=6s count=7" |
| 120 | + |
| 121 | + |
| 122 | +def test_unit_sdk_owned_clients(): |
| 123 | + sdk = UnstructuredClient() |
| 124 | + options = transport.resolve_tcp_keepalive().socket_options() |
| 125 | + assert sdk.sdk_configuration.client._transport.base_transport._pool._socket_options == options |
| 126 | + assert sdk.sdk_configuration.async_client._transport._pool._socket_options == options |
| 127 | + _close(sdk.sdk_configuration.client) |
| 128 | + _close(sdk.sdk_configuration.async_client) |
| 129 | + |
| 130 | + |
| 131 | +def test_unit_supplied_clients_untouched(): |
| 132 | + sync = httpx.Client() |
| 133 | + asynchronous = httpx.AsyncClient() |
| 134 | + sync_transport = sync._transport |
| 135 | + async_transport = asynchronous._transport |
| 136 | + UnstructuredClient(client=sync, async_client=asynchronous) |
| 137 | + assert sync._transport.base_transport is sync_transport |
| 138 | + assert asynchronous._transport is async_transport |
| 139 | + _close(sync) |
| 140 | + _close(asynchronous) |
| 141 | + |
| 142 | + |
| 143 | +@pytest.mark.parametrize("missing_proxy_helper", [False, True]) |
| 144 | +@pytest.mark.parametrize("asynchronous", [False, True]) |
| 145 | +def test_unit_environment_proxy_routes(monkeypatch, asynchronous, missing_proxy_helper): |
| 146 | + if missing_proxy_helper: |
| 147 | + monkeypatch.setattr(transport, "get_environment_proxies", None) |
| 148 | + monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:8123") |
| 149 | + monkeypatch.setenv("NO_PROXY", "excluded.example") |
| 150 | + client = transport.create_async_http_client() if asynchronous else transport.create_http_client() |
| 151 | + proxied = client._transport_for_url(httpx.URL("https://api.example")) |
| 152 | + assert isinstance(proxied._pool, httpcore.AsyncHTTPProxy if asynchronous else httpcore.HTTPProxy) |
| 153 | + assert proxied._pool._proxy_url.host == b"127.0.0.1" |
| 154 | + assert proxied._pool._socket_options is None |
| 155 | + expected = None if missing_proxy_helper else transport.resolve_tcp_keepalive().socket_options() |
| 156 | + assert client._transport._pool._socket_options == expected |
| 157 | + assert client._transport_for_url(httpx.URL("https://excluded.example")) is client._transport |
| 158 | + _close(client) |
| 159 | + |
| 160 | + |
| 161 | +@pytest.mark.parametrize("asynchronous", [False, True]) |
| 162 | +def test_unit_real_socket_keepalive(asynchronous): |
| 163 | + class Handler(BaseHTTPRequestHandler): |
| 164 | + protocol_version = "HTTP/1.1" |
| 165 | + |
| 166 | + def do_GET(self): |
| 167 | + self.send_response(200) |
| 168 | + self.send_header("Content-Length", "2") |
| 169 | + self.end_headers() |
| 170 | + self.wfile.write(b"ok") |
| 171 | + |
| 172 | + def check(response): |
| 173 | + stream = response.extensions["network_stream"] |
| 174 | + sock = stream.get_extra_info("socket") |
| 175 | + for level, option, value in transport.resolve_tcp_keepalive().socket_options(): |
| 176 | + if (level, option) == (socket.SOL_SOCKET, socket.SO_KEEPALIVE): |
| 177 | + assert sock.getsockopt(level, option) |
| 178 | + else: |
| 179 | + assert sock.getsockopt(level, option) == value |
| 180 | + |
| 181 | + async def request(): |
| 182 | + async with transport.create_async_http_client() as client: |
| 183 | + async with client.stream("GET", url) as response: |
| 184 | + check(response) |
| 185 | + await response.aread() |
| 186 | + |
| 187 | + with local_server(Handler) as port: |
| 188 | + url = f"http://127.0.0.1:{port}" |
| 189 | + if asynchronous: |
| 190 | + asyncio.run(request()) |
| 191 | + else: |
| 192 | + with transport.create_http_client() as client: |
| 193 | + with client.stream("GET", url) as response: |
| 194 | + check(response) |
| 195 | + response.read() |
| 196 | + |
| 197 | + |
| 198 | +@pytest.mark.parametrize("asynchronous", [False, True]) |
| 199 | +def test_unit_https_proxy_receives_connect(monkeypatch, asynchronous): |
| 200 | + destinations = [] |
| 201 | + |
| 202 | + class ProxyHandler(BaseHTTPRequestHandler): |
| 203 | + def do_CONNECT(self): |
| 204 | + destinations.append(self.path) |
| 205 | + self.send_error(502) |
| 206 | + |
| 207 | + async def request(): |
| 208 | + async with transport.create_async_http_client() as client: |
| 209 | + await client.get("https://proxy-target.invalid/") |
| 210 | + |
| 211 | + with local_server(ProxyHandler) as port: |
| 212 | + monkeypatch.setenv("HTTPS_PROXY", f"http://127.0.0.1:{port}") |
| 213 | + monkeypatch.setenv("NO_PROXY", "") |
| 214 | + with pytest.raises(httpx.ProxyError, match="502"): |
| 215 | + if asynchronous: |
| 216 | + asyncio.run(request()) |
| 217 | + else: |
| 218 | + with transport.create_http_client() as client: |
| 219 | + client.get("https://proxy-target.invalid/") |
| 220 | + assert destinations == ["proxy-target.invalid:443"] |
0 commit comments