Repository navigation
Timeout during AnyIOStream.start_tls causes stuck connections in the pool when using AsyncHTTPProxy #905
Replies: 2 comments
|
The failure window described here is still visible in current main.
stream = await stream.start_tls(...)Only after TLS succeeds does it replace If So the cleanup invariant should be: once CONNECT succeeds, failure of TLS upgrade must make that tunnel connection unusable and close its underlying stream/connection before propagating the timeout/error. The critical cleanup should also be cancellation-safe, for the same reason response cleanup is shielded elsewhere in current async httpcore. A focused regression test can avoid a real proxy: have a mock proxy return a successful CONNECT and a network stream whose That targets the actual ownership transition—CONNECT has consumed the proxy connection, TLS failed before the remote HTTP connection was installed—rather than special-casing timeout as such. |
|
Still reproducible with httpx 0.28.1 / httpcore 1.0.9 (latest), with no monkeypatching: a proxy that accepts CONNECT and then never answers (what a dead upstream behind an HTTP proxy looks like) is enough. import asyncio
import httpcore
import httpx
async def dead_tunnel(reader, writer):
# A proxy whose next hop is dead: CONNECT is accepted, then nothing comes back.
await reader.readuntil(b"\r\n\r\n")
writer.write(b"HTTP/1.1 200 Connection established\r\n\r\n")
await writer.drain()
try:
while await reader.read(65536):
pass # swallow the TLS ClientHello, never answer
finally:
writer.close()
async def main():
server = await asyncio.start_server(dead_tunnel, "127.0.0.1", 0)
port = server.sockets[0].getsockname()[1]
print("httpx", httpx.__version__, "httpcore", httpcore.__version__)
async with httpx.AsyncClient(
proxy=f"http://127.0.0.1:{port}",
limits=httpx.Limits(max_connections=2),
timeout=httpx.Timeout(1.0, pool=0.5),
) as client:
for i in range(4):
try:
await client.get("https://example.com/")
except httpx.HTTPError as exc:
print(i, type(exc).__name__)
pool = next(iter(client._mounts.values()))._pool
print("pool:", pool.connections)
server.close()
asyncio.run(main())Output: Each |
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
Example
Hi!
Please excuse my hacky way to demonstrate the issue:
Setup:
To replicate:
proxy.py:proxy --hostname 127.0.0.1 --port 8080You should see that every time a timeout happens during
start_tls, after just having reconnected to the proxy, there is a new stuck connection in the pool that looks like this:<AsyncTunnelHTTPConnection ['http://127.0.0.1:8080', HTTP/1.1, ACTIVE, Request Count: 1]>Context
We have a bunch of Telegram bots on
python-telegram-botrunning behind a proxy. Once every couple of weeks they all simultaneously stop responding - judging by the logs this seems to be the root issue.All reactions