Skip to content
Myr

connection_pool.py

This file

Path

httpcore/dispatch/connection_pool.py

161 lines · 5.0 KiB · Python

Last changed by

Drop unused interface on ConnectionStore (#70)Tom Christiebefore adoption3ed0885

History of this file

Take it

1import typing23from ..concurrency import AsyncioBackend4from ..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 ..decoders import ACCEPT_ENCODING14from ..exceptions import PoolTimeout15from ..interfaces import ConcurrencyBackend, Dispatcher16from ..models import Origin, Request, Response17from .connection import HTTPConnection1819CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]202122class ConnectionStore:23    """24    We need to maintain collections of connections in a way that allows us to:2526    * Lookup connections by origin.27    * Iterate over connections by insertion time.28    * Return the total number of connections.29    """3031    def __init__(self) -> None:32        self.all = {}  # type: typing.Dict[HTTPConnection, float]33        self.by_origin = (34            {}35        )  # type: typing.Dict[Origin, typing.Dict[HTTPConnection, float]]3637    def pop_by_origin(38        self, origin: Origin, http2_only: bool = False39    ) -> typing.Optional[HTTPConnection]:40        try:41            connections = self.by_origin[origin]42        except KeyError:43            return None4445        connection = next(reversed(list(connections.keys())))46        if http2_only and not connection.is_http2:47            return None4849        del connections[connection]50        if not connections:51            del self.by_origin[origin]52        del self.all[connection]5354        return connection5556    def add(self, connection: HTTPConnection) -> None:57        self.all[connection] = 0.058        try:59            self.by_origin[connection.origin][connection] = 0.060        except KeyError:61            self.by_origin[connection.origin] = {connection: 0.0}6263    def remove(self, connection: HTTPConnection) -> None:64        del self.all[connection]65        del self.by_origin[connection.origin][connection]66        if not self.by_origin[connection.origin]:67            del self.by_origin[connection.origin]6869    def clear(self) -> None:70        self.all.clear()71        self.by_origin.clear()7273    def __iter__(self) -> typing.Iterator[HTTPConnection]:74        return iter(self.all.keys())7576    def __len__(self) -> int:77        return len(self.all)787980class ConnectionPool(Dispatcher):81    def __init__(82        self,83        *,84        ssl: SSLConfig = DEFAULT_SSL_CONFIG,85        timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,86        pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,87        backend: ConcurrencyBackend = None,88    ):89        self.ssl = ssl90        self.timeout = timeout91        self.pool_limits = pool_limits92        self.is_closed = False9394        self.keepalive_connections = ConnectionStore()95        self.active_connections = ConnectionStore()9697        self.backend = AsyncioBackend() if backend is None else backend98        self.max_connections = self.backend.get_semaphore(pool_limits)99100    @property101    def num_connections(self) -> int:102        return len(self.keepalive_connections) + len(self.active_connections)103104    async def send(105        self,106        request: Request,107        stream: bool = False,108        ssl: SSLConfig = None,109        timeout: TimeoutConfig = None,110    ) -> Response:111        connection = await self.acquire_connection(request.url.origin)112        try:113            response = await connection.send(114                request, stream=stream, ssl=ssl, timeout=timeout115            )116        except BaseException as exc:117            self.active_connections.remove(connection)118            self.max_connections.release()119            raise exc120        return response121122    async def acquire_connection(self, origin: Origin) -> HTTPConnection:123        connection = self.active_connections.pop_by_origin(origin, http2_only=True)124        if connection is None:125            connection = self.keepalive_connections.pop_by_origin(origin)126127        if connection is None:128            await self.max_connections.acquire()129            connection = HTTPConnection(130                origin,131                ssl=self.ssl,132                timeout=self.timeout,133                backend=self.backend,134                release_func=self.release_connection,135            )136137        self.active_connections.add(connection)138139        return connection140141    async def release_connection(self, connection: HTTPConnection) -> None:142        if connection.is_closed:143            self.active_connections.remove(connection)144            self.max_connections.release()145        elif (146            self.pool_limits.soft_limit is not None147            and self.num_connections > self.pool_limits.soft_limit148        ):149            self.active_connections.remove(connection)150            self.max_connections.release()151            await connection.close()152        else:153            self.active_connections.remove(connection)154            self.keepalive_connections.add(connection)155156    async def close(self) -> None:157        self.is_closed = True158        connections = list(self.keepalive_connections)159        self.keepalive_connections.clear()160        for connection in connections:161            await connection.close()