Skip to content
Myr

Merge pull request #17 from encode/close-keepalive-connections

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Close outstanding connections on pool.close()

authored by Tom Christie · committed by GitHub · parents 0c20fba, 4ed3a8a · Browse files · 7 files+40 added−66 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+40 added−66 removed

  • other:+40 added−66 removed

7 files+40 added−66 removed

modified:httpcore/__init__.py+2 added-2 removed
1from .config import PoolLimits, SSLConfig, TimeoutConfig2from .connectionpool import ConnectionPool3from .datastructures import URL, Origin, Request, Response4from .exceptions import (5 BadResponse,5 ConnectTimeout,6 PoolTimeout,7 ProtocolError,8 ReadTimeout,9 ResponseClosed,10 StreamConsumed,11 Timeout,12)13from .http11 import HTTP11Connection14from .sync import SyncClient, SyncConnectionPool1516__version__ = "0.2.0"16__version__ = "0.2.1"
deleted:httpcore/compat.py-52 removed
1import asyncio23if hasattr(asyncio, "run"):4 asyncio_run = asyncio.run56else: # pragma: nocover78 def asyncio_run(main, *, debug=False): # type: ignore9 if asyncio._get_running_loop() is not None:10 raise RuntimeError(11 "asyncio.run() cannot be called from a running event loop"12 )1314 if not asyncio.iscoroutine(main):15 raise ValueError("a coroutine was expected, got {!r}".format(main))1617 loop = asyncio.new_event_loop()18 try:19 asyncio.set_event_loop(loop)20 loop.set_debug(debug)21 return loop.run_until_complete(main)22 finally:23 try:24 _cancel_all_tasks(loop)25 loop.run_until_complete(loop.shutdown_asyncgens())26 finally:27 asyncio.set_event_loop(None)28 loop.close()2930 def _cancel_all_tasks(loop): # type: ignore31 to_cancel = asyncio.all_tasks(loop)32 if not to_cancel:33 return3435 for task in to_cancel:36 task.cancel()3738 loop.run_until_complete(39 tasks.gather(*to_cancel, loop=loop, return_exceptions=True)40 )4142 for task in to_cancel:43 if task.cancelled():44 continue45 if task.exception() is not None:46 loop.call_exception_handler(47 {48 "message": "unhandled exception during asyncio.run() shutdown",49 "exception": task.exception(),50 "task": task,51 }52 )
modified:httpcore/connectionpool.py+7 added-1 removed
8 unmodified lines
9 PoolLimits,10 SSLConfig,11 TimeoutConfig,12)13from .http11 import HTTP11Connection13from .datastructures import Client, Origin, Request, Response14from .exceptions import PoolTimeout15from .http11 import HTTP11Connection161718class ConnectionPool(Client):19 def __init__(
81 unmodified lines
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):
18 unmodified lines
modified:httpcore/exceptions.py+2 added-2 removed
20 unmodified lines
21 Timeout while waiting to acquire a connection from the pool.22 """232425class BadResponse(Exception):25class ProtocolError(Exception):26 """27 A malformed HTTP response.27 Malformed HTTP.28 """293031class StreamConsumed(Exception):
11 unmodified lines
modified:httpcore/sync.py+10 added-8 removed
1import asyncio2import typing3from types import TracebackType44from .compat import asyncio_run5from .config import SSLConfig, TimeoutConfig6from .connectionpool import ConnectionPool7from .datastructures import URL, Client, Response8910class SyncResponse:11 def __init__(self, response: Response):11 def __init__(self, response: Response, loop: asyncio.AbstractEventLoop):12 self._response = response13 self._loop = loop1415 @property16 def status_code(self) -> int:17 return self._response.status_code
10 unmodified lines
28 def body(self) -> bytes:29 return self._response.body3031 def read(self) -> bytes:31 return asyncio_run(self._response.read())32 return self._loop.run_until_complete(self._response.read())3334 def stream(self) -> typing.Iterator[bytes]:35 inner = self._response.stream()36 while True:37 try:37 yield asyncio_run(inner.__anext__())38 yield self._loop.run_until_complete(inner.__anext__())39 except StopAsyncIteration as exc:40 break4142 def close(self) -> None:42 return asyncio_run(self._response.close())43 return self._loop.run_until_complete(self._response.close())444546class SyncClient:47 def __init__(self, client: Client):48 self._client = client49 self._loop = asyncio.new_event_loop()5051 def request(52 self,53 method: str,
4 unmodified lines
58 ssl: typing.Optional[SSLConfig] = None,59 timeout: typing.Optional[TimeoutConfig] = None,60 stream: bool = False,61 ) -> SyncResponse:60 response = asyncio_run(62 response = self._loop.run_until_complete(63 self._client.request(64 method,65 url,66 headers=headers,
2 unmodified lines
69 timeout=timeout,70 stream=stream,71 )72 )71 return SyncResponse(response)73 return SyncResponse(response, self._loop)7475 def close(self) -> None:74 asyncio_run(self._client.close())76 self._loop.run_until_complete(self._client.close())7778 def __enter__(self) -> "SyncClient":79 return self80
12 unmodified lines
added:.travis.yml+19 added
modified:requirements.txt-1 removed
6 unmodified lines
78# Testing9autoflake10black11codecov11isort12mypy13pytest14pytest-asyncio
2 unmodified lines