Skip to content
Myr

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

3 files+162 added−41 removed

modified:httpcore/config.py+59 added-3 removed
6 unmodified lines
7 """8 SSL Configuration.9 """1011 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 = verify1920 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 )2627 def __hash__(self) -> int:28 as_tuple = (self.cert, self.verify)29 return hash(as_tuple)3031 def __repr__(self) -> str:32 class_name = self.__class__.__name__33 return f"{class_name}(cert={self.cert}, verify={self.verify})"343536class TimeoutConfig:37 """38 Timeout values.39 """
3 unmodified lines
43 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 None
2 unmodified lines
54 connect_timeout = timeout55 read_timeout = timeout56 pool_timeout = timeout5758 self.timeout = timeout59 self.connect_timeout = connect_timeout60 self.read_timeout = read_timeout61 self.pool_timeout = pool_timeout6263 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 )7071 def __hash__(self) -> int:72 as_tuple = (self.connect_timeout, self.read_timeout, self.pool_timeout)73 return hash(as_tuple)7475 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})"808182class PoolLimits:83 """84 Limits on the number of connections in a connection pool.85 """
1 unmodified line
87 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_limit9596 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 )102103 def __hash__(self) -> int:104 as_tuple = (self.soft_limit, self.hard_limit)105 return hash(as_tuple)106107 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 )112113114DEFAULT_SSL_CONFIG = SSLConfig(cert=None, verify=True)115DEFAULT_TIMEOUT_CONFIG = TimeoutConfig(timeout=5.0)116DEFAULT_POOL_LIMITS = PoolLimits(soft_limit=10, hard_limit=100)117DEFAULT_CA_BUNDLE_PATH = certifi.where()
modified:httpcore/pool.py+45 added-38 removed
16 unmodified lines
17from .connections import Connection18from .datastructures import URL, Request, Response19from .exceptions import PoolTimeout2021ConnectionKey = typing.Tuple[str, str, int] # (scheme, host, port)21ConnectionKey = typing.Tuple[str, str, int, SSLConfig, TimeoutConfig]222324class 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)2829 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()3233 def release(self) -> None:34 if hasattr(self, "semaphore"):35 self.semaphore.release()
12 unmodified lines
48 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 )5859 async def request(60 self,
2 unmodified lines
63 *,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.timeout7475 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 lines
87 def num_connections(self) -> int:88 return self.num_active_connections + self.num_keepalive_connections8990 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 += 1100101 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)113114 return connection115116 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]136129 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 None142143 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 lines
162 context.options |= ssl.OP_NO_COMPRESSION163 context.set_default_verify_paths()164 return context165156 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.verify162163 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 )179180 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)185179 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])191192 return context193194 async def close(self) -> None:
12 unmodified lines
added:tests/test_config.py+58 added
1import httpcore234def test_ssl_repr():5 ssl = httpcore.SSLConfig(verify=False)6 assert repr(ssl) == "SSLConfig(cert=None, verify=False)"789def test_timeout_repr():10 timeout = httpcore.TimeoutConfig(timeout=5.0)11 assert repr(timeout) == "TimeoutConfig(timeout=5.0)"1213 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 )181920def test_limits_repr():21 limits = httpcore.PoolLimits(hard_limit=100)22 assert repr(limits) == "PoolLimits(soft_limit=None, hard_limit=100)"232425def test_ssl_eq():26 ssl = httpcore.SSLConfig(verify=False)27 assert ssl == httpcore.SSLConfig(verify=False)282930def test_timeout_eq():31 timeout = httpcore.TimeoutConfig(timeout=5.0)32 assert timeout == httpcore.TimeoutConfig(timeout=5.0)333435def test_limits_eq():36 limits = httpcore.PoolLimits(hard_limit=100)37 assert limits == httpcore.PoolLimits(hard_limit=100)383940def test_ssl_hash():41 cache = {}42 ssl = httpcore.SSLConfig(verify=False)43 cache[ssl] = "example"44 assert cache[httpcore.SSLConfig(verify=False)] == "example"454647def 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"525354def 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"