Skip to content
Myr

Keep-alive timeouts. (#627)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* Add .time() to backend * Add connection timeouts * Add test case for keep alive timeouts * Update httpx/dispatch/connection_pool.py Co-Authored-By: Florimond Manca <florimond.manca@gmail.com> * Cleanups from review * Use .expires_at, rather than .timeout_at

authored by Tom Christie · committed by GitHub · parent 77da6db · Browse files · 7 files+66 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+66 added−0 removed

  • tests:+31 added−0 removed
  • other:+35 added−0 removed

7 files+66 added−0 removed

modified:httpx/concurrency/asyncio.py+4 added
240 unmodified lines
241 raise ConnectTimeout()242243 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)244245 def time(self) -> float:246 loop = asyncio.get_event_loop()247 return loop.time()248249 async def run_in_threadpool(250 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any251 ) -> typing.Any:252 if kwargs:
31 unmodified lines
modified:httpx/concurrency/auto.py+3 added
39 unmodified lines
40 timeout: Timeout,41 ) -> BaseSocketStream:42 return await self.backend.open_uds_stream(path, hostname, ssl_context, timeout)4344 def time(self) -> float:45 return self.backend.time()4647 def get_semaphore(self, max_value: int) -> BasePoolSemaphore:48 return self.backend.get_semaphore(max_value)4950 async def run_in_threadpool(
6 unmodified lines
modified:httpx/concurrency/base.py+3 added
97 unmodified lines
98 timeout: Timeout,99 ) -> BaseSocketStream:100 raise NotImplementedError() # pragma: no cover101102 def time(self) -> float:103 raise NotImplementedError() # pragma: no cover104105 def get_semaphore(self, max_value: int) -> BasePoolSemaphore:106 raise NotImplementedError() # pragma: no cover107108 async def run_in_threadpool(
11 unmodified lines
modified:httpx/concurrency/trio.py+3 added
154 unmodified lines
155 return trio.run(156 functools.partial(coroutine, **kwargs) if kwargs else coroutine, *args157 )158159 def time(self) -> float:160 return trio.current_time()161162 def get_semaphore(self, max_value: int) -> BasePoolSemaphore:163 return PoolSemaphore(max_value)164165 def create_event(self) -> BaseEvent:
12 unmodified lines
modified:httpx/dispatch/connection_pool.py+21 added
76 unmodified lines
77 return len(self.all)787980class ConnectionPool(Dispatcher):81 KEEP_ALIVE_EXPIRY = 5.08283 def __init__(84 self,85 *,86 verify: VerifyTypes = True,
15 unmodified lines
102 self.keepalive_connections = ConnectionStore()103 self.active_connections = ConnectionStore()104105 self.backend = lookup_backend(backend)106 self.next_keepalive_check = 0.0107108 @property109 def max_connections(self) -> BasePoolSemaphore:110 # We do this lazily, to make sure backend autodetection always
9 unmodified lines
120 @property121 def num_connections(self) -> int:122 return len(self.keepalive_connections) + len(self.active_connections)123124 async def check_keepalive_expiry(self) -> None:125 now = self.backend.time()126 if now < self.next_keepalive_check:127 return128 self.next_keepalive_check = now + 1.0129130 # Iterate through all the keep alive connections.131 # We create a list here to avoid any 'changed during iteration' errors.132 keepalives = list(self.keepalive_connections.all.keys())133 for connection in keepalives:134 if connection.expires_at is not None and now > connection.expires_at:135 self.keepalive_connections.remove(connection)136 self.max_connections.release()137 await connection.close()138139 async def send(140 self,141 request: Request,142 verify: VerifyTypes = None,143 cert: CertTypes = None,144 timeout: Timeout = None,145 ) -> Response:146 await self.check_keepalive_expiry()147 connection = await self.acquire_connection(148 origin=request.url.origin, timeout=timeout149 )150 try:
47 unmodified lines
198 self.active_connections.remove(connection)199 self.max_connections.release()200 await connection.close()201 else:202 now = self.backend.time()203 connection.expires_at = now + self.KEEP_ALIVE_EXPIRY204 self.active_connections.remove(connection)205 self.keepalive_connections.add(connection)206207 async def close(self) -> None:
16 unmodified lines
modified:httpx/dispatch/connection.py+1 added
36 unmodified lines
37 self.backend = lookup_backend(backend)38 self.release_func = release_func39 self.uds = uds40 self.open_connection: typing.Optional[OpenConnection] = None41 self.expires_at: typing.Optional[float] = None4243 async def send(44 self,45 request: Request,
144 unmodified lines
modified:tests/dispatch/test_connection_pools.py+31 added
16 unmodified lines
17 assert len(http.active_connections) == 018 assert len(http.keepalive_connections) == 1192021async def test_keepalive_timeout(server, backend):22 """23 Keep-alive connections should timeout.24 """25 async with ConnectionPool() as http:26 response = await http.request("GET", server.url)27 await response.read()28 assert len(http.active_connections) == 029 assert len(http.keepalive_connections) == 13031 http.next_keepalive_check = 0.032 await http.check_keepalive_expiry()3334 assert len(http.active_connections) == 035 assert len(http.keepalive_connections) == 13637 async with ConnectionPool() as http:38 http.KEEP_ALIVE_EXPIRY = 0.03940 response = await http.request("GET", server.url)41 await response.read()42 assert len(http.active_connections) == 043 assert len(http.keepalive_connections) == 14445 http.next_keepalive_check = 0.046 await http.check_keepalive_expiry()4748 assert len(http.active_connections) == 049 assert len(http.keepalive_connections) == 0505152async def test_differing_connection_keys(server, backend):53 """54 Connections to differing connection keys should result in multiple connections.55 """
156 unmodified lines