Skip to content
Myr

connection_pool.py

This file

Path

httpcore/dispatch/connection_pool.py

167 lines · 5.2 KiB · Python

Last changed by

Merge pull request #60 from encode/concurrency-backend-classTom Christiebefore adoption3d997af

History of this file

Take it

1import collections.abc2import typing34from ..concurrency import AsyncioBackend5from ..config import (6    DEFAULT_CA_BUNDLE_PATH,7    DEFAULT_POOL_LIMITS,8    DEFAULT_SSL_CONFIG,9    DEFAULT_TIMEOUT_CONFIG,10    PoolLimits,11    SSLConfig,12    TimeoutConfig,13)14from ..decoders import ACCEPT_ENCODING15from ..exceptions import PoolTimeout16from ..interfaces import ConcurrencyBackend, Dispatcher17from ..models import Origin, Request, Response18from .connection import HTTPConnection1920CONNECTIONS_DICT = typing.Dict[Origin, typing.List[HTTPConnection]]212223class ConnectionStore(collections.abc.Sequence):24    """25    We need to maintain collections of connections in a way that allows us to:2627    * Lookup connections by origin.28    * Iterate over connections by insertion time.29    * Return the total number of connections.30    """3132    def __init__(self) -> None:33        self.all = {}  # type: typing.Dict[HTTPConnection, float]34        self.by_origin = (35            {}36        )  # type: typing.Dict[Origin, typing.Dict[HTTPConnection, float]]3738    def pop_by_origin(39        self, origin: Origin, http2_only: bool = False40    ) -> typing.Optional[HTTPConnection]:41        try:42            connections = self.by_origin[origin]43        except KeyError:44            return None4546        connection = next(reversed(list(connections.keys())))47        if http2_only and not connection.is_http2:48            return None4950        del connections[connection]51        if not connections:52            del self.by_origin[origin]53        del self.all[connection]5455        return connection5657    def add(self, connection: HTTPConnection) -> None:58        self.all[connection] = 0.059        try:60            self.by_origin[connection.origin][connection] = 0.061        except KeyError:62            self.by_origin[connection.origin] = {connection: 0.0}6364    def remove(self, connection: HTTPConnection) -> None:65        del self.all[connection]66        del self.by_origin[connection.origin][connection]67        if not self.by_origin[connection.origin]:68            del self.by_origin[connection.origin]6970    def clear(self) -> None:71        self.all.clear()72        self.by_origin.clear()7374    def __iter__(self) -> typing.Iterator[HTTPConnection]:75        return iter(self.all.keys())7677    def __getitem__(self, key: typing.Any) -> typing.Any:78        if key in self.all:79            return key80        return None8182    def __len__(self) -> int:83        return len(self.all)848586class ConnectionPool(Dispatcher):87    def __init__(88        self,89        *,90        ssl: SSLConfig = DEFAULT_SSL_CONFIG,91        timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,92        pool_limits: PoolLimits = DEFAULT_POOL_LIMITS,93        backend: ConcurrencyBackend = None,94    ):95        self.ssl = ssl96        self.timeout = timeout97        self.pool_limits = pool_limits98        self.is_closed = False99100        self.keepalive_connections = ConnectionStore()101        self.active_connections = ConnectionStore()102103        self.backend = AsyncioBackend() if backend is None else backend104        self.max_connections = self.backend.get_semaphore(pool_limits)105106    @property107    def num_connections(self) -> int:108        return len(self.keepalive_connections) + len(self.active_connections)109110    async def send(111        self,112        request: Request,113        stream: bool = False,114        ssl: SSLConfig = None,115        timeout: TimeoutConfig = None,116    ) -> Response:117        connection = await self.acquire_connection(request.url.origin)118        try:119            response = await connection.send(120                request, stream=stream, ssl=ssl, timeout=timeout121            )122        except BaseException as exc:123            self.active_connections.remove(connection)124            self.max_connections.release()125            raise exc126        return response127128    async def acquire_connection(self, origin: Origin) -> HTTPConnection:129        connection = self.active_connections.pop_by_origin(origin, http2_only=True)130        if connection is None:131            connection = self.keepalive_connections.pop_by_origin(origin)132133        if connection is None:134            await self.max_connections.acquire()135            connection = HTTPConnection(136                origin,137                ssl=self.ssl,138                timeout=self.timeout,139                backend=self.backend,140                release_func=self.release_connection,141            )142143        self.active_connections.add(connection)144145        return connection146147    async def release_connection(self, connection: HTTPConnection) -> None:148        if connection.is_closed:149            self.active_connections.remove(connection)150            self.max_connections.release()151        elif (152            self.pool_limits.soft_limit is not None153            and self.num_connections > self.pool_limits.soft_limit154        ):155            self.active_connections.remove(connection)156            self.max_connections.release()157            await connection.close()158        else:159            self.active_connections.remove(connection)160            self.keepalive_connections.add(connection)161162    async def close(self) -> None:163        self.is_closed = True164        connections = list(self.keepalive_connections)165        self.keepalive_connections.clear()166        for connection in connections:167            await connection.close()