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
Provenance
- Commit
499de51- Tree
d74cb17- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
77da6db
7 files changed+66 added−0 removed
modified:httpx/concurrency/asyncio.py+4 added
240 unmodified lines241 raise ConnectTimeout()242 243 return SocketStream(stream_reader=stream_reader, stream_writer=stream_writer)244 245+ def time(self) -> float:246+ loop = asyncio.get_event_loop()247+ return loop.time()248+249 async def run_in_threadpool(250 self, func: typing.Callable, *args: typing.Any, **kwargs: typing.Any251 ) -> typing.Any:252 if kwargs:31 unmodified linesmodified:httpx/concurrency/auto.py+3 added
39 unmodified lines40 timeout: Timeout,41 ) -> BaseSocketStream:42 return await self.backend.open_uds_stream(path, hostname, ssl_context, timeout)43 44+ def time(self) -> float:45+ return self.backend.time()46+47 def get_semaphore(self, max_value: int) -> BasePoolSemaphore:48 return self.backend.get_semaphore(max_value)49 50 async def run_in_threadpool(6 unmodified linesmodified:httpx/concurrency/base.py+3 added
97 unmodified lines98 timeout: Timeout,99 ) -> BaseSocketStream:100 raise NotImplementedError() # pragma: no cover101 102+ def time(self) -> float:103+ raise NotImplementedError() # pragma: no cover104+105 def get_semaphore(self, max_value: int) -> BasePoolSemaphore:106 raise NotImplementedError() # pragma: no cover107 108 async def run_in_threadpool(11 unmodified linesmodified:httpx/concurrency/trio.py+3 added
154 unmodified lines155 return trio.run(156 functools.partial(coroutine, **kwargs) if kwargs else coroutine, *args157 )158 159+ def time(self) -> float:160+ return trio.current_time()161+162 def get_semaphore(self, max_value: int) -> BasePoolSemaphore:163 return PoolSemaphore(max_value)164 165 def create_event(self) -> BaseEvent:12 unmodified linesmodified:httpx/dispatch/connection_pool.py+21 added
76 unmodified lines77 return len(self.all)78 79 80 class ConnectionPool(Dispatcher):81+ KEEP_ALIVE_EXPIRY = 5.082+83 def __init__(84 self,85 *,86 verify: VerifyTypes = True,15 unmodified lines102 self.keepalive_connections = ConnectionStore()103 self.active_connections = ConnectionStore()104 105 self.backend = lookup_backend(backend)106+ self.next_keepalive_check = 0.0107 108 @property109 def max_connections(self) -> BasePoolSemaphore:110 # We do this lazily, to make sure backend autodetection always9 unmodified lines120 @property121 def num_connections(self) -> int:122 return len(self.keepalive_connections) + len(self.active_connections)123 124+ 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.0129+130+ # 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()138+139 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 lines198 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)206 207 async def close(self) -> None:16 unmodified linesmodified:httpx/dispatch/connection.py+1 added
36 unmodified lines37 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] = None42 43 async def send(44 self,45 request: Request,144 unmodified linesmodified:tests/dispatch/test_connection_pools.py+31 added
16 unmodified lines17 assert len(http.active_connections) == 018 assert len(http.keepalive_connections) == 119 20 21+async 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) == 130+31+ http.next_keepalive_check = 0.032+ await http.check_keepalive_expiry()33+34+ assert len(http.active_connections) == 035+ assert len(http.keepalive_connections) == 136+37+ async with ConnectionPool() as http:38+ http.KEEP_ALIVE_EXPIRY = 0.039+40+ response = await http.request("GET", server.url)41+ await response.read()42+ assert len(http.active_connections) == 043+ assert len(http.keepalive_connections) == 144+45+ http.next_keepalive_check = 0.046+ await http.check_keepalive_expiry()47+48+ assert len(http.active_connections) == 049+ assert len(http.keepalive_connections) == 050+51+52 async def test_differing_connection_keys(server, backend):53 """54 Connections to differing connection keys should result in multiple connections.55 """156 unmodified lines