pool.py
This file
Path
httpcore/pool.py
206 lines · 6.7 KiB · Python
Last changed by
Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
History of this fileTake it
Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
line 1why, one step back1import asyncioMerge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
line 2why, one step back2import functoolsMerge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 3–18why, one step back3import os4import ssl5import typing6from types import TracebackType78from .config import (9 DEFAULT_CA_BUNDLE_PATH,10 DEFAULT_POOL_LIMITS,11 DEFAULT_SSL_CONFIG,12 DEFAULT_TIMEOUT_CONFIG,13 PoolLimits,14 SSLConfig,15 TimeoutConfig,16)17from .connections import Connection18from .datastructures import URL, Request, ResponseMerge pull request #7 from encode/timeout-testsTom Christiebefore adoption34c03d7
line 19why, one step back19from .exceptions import PoolTimeoutMerge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
line 20why, one step back20Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 21why, one step back21ConnectionKey = typing.Tuple[str, str, int, SSLConfig, TimeoutConfig]Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
line 22why, one step back22Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 23–24why, one step back2324class ConnectionSemaphore:Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 25why, one step back25 def __init__(self, max_connections: int = None):Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 26–30why, one step back26 if max_connections is not None:27 self.semaphore = asyncio.BoundedSemaphore(value=max_connections)2829 async def acquire(self) -> None:30 if hasattr(self, "semaphore"):Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 31why, one step back31 await self.semaphore.acquire()Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 32–37why, one step back3233 def release(self) -> None:34 if hasattr(self, "semaphore"):35 self.semaphore.release()3637Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 38–49why, one step back38class ConnectionPool:39 def __init__(40 self,41 *,42 ssl: SSLConfig = DEFAULT_SSL_CONFIG,43 timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,44 limits: PoolLimits = DEFAULT_POOL_LIMITS,45 ):46 self.ssl_config = ssl47 self.timeout = timeout48 self.limits = limits49 self.is_closed = FalseMerge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 50–51why, one step back50 self.num_active_connections = 051 self.num_keepalive_connections = 0Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 52why, one step back52 self._keepalive_connections = (Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 53–54why, one step back53 {}54 ) # type: typing.Dict[ConnectionKey, typing.List[Connection]]Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
lines 55–56why, one step back55 self._max_connections = ConnectionSemaphore(56 max_connections=self.limits.hard_limitMerge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
line 57why, one step back57 )Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 58–66why, one step back5859 async def request(60 self,61 method: str,62 url: str,63 *,64 headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),65 body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",66 stream: bool = False,Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
lines 67–68why, one step back67 ssl: typing.Optional[SSLConfig] = None,68 timeout: typing.Optional[TimeoutConfig] = None,Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
line 69why, one step back69 ) -> Response:Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
lines 70–74why, one step back70 if ssl is None:71 ssl = self.ssl_config72 if timeout is None:73 timeout = self.timeout74Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 75–76why, one step back75 parsed_url = URL(url)76 request = Request(method, parsed_url, headers=headers, body=body)Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 77why, one step back77 connection = await self.acquire_connection(parsed_url, ssl=ssl, timeout=timeout)Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 78–83why, one step back78 response = await connection.send(request)79 if not stream:80 try:81 await response.read()82 finally:83 await response.close()Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 84–85why, one step back84 return response85Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 86–89why, one step back86 @property87 def num_connections(self) -> int:88 return self.num_active_connections + self.num_keepalive_connections89Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
line 90why, one step back90 async def acquire_connection(Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 91why, one step back91 self, url: URL, ssl: SSLConfig, timeout: TimeoutConfigMerge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
line 92why, one step back92 ) -> Connection:Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 93why, one step back93 key = (url.scheme, url.hostname, url.port, ssl, timeout)Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
line 94why, one step back94 try:Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
lines 95–97why, one step back95 connection = self._keepalive_connections[key].pop()96 if not self._keepalive_connections[key]:97 del self._keepalive_connections[key]Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 98–101why, one step back98 self.num_keepalive_connections -= 199 self.num_active_connections += 1100101 except (KeyError, IndexError):Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
lines 102–108why, one step back102 ssl_context = await self.get_ssl_context(url, ssl)103 try:104 await asyncio.wait_for(105 self._max_connections.acquire(), timeout.pool_timeout106 )107 except asyncio.TimeoutError:108 raise PoolTimeout()Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
line 109why, one step back109 release = functools.partial(self.release_connection, key=key)Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 110why, one step back110 connection = Connection(timeout=timeout, on_release=release)Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
line 111why, one step back111 self.num_active_connections += 1Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 112why, one step back112 await connection.open(url.hostname, url.port, ssl=ssl_context)Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
line 113why, one step back113Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 114–115why, one step back114 return connection115Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 116–119why, one step back116 async def release_connection(117 self, connection: Connection, key: ConnectionKey118 ) -> None:119 if connection.is_closed:Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 120why, one step back120 self._max_connections.release()Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 121–125why, one step back121 self.num_active_connections -= 1122 elif (123 self.limits.soft_limit is not None124 and self.num_connections > self.limits.soft_limit125 ):Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 126why, one step back126 self._max_connections.release()Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
lines 127–132why, one step back127 self.num_active_connections -= 1128 connection.close()129 else:130 self.num_active_connections -= 1131 self.num_keepalive_connections += 1132 try:Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 133why, one step back133 self._keepalive_connections[key].append(connection)Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
line 134why, one step back134 except KeyError:Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 135why, one step back135 self._keepalive_connections[key] = [connection]Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
line 136why, one step back136Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
lines 137–139why, one step back137 async def get_ssl_context(138 self, url: URL, config: SSLConfig139 ) -> typing.Optional[ssl.SSLContext]:Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
line 140why, one step back140 if not url.is_secure:Merge pull request #4 from encode/connection-poolingTom Christiebefore adoption68c468a
line 141why, one step back141 return NoneMerge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 142–143why, one step back142143 if not hasattr(self, "ssl_context"):Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 144why, one step back144 if not config.verify:Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 145–165why, one step back145 self.ssl_context = self.get_ssl_context_no_verify()146 else:147 # Run the SSL loading in a threadpool, since it makes disk accesses.148 loop = asyncio.get_event_loop()149 self.ssl_context = await loop.run_in_executor(150 None, self.get_ssl_context_verify151 )152153 return self.ssl_context154155 def get_ssl_context_no_verify(self) -> ssl.SSLContext:156 """157 Return an SSL context for unverified connections.158 """159 context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)160 context.options |= ssl.OP_NO_SSLv2161 context.options |= ssl.OP_NO_SSLv3162 context.options |= ssl.OP_NO_COMPRESSION163 context.set_default_verify_paths()164 return context165Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 166why, one step back166 def get_ssl_context_verify(self, config: SSLConfig) -> ssl.SSLContext:Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 167–169why, one step back167 """168 Return an SSL context for verified connections.169 """Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 170why, one step back170 if isinstance(config.verify, bool):Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
line 171why, one step back171 ca_bundle_path = DEFAULT_CA_BUNDLE_PATHMerge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
lines 172–173why, one step back172 elif os.path.exists(config.verify):173 ca_bundle_path = config.verifyMerge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 174–176why, one step back174 else:175 raise IOError(176 "Could not find a suitable TLS CA certificate bundle, "Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 177why, one step back177 "invalid path: {}".format(config.verify)Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 178–185why, one step back178 )179180 context = ssl.create_default_context()181 if os.path.isfile(ca_bundle_path):182 context.load_verify_locations(cafile=ca_bundle_path)183 elif os.path.isdir(ca_bundle_path):184 context.load_verify_locations(capath=ca_bundle_path)185Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
lines 186–188why, one step back186 if config.cert is not None:187 if isinstance(config.cert, str):188 context.load_cert_chain(certfile=config.cert)Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
line 189why, one step back189 else:Merge pull request #9 from encode/allow_per_request_timeout_and_sslTom Christiebefore adoptiondf84cde
line 190why, one step back190 context.load_cert_chain(certfile=config.cert[0], keyfile=config.cert[1])Merge pull request #1 from encode/add-connectionsTom Christiebefore adoption7626fe7
lines 191–206why, one step back191192 return context193194 async def close(self) -> None:195 self.is_closed = True196197 async def __aenter__(self) -> "ConnectionPool":198 return self199200 async def __aexit__(201 self,202 exc_type: typing.Type[BaseException] = None,203 exc_value: BaseException = None,204 traceback: TracebackType = None,205 ) -> None:206 await self.close()