Skip to content
Myr

connectionpool.py

This file

Path

httpcore/connectionpool.py

132 lines · 4.3 KiB · Python

Last changed by

Merge pull request #17 from encode/close-keepalive-connectionsTom Christiebefore adoption91a2a1b

History of this file

Take it

1import asyncio2import typing34from .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 .datastructures import Client, Origin, Request, Response14from .exceptions import PoolTimeout15from .http11 import HTTP11Connection161718class ConnectionPool(Client):19    def __init__(20        self,21        *,22        ssl: SSLConfig = DEFAULT_SSL_CONFIG,23        timeout: TimeoutConfig = DEFAULT_TIMEOUT_CONFIG,24        limits: PoolLimits = DEFAULT_POOL_LIMITS,25    ):26        self.ssl = ssl27        self.timeout = timeout28        self.limits = limits29        self.is_closed = False30        self.num_active_connections = 031        self.num_keepalive_connections = 032        self._keepalive_connections = (33            {}34        )  # type: typing.Dict[Origin, typing.List[HTTP11Connection]]35        self._max_connections = ConnectionSemaphore(36            max_connections=self.limits.hard_limit37        )3839    async def send(40        self,41        request: Request,42        *,43        ssl: typing.Optional[SSLConfig] = None,44        timeout: typing.Optional[TimeoutConfig] = None,45    ) -> Response:46        connection = await self.acquire_connection(request.url.origin, timeout=timeout)47        response = await connection.send(request, ssl=ssl, timeout=timeout)48        return response4950    @property51    def num_connections(self) -> int:52        return self.num_active_connections + self.num_keepalive_connections5354    async def acquire_connection(55        self, origin: Origin, timeout: typing.Optional[TimeoutConfig] = None56    ) -> HTTP11Connection:57        try:58            connection = self._keepalive_connections[origin].pop()59            if not self._keepalive_connections[origin]:60                del self._keepalive_connections[origin]61            self.num_keepalive_connections -= 162            self.num_active_connections += 16364        except (KeyError, IndexError):65            if timeout is None:66                pool_timeout = self.timeout.pool_timeout67            else:68                pool_timeout = timeout.pool_timeout6970            try:71                await asyncio.wait_for(self._max_connections.acquire(), pool_timeout)72            except asyncio.TimeoutError:73                raise PoolTimeout()74            connection = HTTP11Connection(75                origin,76                ssl=self.ssl,77                timeout=self.timeout,78                on_release=self.release_connection,79            )80            self.num_active_connections += 18182        return connection8384    async def release_connection(self, connection: HTTP11Connection) -> None:85        if connection.is_closed:86            self._max_connections.release()87            self.num_active_connections -= 188        elif (89            self.limits.soft_limit is not None90            and self.num_connections > self.limits.soft_limit91        ):92            self._max_connections.release()93            self.num_active_connections -= 194            await connection.close()95        else:96            self.num_active_connections -= 197            self.num_keepalive_connections += 198            try:99                self._keepalive_connections[connection.origin].append(connection)100            except KeyError:101                self._keepalive_connections[connection.origin] = [connection]102103    async def close(self) -> None:104        self.is_closed = True105        all_connections = []106        for connections in self._keepalive_connections.values():107            all_connections.extend(list(connections))108        self._keepalive_connections.clear()109        for connection in all_connections:110            await connection.close()111112113class ConnectionSemaphore:114    def __init__(self, max_connections: int = None):115        self.max_connections = max_connections116117    @property118    def semaphore(self) -> typing.Optional[asyncio.BoundedSemaphore]:119        if not hasattr(self, "_semaphore"):120            if self.max_connections is None:121                self._semaphore = None122            else:123                self._semaphore = asyncio.BoundedSemaphore(value=self.max_connections)124        return self._semaphore125126    async def acquire(self) -> None:127        if self.semaphore is not None:128            await self.semaphore.acquire()129130    def release(self) -> None:131        if self.semaphore is not None:132            self.semaphore.release()