pool.py
This file
Path
httpcore/pool.py
126 lines · 4.0 KiB · Python
Last changed by
Add SyncConnectionPoolTom Christiebefore adoption4a36ec7
History of this fileTake it
1import asyncio2import typing34from .config import (5 DEFAULT_CA_BUNDLE_PATH,6 DEFAULT_POOL_LIMITS,7 DEFAULT_SSL_CONFIG,8 DEFAULT_TIMEOUT_CONFIG,9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12)13from .connections import Connection14from .datastructures import Client, Origin, Request, Response15from .exceptions import PoolTimeout161718class ConnectionPool(Client):19 def __init__(20 self,21 *,22 ssl: SSLConfig = DEFAULT_SSL_CONFIG,23 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24 limits: PoolLimits = DEFAULT_POOL_LIMITS,25 ):26 self.ssl = ssl27 self.timeout = timeout28 self.limits = limits29 self.is_closed = False30 self.num_active_connections = 031 self.num_keepalive_connections = 032 self._keepalive_connections = (33 {}34 ) # type: typing.Dict[Origin, typing.List[Connection]]35 self._max_connections = ConnectionSemaphore(36 max_connections=self.limits.hard_limit37 )3839 async def send(40 self,41 request: Request,42 *,43 ssl: typing.Optional[SSLConfig] = None,44 timeout: typing.Optional[TimeoutConfig] = None,45 ) -> Response:46 connection = await self.acquire_connection(request.url.origin, timeout=timeout)47 response = await connection.send(request, ssl=ssl, timeout=timeout)48 return response4950 @property51 def num_connections(self) -> int:52 return self.num_active_connections + self.num_keepalive_connections5354 async def acquire_connection(55 self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None56 ) -> Connection:57 try:58 connection = self._keepalive_connections[origin].pop()59 if not self._keepalive_connections[origin]:60 del self._keepalive_connections[origin]61 self.num_keepalive_connections -= 162 self.num_active_connections += 16364 except (KeyError, IndexError):65 if timeout is None:66 pool_timeout = self.timeout.pool_timeout67 else:68 pool_timeout = timeout.pool_timeout6970 try:71 await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)72 except asyncio.TimeoutError:73 raise PoolTimeout()74 connection = Connection(75 origin,76 ssl=self.ssl,77 timeout=self.timeout,78 on_release=self.release_connection,79 )80 self.num_active_connections += 18182 return connection8384 async def release_connection(self, connection: Connection) -> None:85 if connection.is_closed:86 self._max_connections.release()87 self.num_active_connections -= 188 elif (89 self.limits.soft_limit is not None90 and self.num_connections > self.limits.soft_limit91 ):92 self._max_connections.release()93 self.num_active_connections -= 194 await connection.close()95 else:96 self.num_active_connections -= 197 self.num_keepalive_connections += 198 try:99 self._keepalive_connections[connection.origin].append(connection)100 except KeyError:101 self._keepalive_connections[connection.origin] = [connection]102103 async def close(self) -> None:104 self.is_closed = True105106107class ConnectionSemaphore:108 def __init__(self, max_connections: int = None):109 self.max_connections = max_connections110111 @property112 def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:113 if not hasattr(self, "_semaphore"):114 if self.max_connections is None:115 self._semaphore = None116 else:117 self._semaphore = asyncio.BoundedSemaphore(value=self.max_connections)118 return self._semaphore119120 async def acquire(self) -> None:121 if self.semaphore is not None:122 await self.semaphore.acquire()123124 def release(self) -> None:125 if self.semaphore is not None:126 self.semaphore.release()