Merge pull request #9 from encode/allow_per_request_timeout_and_ssl
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Allow per-request timeout/ssl config
authored by Tom Christie · committed by GitHub · parents 74c9048, 42c0e06 · Browse files · 3 files·+162 added−41 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
3 files+162 added−41 removed
- tests:+58 added−0 removed
- other:+104 added−41 removed
Provenance
- Commit
df84cde- Tree
135dc8e- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent 1
74c9048- Parent 2
42c0e06
3 files changed+162 added−41 removed
modified:httpcore/config.py+59 added-3 removed
6 unmodified lines7 """8 SSL Configuration.9 """10 11- def __init__(self, *, cert: typing.Optional[str], verify: typing.Union[str, bool]):11+ def __init__(12+ self,13+ *,14+ cert: typing.Union[None, str, typing.Tuple[str, str]] = None,15+ verify: typing.Union[str, bool] = True,16+ ):17 self.cert = cert18 self.verify = verify19 20+ def __eq__(self, other: typing.Any) -> bool:21+ return (22+ isinstance(other, self.__class__)23+ and self.cert == other.cert24+ and self.verify == other.verify25+ )26 27+ def __hash__(self) -> int:28+ as_tuple = (self.cert, self.verify)29+ return hash(as_tuple)30+31+ def __repr__(self) -> str:32+ class_name = self.__class__.__name__33+ return f"{class_name}(cert={self.cert}, verify={self.verify})"34+35+36 class TimeoutConfig:37 """38 Timeout values.39 """3 unmodified lines43 timeout: float = None,44 *,45 connect_timeout: float = None,46 read_timeout: float = None,27- pool_timeout: float = None47+ pool_timeout: float = None,48 ):49 if timeout is not None:50 # Specified as a single timeout value51 assert connect_timeout is None2 unmodified lines54 connect_timeout = timeout55 read_timeout = timeout56 pool_timeout = timeout57 58+ self.timeout = timeout59 self.connect_timeout = connect_timeout60 self.read_timeout = read_timeout61 self.pool_timeout = pool_timeout62 63+ def __eq__(self, other: typing.Any) -> bool:64+ return (65+ isinstance(other, self.__class__)66+ and self.connect_timeout == other.connect_timeout67+ and self.read_timeout == other.read_timeout68+ and self.pool_timeout == other.pool_timeout69+ )70 71+ def __hash__(self) -> int:72+ as_tuple = (self.connect_timeout, self.read_timeout, self.pool_timeout)73+ return hash(as_tuple)74+75+ def __repr__(self) -> str:76+ class_name = self.__class__.__name__77+ if self.timeout is not None:78+ return f"{class_name}(timeout={self.timeout})"79+ return f"{class_name}(connect_timeout={self.connect_timeout}, read_timeout={self.read_timeout}, pool_timeout={self.pool_timeout})"80+81+82 class PoolLimits:83 """84 Limits on the number of connections in a connection pool.85 """1 unmodified line87 def __init__(88 self,89 *,90 soft_limit: typing.Optional[int] = None,52- hard_limit: typing.Optional[int] = None91+ hard_limit: typing.Optional[int] = None,92 ):93 self.soft_limit = soft_limit94 self.hard_limit = hard_limit95 96+ def __eq__(self, other: typing.Any) -> bool:97+ return (98+ isinstance(other, self.__class__)99+ and self.soft_limit == other.soft_limit100+ and self.hard_limit == other.hard_limit101+ )102 103+ def __hash__(self) -> int:104+ as_tuple = (self.soft_limit, self.hard_limit)105+ return hash(as_tuple)106+107+ def __repr__(self) -> str:108+ class_name = self.__class__.__name__109+ return (110+ f"{class_name}(soft_limit={self.soft_limit}, hard_limit={self.hard_limit})"111+ )112+113+114 DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)115 DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)116 DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)117 DEFAULT_CA_BUNDLE_PATH = certifi.where()modified:httpcore/pool.py+45 added-38 removed
16 unmodified lines17 from .connections import Connection18 from .datastructures import URL, Request, Response19 from .exceptions import PoolTimeout20 21-ConnectionKey = typing.Tuple[str, str, int] # (scheme, host, port)21+ConnectionKey = typing.Tuple[str, str, int, SSLConfig, TimeoutConfig]22 23 24 class ConnectionSemaphore:25- def __init__(self, max_connections: int = None, timeout: float = None):26- self.timeout = timeout25+ def __init__(self, max_connections: int = None):26 if max_connections is not None:27 self.semaphore = asyncio.BoundedSemaphore(value=max_connections)28 29 async def acquire(self) -> None:30 if hasattr(self, "semaphore"):32- try:33- await asyncio.wait_for(self.semaphore.acquire(), self.timeout)34- except asyncio.TimeoutError:35- raise PoolTimeout()31+ await self.semaphore.acquire()32 33 def release(self) -> None:34 if hasattr(self, "semaphore"):35 self.semaphore.release()12 unmodified lines48 self.limits = limits49 self.is_closed = False50 self.num_active_connections = 051 self.num_keepalive_connections = 056- self._connections = (52+ self._keepalive_connections = (53 {}54 ) # type: typing.Dict[ConnectionKey, typing.List[Connection]]59- self._connection_semaphore = ConnectionSemaphore(60- max_connections=self.limits.hard_limit, timeout=self.timeout.pool_timeout55+ self._max_connections = ConnectionSemaphore(56+ max_connections=self.limits.hard_limit57 )58 59 async def request(60 self,2 unmodified lines63 *,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.timeout74+75 parsed_url = URL(url)76 request = Request(method, parsed_url, headers=headers, body=body)74- ssl_context = await self.get_ssl_context(parsed_url)75- connection = await self.acquire_connection(parsed_url, ssl=ssl_context)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()5 unmodified lines87 def num_connections(self) -> int:88 return self.num_active_connections + self.num_keepalive_connections89 90 async def acquire_connection(89- self, url: URL, *, ssl: typing.Optional[ssl.SSLContext] = None91+ self, url: URL, ssl: SSLConfig, timeout: TimeoutConfig92 ) -> Connection:91- key = (url.scheme, url.hostname, url.port)93+ key = (url.scheme, url.hostname, url.port, ssl, timeout)94 try:93- connection = self._connections[key].pop()94- if not self._connections[key]:95- del self._connections[key]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 += 1100 101 except (KeyError, IndexError):100- await self._connection_semaphore.acquire()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)102- connection = Connection(timeout=self.timeout, on_release=release)110+ connection = Connection(timeout=timeout, on_release=release)111 self.num_active_connections += 1104- await connection.open(url.hostname, url.port, ssl=ssl)112+ await connection.open(url.hostname, url.port, ssl=ssl_context)113 114 return connection115 116 async def release_connection(117 self, connection: Connection, key: ConnectionKey118 ) -> None:119 if connection.is_closed:112- self._connection_semaphore.release()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 ):118- self._connection_semaphore.release()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:125- self._connections[key].append(connection)133+ self._keepalive_connections[key].append(connection)134 except KeyError:127- self._connections[key] = [connection]135+ self._keepalive_connections[key] = [connection]136 129- async def get_ssl_context(self, url: URL) -> typing.Optional[ssl.SSLContext]:137+ async def get_ssl_context(138+ self, url: URL, config: SSLConfig139+ ) -> typing.Optional[ssl.SSLContext]:140 if not url.is_secure:141 return None142 143 if not hasattr(self, "ssl_context"):134- if not self.ssl_config.verify: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()13 unmodified lines162 context.options |= ssl.OP_NO_COMPRESSION163 context.set_default_verify_paths()164 return context165 156- def get_ssl_context_verify(self) -> ssl.SSLContext:166+ def get_ssl_context_verify(self, config: SSLConfig) -> ssl.SSLContext:167 """168 Return an SSL context for verified connections.169 """160- cert = self.ssl_config.cert161- verify = self.ssl_config.verify162-163- if isinstance(verify, bool):170+ if isinstance(config.verify, bool):171 ca_bundle_path = DEFAULT_CA_BUNDLE_PATH165- elif os.path.exists(verify):166- ca_bundle_path = verify172+ 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, "170- "invalid path: {}".format(verify)177+ "invalid path: {}".format(config.verify)178 )179 180 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)185 179- if cert is not None:180- if isinstance(cert, str):181- context.load_cert_chain(certfile=cert)186+ if config.cert is not None:187+ if isinstance(config.cert, str):188+ context.load_cert_chain(certfile=config.cert)189 else:183- context.load_cert_chain(certfile=cert[0], keyfile=cert[1])190+ context.load_cert_chain(certfile=config.cert[0], keyfile=config.cert[1])191 192 return context193 194 async def close(self) -> None:12 unmodified linesadded:tests/test_config.py+58 added
1+import httpcore2+3+4+def test_ssl_repr():5+ ssl = httpcore.SSLConfig(verify=False)6+ assert repr(ssl) == "SSLConfig(cert=None, verify=False)"7+8+9+def test_timeout_repr():10+ timeout = httpcore.TimeoutConfig(timeout=5.0)11+ assert repr(timeout) == "TimeoutConfig(timeout=5.0)"12+13+ timeout = httpcore.TimeoutConfig(read_timeout=5.0)14+ assert (15+ repr(timeout)16+ == "TimeoutConfig(connect_timeout=None, read_timeout=5.0, pool_timeout=None)"17+ )18+19+20+def test_limits_repr():21+ limits = httpcore.PoolLimits(hard_limit=100)22+ assert repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100)"23+24+25+def test_ssl_eq():26+ ssl = httpcore.SSLConfig(verify=False)27+ assert ssl == httpcore.SSLConfig(verify=False)28+29+30+def test_timeout_eq():31+ timeout = httpcore.TimeoutConfig(timeout=5.0)32+ assert timeout == httpcore.TimeoutConfig(timeout=5.0)33+34+35+def test_limits_eq():36+ limits = httpcore.PoolLimits(hard_limit=100)37+ assert limits == httpcore.PoolLimits(hard_limit=100)38+39+40+def test_ssl_hash():41+ cache = {}42+ ssl = httpcore.SSLConfig(verify=False)43+ cache[ssl] = "example"44+ assert cache[httpcore.SSLConfig(verify=False)] == "example"45+46+47+def test_timeout_hash():48+ cache = {}49+ timeout = httpcore.TimeoutConfig(timeout=5.0)50+ cache[timeout] = "example"51+ assert cache[httpcore.TimeoutConfig(timeout=5.0)] == "example"52+53+54+def test_limits_hash():55+ cache = {}56+ limits = httpcore.PoolLimits(hard_limit=100)57+ cache[limits] = "example"58+ assert cache[httpcore.PoolLimits(hard_limit=100)] == "example"