Skip to content
Myr

pool.py

This file

Path

httpcore/pool.py

199 lines · 6.5 KiB · Python

Last changed by

Merge pull request #7 from encode/timeout-testsTom Christiebefore adoption34c03d7

History of this file

Take it

1import asyncio2import functools3import 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, Response19from .exceptions import PoolTimeout2021ConnectionKey = typing.Tuple[str, str, int]  # (scheme, host, port)222324class ConnectionSemaphore:25    def __init__(self, max_connections: int = None, timeout: float = None):26        self.timeout = timeout27        if max_connections is not None:28            self.semaphore = asyncio.BoundedSemaphore(value=max_connections)2930    async def acquire(self) -> None:31        if hasattr(self, "semaphore"):32            try:33                await asyncio.wait_for(self.semaphore.acquire(), self.timeout)34            except asyncio.TimeoutError:35                raise PoolTimeout()3637    def release(self) -> None:38        if hasattr(self, "semaphore"):39            self.semaphore.release()404142class ConnectionPool:43    def __init__(44        self,45        *,46        ssl: SSLConfig = DEFAULT_SSL_CONFIG,47        timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,48        limits: PoolLimits = DEFAULT_POOL_LIMITS,49    ):50        self.ssl_config = ssl51        self.timeout = timeout52        self.limits = limits53        self.is_closed = False54        self.num_active_connections = 055        self.num_keepalive_connections = 056        self._connections = (57            {}58        )  # type: typing.Dict[ConnectionKey, typing.List[Connection]]59        self._connection_semaphore = ConnectionSemaphore(60            max_connections=self.limits.hard_limit, timeout=self.timeout.pool_timeout61        )6263    async def request(64        self,65        method: str,66        url: str,67        *,68        headers: typing.Sequence[typing.Tuple[bytes, bytes]] = (),69        body: typing.Union[bytes, typing.AsyncIterator[bytes]] = b"",70        stream: bool = False,71    ) -> Response:72        parsed_url = URL(url)73        request = Request(method, parsed_url, headers=headers, body=body)74        ssl_context = await self.get_ssl_context(parsed_url)75        connection = await self.acquire_connection(parsed_url, ssl=ssl_context)76        response = await connection.send(request)77        if not stream:78            try:79                await response.read()80            finally:81                await response.close()82        return response8384    @property85    def num_connections(self) -> int:86        return self.num_active_connections + self.num_keepalive_connections8788    async def acquire_connection(89        self, url: URL, *, ssl: typing.Optional[ssl.SSLContext] = None90    ) -> Connection:91        key = (url.scheme, url.hostname, url.port)92        try:93            connection = self._connections[key].pop()94            if not self._connections[key]:95                del self._connections[key]96            self.num_keepalive_connections -= 197            self.num_active_connections += 19899        except (KeyError, IndexError):100            await self._connection_semaphore.acquire()101            release = functools.partial(self.release_connection, key=key)102            connection = Connection(timeout=self.timeout, on_release=release)103            self.num_active_connections += 1104            await connection.open(url.hostname, url.port, ssl=ssl)105106        return connection107108    async def release_connection(109        self, connection: Connection, key: ConnectionKey110    ) -> None:111        if connection.is_closed:112            self._connection_semaphore.release()113            self.num_active_connections -= 1114        elif (115            self.limits.soft_limit is not None116            and self.num_connections > self.limits.soft_limit117        ):118            self._connection_semaphore.release()119            self.num_active_connections -= 1120            connection.close()121        else:122            self.num_active_connections -= 1123            self.num_keepalive_connections += 1124            try:125                self._connections[key].append(connection)126            except KeyError:127                self._connections[key] = [connection]128129    async def get_ssl_context(self, url: URL) -> typing.Optional[ssl.SSLContext]:130        if not url.is_secure:131            return None132133        if not hasattr(self, "ssl_context"):134            if not self.ssl_config.verify:135                self.ssl_context = self.get_ssl_context_no_verify()136            else:137                # Run the SSL loading in a threadpool, since it makes disk accesses.138                loop = asyncio.get_event_loop()139                self.ssl_context = await loop.run_in_executor(140                    None, self.get_ssl_context_verify141                )142143        return self.ssl_context144145    def get_ssl_context_no_verify(self) -> ssl.SSLContext:146        """147        Return an SSL context for unverified connections.148        """149        context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)150        context.options |= ssl.OP_NO_SSLv2151        context.options |= ssl.OP_NO_SSLv3152        context.options |= ssl.OP_NO_COMPRESSION153        context.set_default_verify_paths()154        return context155156    def get_ssl_context_verify(self) -> ssl.SSLContext:157        """158        Return an SSL context for verified connections.159        """160        cert = self.ssl_config.cert161        verify = self.ssl_config.verify162163        if isinstance(verify, bool):164            ca_bundle_path = DEFAULT_CA_BUNDLE_PATH165        elif os.path.exists(verify):166            ca_bundle_path = verify167        else:168            raise IOError(169                "Could not find a suitable TLS CA certificate bundle, "170                "invalid path: {}".format(verify)171            )172173        context = ssl.create_default_context()174        if os.path.isfile(ca_bundle_path):175            context.load_verify_locations(cafile=ca_bundle_path)176        elif os.path.isdir(ca_bundle_path):177            context.load_verify_locations(capath=ca_bundle_path)178179        if cert is not None:180            if isinstance(cert, str):181                context.load_cert_chain(certfile=cert)182            else:183                context.load_cert_chain(certfile=cert[0], keyfile=cert[1])184185        return context186187    async def close(self) -> None:188        self.is_closed = True189190    async def __aenter__(self) -> "ConnectionPool":191        return self192193    async def __aexit__(194        self,195        exc_type: typing.Type[BaseException] = None,196        exc_value: BaseException = None,197        traceback: TracebackType = None,198    ) -> None:199        await self.close()