Debian Codegraph @

src/anthropic/_vendor/httpx_aiohttp/transport.py

raw
1 # Vendored from httpx-aiohttp v0.2.0 (BSD-3-Clause), src/httpx_aiohttp/httpx2/transport.py.
2 # Copyright (c) 2025, Karen Petrosyan. Licence text and provenance: LICENSE and
3 # NOTICE.md in this directory.
4 # The code below is verbatim; only this header was added, by Anthropic PBC (2026).
5 # Do not edit by hand; re-copy from upstream to update.
6 from __future__ import annotations
7
8 import contextlib
9 import ssl
10 import typing
11 import typing as t
12 from importlib import metadata
13 from logging import warning
14
15 import aiohttp
16 import httpx2 as httpx
17 from aiohttp import BasicAuth, ClientTimeout
18 from aiohttp.client import ClientResponse, ClientSession
19
20 AIOHTTP_EXC_MAP = {
21 aiohttp.ServerTimeoutError: httpx.TimeoutException,
22 aiohttp.SocketTimeoutError: httpx.ReadTimeout,
23 aiohttp.ClientConnectionError: httpx.ConnectTimeout,
24 aiohttp.ClientConnectorError: httpx.ConnectError,
25 aiohttp.ClientPayloadError: httpx.ReadError,
26 aiohttp.ClientProxyConnectionError: httpx.ProxyError,
27 aiohttp.ClientHttpProxyError: httpx.ProxyError,
28 }
29
30 if metadata.version("aiohttp") >= "3.10.0":
31 AIOHTTP_EXC_MAP.update(
32 {
33 aiohttp.client_exceptions.NonHttpUrlClientError: httpx.UnsupportedProtocol, # type: ignore[reportAttributeAccessIssue]
34 aiohttp.client_exceptions.InvalidUrlClientError: httpx.UnsupportedProtocol, # type: ignore[reportAttributeAccessIssue]
35 }
36 )
37
38 SOCKET_OPTION = t.Union[
39 t.Tuple[int, int, int],
40 t.Tuple[int, int, t.Union[bytes, bytearray]],
41 t.Tuple[int, int, None, int],
42 ]
43
44
45 @contextlib.contextmanager
46 def map_aiohttp_exceptions() -> typing.Iterator[None]:
47 try:
48 yield
49 except Exception as exc:
50 mapped_exc = None
51
52 for from_exc, to_exc in AIOHTTP_EXC_MAP.items():
53 if not isinstance(exc, from_exc): # type: ignore
54 continue
55 if mapped_exc is None or issubclass(to_exc, mapped_exc):
56 mapped_exc = to_exc
57
58 if mapped_exc is None: # pragma: no cover
59 raise
60
61 message = str(exc)
62 raise mapped_exc(message) from exc
63
64
65 class AiohttpResponseStream(httpx.AsyncByteStream):
66 CHUNK_SIZE = 1024 * 16
67
68 def __init__(self, aiohttp_response: ClientResponse) -> None:
69 self._aiohttp_response = aiohttp_response
70
71 async def __aiter__(self) -> typing.AsyncIterator[bytes]:
72 with map_aiohttp_exceptions():
73 async for chunk in self._aiohttp_response.content.iter_chunked(self.CHUNK_SIZE):
74 yield chunk
75
76 async def aclose(self) -> None:
77 with map_aiohttp_exceptions():
78 await self._aiohttp_response.__aexit__(None, None, None)
79
80
81 class AiohttpTransport(httpx.AsyncBaseTransport):
82 def __init__(
83 self,
84 verify: ssl.SSLContext | str | bool = True,
85 cert: t.Union[str, t.Tuple[str, str], t.Tuple[str, str, str], None] = None,
86 trust_env: bool = True,
87 http1: bool = True,
88 http2: bool = False,
89 limits: httpx.Limits = httpx.Limits(max_connections=100, max_keepalive_connections=20),
90 proxy: httpx.Proxy | None = None,
91 uds: str | None = None,
92 local_address: str | None = None,
93 retries: int = 0,
94 socket_options: typing.Iterable[SOCKET_OPTION] | None = None,
95 client: ClientSession | t.Callable[[], ClientSession] | None = None,
96 # Additional keyword arguments for future compatibility
97 # If httpx decides to add one, we won't break the API
98 **kwargs: t.Dict[str, t.Any],
99 ) -> None:
100 if http2:
101 if not http1:
102 raise httpx.UnsupportedProtocol("HTTP/2 is not supported by aiohttp transport, use HTTP/1.1 instead.")
103 warning("HTTP/2 is not supported by aiohttp transport, using HTTP/1.1 instead.")
104
105 ssl_context = httpx.create_ssl_context(
106 verify=verify,
107 cert=cert,
108 trust_env=trust_env,
109 )
110
111 self.ssl_context = ssl_context
112 self.proxy = proxy
113 self.limits = limits
114 self.retries = retries
115 self.socket_options = socket_options or []
116 self.uds = uds
117 self.local_address = local_address
118
119 self.client = client
120
121 def get_client(self) -> ClientSession:
122 if callable(self.client):
123 return self.client()
124 elif isinstance(self.client, ClientSession):
125 return self.client
126 else:
127 limit_kwarg = (
128 {
129 "limit": self.limits.max_connections,
130 }
131 if self.limits.max_connections is not None
132 else {}
133 )
134 if self.uds:
135 connector = aiohttp.UnixConnector(
136 path=self.uds,
137 keepalive_timeout=self.limits.keepalive_expiry,
138 **limit_kwarg, # type: ignore
139 )
140 else:
141 connector = aiohttp.TCPConnector(
142 keepalive_timeout=self.limits.keepalive_expiry,
143 ssl=self.ssl_context,
144 local_addr=(self.local_address, 0) if self.local_address else None,
145 **limit_kwarg, # type: ignore
146 )
147 return ClientSession(connector=connector)
148
149 async def handle_async_request(
150 self,
151 request: httpx.Request,
152 ) -> httpx.Response:
153 if not isinstance(self.client, ClientSession):
154 self.client = self.get_client()
155
156 timeout = request.extensions.get("timeout", {})
157 sni_hostname = request.extensions.get("sni_hostname")
158
159 with map_aiohttp_exceptions():
160 data: t.Union[bytes, httpx.AsyncByteStream, None]
161 try:
162 data = request.content
163 if data == b"":
164 data = None
165
166 except httpx.RequestNotRead:
167 data = request.stream # type: ignore
168 request.headers.pop("transfer-encoding", None) # handled by aiohttp
169
170 response = await self.client.request(
171 method=request.method,
172 url=str(request.url) if request.url else "https://127.0.0.1:8000/",
173 headers=request.headers,
174 data=data,
175 allow_redirects=False,
176 auto_decompress=False,
177 compress=False,
178 timeout=ClientTimeout(
179 sock_connect=timeout.get("connect"),
180 sock_read=timeout.get("read"),
181 connect=timeout.get("pool"),
182 ),
183 server_hostname=sni_hostname,
184 proxy=str(self.proxy.url) if self.proxy else None,
185 proxy_auth=BasicAuth(self.proxy.auth[0], self.proxy.auth[1])
186 if self.proxy and self.proxy.auth
187 else None,
188 proxy_headers=self.proxy.headers if self.proxy else None,
189 ).__aenter__()
190
191 extensions = {"http_version": b"HTTP/1.1"}
192
193 if response.reason:
194 extensions["reason_phrase"] = response.reason.encode()
195
196 return httpx.Response(
197 status_code=response.status,
198 headers=response.raw_headers,
199 stream=AiohttpResponseStream(response),
200 request=request,
201 extensions=extensions,
202 )
203
204 async def aclose(self) -> None:
205 if isinstance(self.client, ClientSession):
206 await self.client.close()