|
| 1 | +"""TCP keepalive configuration and transport integration.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import socket |
| 5 | +import sys |
| 6 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 7 | +from threading import Thread |
| 8 | + |
| 9 | +import httpcore |
| 10 | +import httpx |
| 11 | +import pytest |
| 12 | + |
| 13 | +from unstructured_client import UnstructuredClient |
| 14 | +from unstructured_client._hooks.custom import http_transport as transport |
| 15 | + |
| 16 | + |
| 17 | +@pytest.fixture(autouse=True) |
| 18 | +def clean_env(monkeypatch): |
| 19 | + for suffix in ("", "_IDLE", "_INTERVAL", "_COUNT"): |
| 20 | + monkeypatch.delenv("UNSTRUCTURED_CLIENT_TCP_KEEPALIVE" + suffix, raising=False) |
| 21 | + monkeypatch.setenv("NO_PROXY", "*") |
| 22 | + |
| 23 | + |
| 24 | +@pytest.mark.parametrize("platform", ["linux", "macos", "macos_old", "windows"]) |
| 25 | +def test_unit_platform_options(monkeypatch, platform): |
| 26 | + for name in ("TCP_KEEPIDLE", "TCP_KEEPALIVE", "TCP_KEEPINTVL", "TCP_KEEPCNT"): |
| 27 | + monkeypatch.delattr(socket, name, raising=False) |
| 28 | + expected = [(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)] |
| 29 | + if platform != "windows": |
| 30 | + monkeypatch.setattr(socket, "TCP_KEEPIDLE" if platform == "linux" else "TCP_KEEPALIVE", 100, raising=False) |
| 31 | + expected.append((socket.IPPROTO_TCP, 100, 60)) |
| 32 | + if platform != "macos_old": |
| 33 | + monkeypatch.setattr(socket, "TCP_KEEPINTVL", 101, raising=False) |
| 34 | + monkeypatch.setattr(socket, "TCP_KEEPCNT", 102, raising=False) |
| 35 | + expected += [(socket.IPPROTO_TCP, 101, 30), (socket.IPPROTO_TCP, 102, 5)] |
| 36 | + assert transport.resolve_tcp_keepalive().socket_options() == expected |
| 37 | + |
| 38 | + |
| 39 | +@pytest.mark.parametrize("value", ["0", "false", "False", " FALSE "]) |
| 40 | +def test_unit_disabled(monkeypatch, value): |
| 41 | + monkeypatch.setenv("UNSTRUCTURED_CLIENT_TCP_KEEPALIVE", value) |
| 42 | + assert transport.resolve_tcp_keepalive().socket_options() == [] |
| 43 | + |
| 44 | + |
| 45 | +@pytest.mark.parametrize("suffix,default", [("IDLE", 60), ("INTERVAL", 30), ("COUNT", 5)]) |
| 46 | +@pytest.mark.parametrize("value", ["0", "-1", "bad", "1.5", ""]) |
| 47 | +def test_unit_invalid_value(monkeypatch, caplog, suffix, default, value): |
| 48 | + monkeypatch.setenv("UNSTRUCTURED_CLIENT_TCP_KEEPALIVE_" + suffix, value) |
| 49 | + assert getattr(transport.resolve_tcp_keepalive(), suffix.lower()) == default |
| 50 | + assert "using default" in caplog.text |
| 51 | + |
| 52 | + |
| 53 | +def test_unit_custom_values(monkeypatch): |
| 54 | + for suffix, value in (("IDLE", "5"), ("INTERVAL", "6"), ("COUNT", "7")): |
| 55 | + monkeypatch.setenv("UNSTRUCTURED_CLIENT_TCP_KEEPALIVE_" + suffix, value) |
| 56 | + assert transport.resolve_tcp_keepalive() == transport.TCPKeepAlive(True, 5, 6, 7) |
| 57 | + |
| 58 | + |
| 59 | +def test_unit_sdk_owned_clients(): |
| 60 | + sdk = UnstructuredClient() |
| 61 | + options = transport.resolve_tcp_keepalive().socket_options() |
| 62 | + assert sdk.sdk_configuration.client._transport.base_transport._pool._socket_options == options |
| 63 | + assert sdk.sdk_configuration.async_client._transport._pool._socket_options == options |
| 64 | + sdk.sdk_configuration.client.close() |
| 65 | + asyncio.run(sdk.sdk_configuration.async_client.aclose()) |
| 66 | + |
| 67 | + |
| 68 | +def test_unit_supplied_clients_untouched(): |
| 69 | + sync = httpx.Client() |
| 70 | + asynchronous = httpx.AsyncClient() |
| 71 | + sync_transport = sync._transport |
| 72 | + async_transport = asynchronous._transport |
| 73 | + sdk = UnstructuredClient(client=sync, async_client=asynchronous) |
| 74 | + assert sdk.sdk_configuration.client is sync |
| 75 | + assert sdk.sdk_configuration.async_client is asynchronous |
| 76 | + assert sync._transport.base_transport is sync_transport |
| 77 | + assert asynchronous._transport is async_transport |
| 78 | + assert sync_transport._pool._socket_options is None |
| 79 | + assert asynchronous._transport._pool._socket_options is None |
| 80 | + sync.close() |
| 81 | + asyncio.run(asynchronous.aclose()) |
| 82 | + |
| 83 | + |
| 84 | +@pytest.mark.parametrize("asynchronous", [False, True]) |
| 85 | +def test_unit_environment_proxy_routes(monkeypatch, asynchronous): |
| 86 | + monkeypatch.setenv("HTTPS_PROXY", "http://127.0.0.1:8123") |
| 87 | + monkeypatch.setenv("NO_PROXY", "excluded.example") |
| 88 | + client = transport.create_async_http_client() if asynchronous else transport.create_http_client() |
| 89 | + proxied = client._transport_for_url(httpx.URL("https://api.example")) |
| 90 | + assert isinstance(proxied._pool, httpcore.AsyncHTTPProxy if asynchronous else httpcore.HTTPProxy) |
| 91 | + assert proxied._pool._proxy_url.host == b"127.0.0.1" |
| 92 | + assert proxied._pool._socket_options == transport.resolve_tcp_keepalive().socket_options() |
| 93 | + assert client._transport_for_url(httpx.URL("https://excluded.example")) is client._transport |
| 94 | + if asynchronous: |
| 95 | + asyncio.run(client.aclose()) |
| 96 | + else: |
| 97 | + client.close() |
| 98 | + |
| 99 | + |
| 100 | +@pytest.mark.parametrize("asynchronous", [False, True]) |
| 101 | +def test_unit_real_socket_keepalive(asynchronous): |
| 102 | + if not hasattr(socket, "SO_KEEPALIVE"): |
| 103 | + pytest.skip("SO_KEEPALIVE unavailable") |
| 104 | + |
| 105 | + class Handler(BaseHTTPRequestHandler): |
| 106 | + protocol_version = "HTTP/1.1" |
| 107 | + |
| 108 | + def do_GET(self): |
| 109 | + self.send_response(200) |
| 110 | + self.send_header("Content-Length", "2") |
| 111 | + self.end_headers() |
| 112 | + self.wfile.write(b"ok") |
| 113 | + |
| 114 | + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) |
| 115 | + thread = Thread(target=server.serve_forever, daemon=True) |
| 116 | + thread.start() |
| 117 | + url = f"http://127.0.0.1:{server.server_port}" |
| 118 | + |
| 119 | + def check(response): |
| 120 | + stream = response.extensions["network_stream"] |
| 121 | + sock = stream.get_extra_info("socket") |
| 122 | + enabled = sock.getsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE) |
| 123 | + # Darwin reports the option bit mask rather than a normalized boolean. |
| 124 | + if sys.platform == "darwin": |
| 125 | + assert enabled != 0 |
| 126 | + else: |
| 127 | + assert enabled == 1 |
| 128 | + |
| 129 | + async def request(): |
| 130 | + async with transport.create_async_http_client() as client: |
| 131 | + async with client.stream("GET", url) as response: |
| 132 | + check(response) |
| 133 | + await response.aread() |
| 134 | + |
| 135 | + try: |
| 136 | + if asynchronous: |
| 137 | + asyncio.run(request()) |
| 138 | + else: |
| 139 | + with transport.create_http_client() as client: |
| 140 | + with client.stream("GET", url) as response: |
| 141 | + check(response) |
| 142 | + response.read() |
| 143 | + finally: |
| 144 | + server.shutdown() |
| 145 | + server.server_close() |
| 146 | + thread.join() |
| 147 | + |
| 148 | + |
| 149 | +@pytest.mark.parametrize("asynchronous", [False, True]) |
| 150 | +def test_unit_https_proxy_receives_connect(monkeypatch, asynchronous): |
| 151 | + destinations = [] |
| 152 | + |
| 153 | + class ProxyHandler(BaseHTTPRequestHandler): |
| 154 | + def do_CONNECT(self): |
| 155 | + destinations.append(self.path) |
| 156 | + self.send_error(502) |
| 157 | + |
| 158 | + server = ThreadingHTTPServer(("127.0.0.1", 0), ProxyHandler) |
| 159 | + thread = Thread(target=server.serve_forever, daemon=True) |
| 160 | + thread.start() |
| 161 | + monkeypatch.setenv("HTTPS_PROXY", f"http://127.0.0.1:{server.server_port}") |
| 162 | + monkeypatch.setenv("NO_PROXY", "") |
| 163 | + |
| 164 | + async def request(): |
| 165 | + async with transport.create_async_http_client() as client: |
| 166 | + await client.get("https://proxy-target.invalid/") |
| 167 | + |
| 168 | + try: |
| 169 | + with pytest.raises(httpx.ProxyError, match="502"): |
| 170 | + if asynchronous: |
| 171 | + asyncio.run(request()) |
| 172 | + else: |
| 173 | + with transport.create_http_client() as client: |
| 174 | + client.get("https://proxy-target.invalid/") |
| 175 | + assert destinations == ["proxy-target.invalid:443"] |
| 176 | + finally: |
| 177 | + server.shutdown() |
| 178 | + server.server_close() |
| 179 | + thread.join() |
0 commit comments