Skip to content
Myr

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 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, SSLConfig, TimeoutConfig]222324class ConnectionSemaphore:25    def __init__(self, max_connections: int = None):26        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"):31            await self.semaphore.acquire()3233    def release(self) -> None:34        if hasattr(self, "semaphore"):35            self.semaphore.release()363738class 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 = False50        self.num_active_connections = 051        self.num_keepalive_connections = 052        self._keepalive_connections = (53            {}54        )  # type: typing.Dict[ConnectionKey, typing.List[Connection]]55        self._max_connections = ConnectionSemaphore(56            max_connections=self.limits.hard_limit57        )5859    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,67        ssl: typing.Optional[SSLConfig] = None,68        timeout: typing.Optional[TimeoutConfig] = None,69    ) -> Response:70        if ssl is None:71            ssl = self.ssl_config72        if timeout is None:73            timeout = self.timeout7475        parsed_url = URL(url)76        request = Request(method, parsed_url, headers=headers, body=body)77        connection = await self.acquire_connection(parsed_url, ssl=ssl, timeout=timeout)78        response = await connection.send(request)79        if not stream:80            try:81                await response.read()82            finally:83                await response.close()84        return response8586    @property87    def num_connections(self) -> int:88        return self.num_active_connections + self.num_keepalive_connections8990    async def acquire_connection(91        self, url: URL, ssl: SSLConfig, timeout: TimeoutConfig92    ) -> Connection:93        key = (url.scheme, url.hostname, url.port, ssl, timeout)94        try:95            connection = self._keepalive_connections[key].pop()96            if not self._keepalive_connections[key]:97                del self._keepalive_connections[key]98            self.num_keepalive_connections -= 199            self.num_active_connections += 1100101        except (KeyError, IndexError):102            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()109            release = functools.partial(self.release_connection, key=key)110            connection = Connection(timeout=timeout, on_release=release)111            self.num_active_connections += 1112            await connection.open(url.hostname, url.port, ssl=ssl_context)113114        return connection115116    async def release_connection(117        self, connection: Connection, key: ConnectionKey118    ) -> None:119        if connection.is_closed:120            self._max_connections.release()121            self.num_active_connections -= 1122        elif (123            self.limits.soft_limit is not None124            and self.num_connections > self.limits.soft_limit125        ):126            self._max_connections.release()127            self.num_active_connections -= 1128            connection.close()129        else:130            self.num_active_connections -= 1131            self.num_keepalive_connections += 1132            try:133                self._keepalive_connections[key].append(connection)134            except KeyError:135                self._keepalive_connections[key] = [connection]136137    async def get_ssl_context(138        self, url: URL, config: SSLConfig139    ) -> typing.Optional[ssl.SSLContext]:140        if not url.is_secure:141            return None142143        if not hasattr(self, "ssl_context"):144            if not config.verify:145                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 context165166    def get_ssl_context_verify(self, config: SSLConfig) -> ssl.SSLContext:167        """168        Return an SSL context for verified connections.169        """170        if isinstance(config.verify, bool):171            ca_bundle_path = DEFAULT_CA_BUNDLE_PATH172        elif os.path.exists(config.verify):173            ca_bundle_path = config.verify174        else:175            raise IOError(176                "Could not find a suitable TLS CA certificate bundle, "177                "invalid path: {}".format(config.verify)178            )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)185186        if config.cert is not None:187            if isinstance(config.cert, str):188                context.load_cert_chain(certfile=config.cert)189            else:190                context.load_cert_chain(certfile=config.cert[0], keyfile=config.cert[1])191192        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()