httpx2-jsfetch-emscripten-forge 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- httpx2_jsfetch_emscripten_forge-0.1.0/LICENSE.md +13 -0
- httpx2_jsfetch_emscripten_forge-0.1.0/PKG-INFO +39 -0
- httpx2_jsfetch_emscripten_forge-0.1.0/README.md +3 -0
- httpx2_jsfetch_emscripten_forge-0.1.0/pyproject.toml +37 -0
- httpx2_jsfetch_emscripten_forge-0.1.0/src/httpx2_jsfetch/__init__.py +375 -0
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright © 2026 to present Pydantic Services Inc. and individual contributors.
|
|
2
|
+
Copyright © 2019, [Encode OSS Ltd](https://www.encode.io/).
|
|
3
|
+
All rights reserved.
|
|
4
|
+
|
|
5
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
6
|
+
|
|
7
|
+
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
8
|
+
|
|
9
|
+
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
10
|
+
|
|
11
|
+
* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
12
|
+
|
|
13
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: httpx2-jsfetch-emscripten-forge
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: httpx2 transports for emscripten-forge.
|
|
5
|
+
Project-URL: Source, https://github.com/davidbrochart/httpx2-jsfetch-emscripten-forge
|
|
6
|
+
Project-URL: Issues, https://github.com/davidbrochart/httpx2-jsfetch-emscripten-forge/issues
|
|
7
|
+
Author-email: Hood Chatham <roberthoodchatham@gmail.com>, David Brochart <david.brochart@gmail.com>
|
|
8
|
+
License: Copyright © 2026 to present Pydantic Services Inc. and individual contributors.
|
|
9
|
+
Copyright © 2019, [Encode OSS Ltd](https://www.encode.io/).
|
|
10
|
+
All rights reserved.
|
|
11
|
+
|
|
12
|
+
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
|
13
|
+
|
|
14
|
+
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
|
15
|
+
|
|
16
|
+
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
|
17
|
+
|
|
18
|
+
* Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
|
19
|
+
|
|
20
|
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
|
21
|
+
License-File: LICENSE.md
|
|
22
|
+
Classifier: Development Status :: 4 - Beta
|
|
23
|
+
Classifier: Environment :: Web Environment
|
|
24
|
+
Classifier: Framework :: AsyncIO
|
|
25
|
+
Classifier: Intended Audience :: Developers
|
|
26
|
+
Classifier: License :: OSI Approved :: BSD License
|
|
27
|
+
Classifier: Operating System :: OS Independent
|
|
28
|
+
Classifier: Programming Language :: Python :: 3
|
|
29
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
30
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
31
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
32
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
33
|
+
Classifier: Typing :: Typed
|
|
34
|
+
Requires-Python: >=3.13
|
|
35
|
+
Description-Content-Type: text/markdown
|
|
36
|
+
|
|
37
|
+
[httpx2](https://github.com/pydantic/httpx2) transports for [emscripten-forge](https://github.com/emscripten-forge/recipes).
|
|
38
|
+
|
|
39
|
+
Originally from [httpx2-jsfetch](https://github.com/hoodmane/httpx2-jsfetch).
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "httpx2-jsfetch-emscripten-forge"
|
|
7
|
+
description = "httpx2 transports for emscripten-forge."
|
|
8
|
+
readme = "README.md"
|
|
9
|
+
version = "0.1.0"
|
|
10
|
+
authors = [
|
|
11
|
+
{ name = "Hood Chatham", email = "roberthoodchatham@gmail.com" },
|
|
12
|
+
{ name = "David Brochart", email = "david.brochart@gmail.com" },
|
|
13
|
+
]
|
|
14
|
+
license = {file = "LICENSE.md"}
|
|
15
|
+
classifiers = [
|
|
16
|
+
"Development Status :: 4 - Beta",
|
|
17
|
+
"Environment :: Web Environment",
|
|
18
|
+
"Framework :: AsyncIO",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"License :: OSI Approved :: BSD License",
|
|
21
|
+
"Operating System :: OS Independent",
|
|
22
|
+
"Programming Language :: Python :: 3",
|
|
23
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
24
|
+
"Programming Language :: Python :: 3.13",
|
|
25
|
+
"Programming Language :: Python :: 3.14",
|
|
26
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
27
|
+
"Typing :: Typed",
|
|
28
|
+
]
|
|
29
|
+
requires-python = ">=3.13"
|
|
30
|
+
|
|
31
|
+
[project.urls]
|
|
32
|
+
Source = "https://github.com/davidbrochart/httpx2-jsfetch-emscripten-forge"
|
|
33
|
+
Issues = "https://github.com/davidbrochart/httpx2-jsfetch-emscripten-forge/issues"
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.wheel]
|
|
36
|
+
ignore-vcs = true
|
|
37
|
+
packages = ["src/httpx2_jsfetch"]
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import email.parser
|
|
4
|
+
import ssl
|
|
5
|
+
import warnings
|
|
6
|
+
from collections.abc import AsyncIterator, Awaitable, Iterable, Iterator
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
from types import TracebackType
|
|
9
|
+
from typing import (
|
|
10
|
+
Any,
|
|
11
|
+
TypeVar,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
from httpx2._config import DEFAULT_LIMITS, Limits
|
|
15
|
+
from httpx2._exceptions import (
|
|
16
|
+
ConnectError,
|
|
17
|
+
ConnectTimeout,
|
|
18
|
+
ReadError,
|
|
19
|
+
ReadTimeout,
|
|
20
|
+
RequestError,
|
|
21
|
+
)
|
|
22
|
+
from httpx2._models import Request, Response
|
|
23
|
+
from httpx2._transports.base import AsyncBaseTransport, BaseTransport
|
|
24
|
+
from httpx2._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream
|
|
25
|
+
from pyjs import JsException, JsValue, js, to_js # type: ignore[import-not-found]
|
|
26
|
+
from typing_extensions import Self
|
|
27
|
+
|
|
28
|
+
T = TypeVar("T", bound="JavascriptFetchTransport")
|
|
29
|
+
A = TypeVar("A", bound="AsyncJavascriptFetchTransport")
|
|
30
|
+
|
|
31
|
+
SOCKET_OPTION = (
|
|
32
|
+
tuple[int, int, int]
|
|
33
|
+
| tuple[int, int, bytes | bytearray]
|
|
34
|
+
| tuple[int, int, None, int]
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
__all__ = ["AsyncJavascriptFetchTransport", "JavascriptFetchTransport"]
|
|
38
|
+
|
|
39
|
+
"""
|
|
40
|
+
There are some headers that trigger unintended CORS preflight requests.
|
|
41
|
+
See also https://github.com/koenvo/pyodide-http/issues/22
|
|
42
|
+
"""
|
|
43
|
+
HEADERS_TO_IGNORE = ("user-agent",)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
# Default values of ignored options.
|
|
47
|
+
# If a different value is passed for any of these is passed we'll warn.
|
|
48
|
+
# trust_env and http1 are not listed here because they don't conflict with the
|
|
49
|
+
# JS-fetch behaviour.
|
|
50
|
+
_IGNORED_OPTION_DEFAULTS: dict[str, Any] = {
|
|
51
|
+
"verify": True,
|
|
52
|
+
"cert": None,
|
|
53
|
+
"http2": False,
|
|
54
|
+
"limits": DEFAULT_LIMITS,
|
|
55
|
+
"proxy": None,
|
|
56
|
+
"uds": None,
|
|
57
|
+
"local_address": None,
|
|
58
|
+
"retries": 0,
|
|
59
|
+
"socket_options": None,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _warn_ignored_options(**kwargs: Any) -> None:
|
|
64
|
+
"""Emit a UserWarning naming each option that is ignored on Emscripten."""
|
|
65
|
+
ignored = [
|
|
66
|
+
name
|
|
67
|
+
for name, value in kwargs.items()
|
|
68
|
+
if name in _IGNORED_OPTION_DEFAULTS and value != _IGNORED_OPTION_DEFAULTS[name]
|
|
69
|
+
]
|
|
70
|
+
if not ignored:
|
|
71
|
+
return
|
|
72
|
+
message = (
|
|
73
|
+
"The following transport option(s) are not supported on Emscripten "
|
|
74
|
+
f"and will be ignored: {', '.join(ignored)}. "
|
|
75
|
+
"Networking is handled by the JavaScript runtime, so connection "
|
|
76
|
+
"pooling, proxies, certificate handling, and low-level socket "
|
|
77
|
+
"configuration cannot be controlled by httpx2."
|
|
78
|
+
)
|
|
79
|
+
warnings.warn(message, stacklevel=3)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@contextmanager
|
|
83
|
+
def _timeout(
|
|
84
|
+
timeout: float,
|
|
85
|
+
abort_controller_js: JsValue,
|
|
86
|
+
TimeoutExceptionType: type[RequestError],
|
|
87
|
+
ErrorExceptionType: type[RequestError],
|
|
88
|
+
) -> Iterator[None]:
|
|
89
|
+
timer_id = None
|
|
90
|
+
if timeout > 0:
|
|
91
|
+
# It looks odd that we have to call bind() here since the JsValue will
|
|
92
|
+
# automatically remember the receiver. But when we pass it back to
|
|
93
|
+
# JavaScript, we unwrap it and forget the receiver.
|
|
94
|
+
abort = abort_controller_js.abort.bind(abort_controller_js)
|
|
95
|
+
timer_id = js.setTimeout(abort, int(timeout * 1000))
|
|
96
|
+
try:
|
|
97
|
+
yield
|
|
98
|
+
except JsException as err:
|
|
99
|
+
if err.name == "AbortError":
|
|
100
|
+
timer_id = None
|
|
101
|
+
raise TimeoutExceptionType(message="Request timed out") from err
|
|
102
|
+
else:
|
|
103
|
+
raise ErrorExceptionType(message=err.message) from err
|
|
104
|
+
finally:
|
|
105
|
+
if timer_id is not None:
|
|
106
|
+
js.clearTimeout(timer_id)
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
async def _run_async_with_timeout(
|
|
110
|
+
promise: Awaitable[JsValue],
|
|
111
|
+
timeout: float,
|
|
112
|
+
abort_controller_js: JsValue,
|
|
113
|
+
TimeoutExceptionType: type[RequestError],
|
|
114
|
+
ErrorExceptionType: type[RequestError],
|
|
115
|
+
) -> JsValue:
|
|
116
|
+
"""await a javascript promise asynchronously with a timeout set via the
|
|
117
|
+
AbortController
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
promise (Awaitable): Javascript promise to await
|
|
121
|
+
timeout (float): Timeout in seconds
|
|
122
|
+
abort_controller_js (Any): A javascript AbortController object, used on timeout
|
|
123
|
+
TimeoutExceptionType (type[Exception]): An exception type to raise on timeout
|
|
124
|
+
ErrorExceptionType (type[Exception]): An exception type to raise on error
|
|
125
|
+
|
|
126
|
+
Raises:
|
|
127
|
+
TimeoutException: If the request times out
|
|
128
|
+
NetworkError: If the request raises a Javascript exception
|
|
129
|
+
|
|
130
|
+
Returns:
|
|
131
|
+
JsValue: The result of awaiting the promise.
|
|
132
|
+
"""
|
|
133
|
+
with _timeout(
|
|
134
|
+
timeout, abort_controller_js, TimeoutExceptionType, ErrorExceptionType
|
|
135
|
+
):
|
|
136
|
+
return await promise
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _compute_timeouts(extensions: dict[str, Any]) -> tuple[float, float]:
|
|
140
|
+
timeout_dict = extensions.get("timeout", {}) or {}
|
|
141
|
+
conn_timeout = timeout_dict.get("connect", 0.0) or 0.0
|
|
142
|
+
read_timeout = timeout_dict.get("read", 0.0) or 0.0
|
|
143
|
+
return (conn_timeout, read_timeout)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def _do_fetch(
|
|
147
|
+
request: Request, request_body: bytes | None, abort_controller_js: Any
|
|
148
|
+
) -> Awaitable[JsValue]:
|
|
149
|
+
headers = {k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE}
|
|
150
|
+
fetch_data = {
|
|
151
|
+
"headers": headers,
|
|
152
|
+
"body": to_js(request_body),
|
|
153
|
+
"method": request.method,
|
|
154
|
+
"signal": abort_controller_js.signal,
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
return js.fetch( # type: ignore[no-any-return]
|
|
158
|
+
request.url,
|
|
159
|
+
to_js(fetch_data),
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
def _js_response_to_python(
|
|
164
|
+
Stream: type[AsyncEmscriptenStream],
|
|
165
|
+
response_js: Any,
|
|
166
|
+
read_timeout: float,
|
|
167
|
+
abort_controller_js: Any,
|
|
168
|
+
) -> Response:
|
|
169
|
+
headers = dict(response_js.headers.entries())
|
|
170
|
+
# fix content-encoding headers because the javascript fetch handles that
|
|
171
|
+
headers["content-encoding"] = "identity"
|
|
172
|
+
status_code = response_js.status
|
|
173
|
+
|
|
174
|
+
# get a reader from the fetch response
|
|
175
|
+
body_stream_js = response_js.body.getReader()
|
|
176
|
+
return Response(
|
|
177
|
+
status_code=status_code,
|
|
178
|
+
headers=headers,
|
|
179
|
+
stream=Stream(body_stream_js, read_timeout, abort_controller_js),
|
|
180
|
+
)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class JavascriptFetchTransport(BaseTransport):
|
|
184
|
+
def __init__(
|
|
185
|
+
self,
|
|
186
|
+
verify: ssl.SSLContext | str | bool = True,
|
|
187
|
+
cert: CertTypes | None = None,
|
|
188
|
+
trust_env: bool = True,
|
|
189
|
+
http1: bool = True,
|
|
190
|
+
http2: bool = False,
|
|
191
|
+
limits: Limits = DEFAULT_LIMITS,
|
|
192
|
+
proxy: ProxyTypes | None = None,
|
|
193
|
+
uds: str | None = None,
|
|
194
|
+
local_address: str | None = None,
|
|
195
|
+
retries: int = 0,
|
|
196
|
+
socket_options: Iterable[SOCKET_OPTION] | None = None,
|
|
197
|
+
) -> None:
|
|
198
|
+
_warn_ignored_options(
|
|
199
|
+
verify=verify,
|
|
200
|
+
cert=cert,
|
|
201
|
+
http2=http2,
|
|
202
|
+
limits=limits,
|
|
203
|
+
proxy=proxy,
|
|
204
|
+
uds=uds,
|
|
205
|
+
local_address=local_address,
|
|
206
|
+
retries=retries,
|
|
207
|
+
socket_options=socket_options,
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
def __enter__(self) -> Self: # Use generics for subclass support.
|
|
211
|
+
return self
|
|
212
|
+
|
|
213
|
+
def __exit__(
|
|
214
|
+
self,
|
|
215
|
+
exc_type: type[BaseException] | None = None,
|
|
216
|
+
exc_value: BaseException | None = None,
|
|
217
|
+
traceback: TracebackType | None = None,
|
|
218
|
+
) -> None:
|
|
219
|
+
pass
|
|
220
|
+
|
|
221
|
+
def handle_request(
|
|
222
|
+
self,
|
|
223
|
+
request: Request,
|
|
224
|
+
) -> Response:
|
|
225
|
+
assert isinstance(request.stream, SyncByteStream)
|
|
226
|
+
return _no_jspi_fallback(request)
|
|
227
|
+
|
|
228
|
+
def close(self) -> None:
|
|
229
|
+
pass
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
class AsyncEmscriptenStream(AsyncByteStream):
|
|
233
|
+
def __init__(
|
|
234
|
+
self,
|
|
235
|
+
response_stream_js: JsValue,
|
|
236
|
+
timeout: float,
|
|
237
|
+
abort_controller_js: JsValue,
|
|
238
|
+
) -> None:
|
|
239
|
+
self._stream_js = response_stream_js
|
|
240
|
+
self.timeout = timeout
|
|
241
|
+
self.abort_controller_js = abort_controller_js
|
|
242
|
+
|
|
243
|
+
async def __aiter__(self) -> AsyncIterator[bytes]:
|
|
244
|
+
while self._stream_js is not None:
|
|
245
|
+
result_js = await _run_async_with_timeout(
|
|
246
|
+
self._stream_js.read(),
|
|
247
|
+
self.timeout,
|
|
248
|
+
self.abort_controller_js,
|
|
249
|
+
ReadTimeout,
|
|
250
|
+
ReadError,
|
|
251
|
+
)
|
|
252
|
+
if result_js.done:
|
|
253
|
+
return
|
|
254
|
+
else:
|
|
255
|
+
yield result_js.value.to_py()
|
|
256
|
+
|
|
257
|
+
async def aclose(self) -> None:
|
|
258
|
+
self._stream_js = None
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
class AsyncJavascriptFetchTransport(AsyncBaseTransport):
|
|
262
|
+
def __init__(
|
|
263
|
+
self,
|
|
264
|
+
verify: ssl.SSLContext | str | bool = True,
|
|
265
|
+
cert: CertTypes | None = None,
|
|
266
|
+
trust_env: bool = True,
|
|
267
|
+
http1: bool = True,
|
|
268
|
+
http2: bool = False,
|
|
269
|
+
limits: Limits = DEFAULT_LIMITS,
|
|
270
|
+
proxy: ProxyTypes | None = None,
|
|
271
|
+
uds: str | None = None,
|
|
272
|
+
local_address: str | None = None,
|
|
273
|
+
retries: int = 0,
|
|
274
|
+
socket_options: Iterable[SOCKET_OPTION] | None = None,
|
|
275
|
+
) -> None:
|
|
276
|
+
_warn_ignored_options(
|
|
277
|
+
verify=verify,
|
|
278
|
+
cert=cert,
|
|
279
|
+
http2=http2,
|
|
280
|
+
limits=limits,
|
|
281
|
+
proxy=proxy,
|
|
282
|
+
uds=uds,
|
|
283
|
+
local_address=local_address,
|
|
284
|
+
retries=retries,
|
|
285
|
+
socket_options=socket_options,
|
|
286
|
+
)
|
|
287
|
+
|
|
288
|
+
async def __aenter__(self) -> Self: # Use generics for subclass support.
|
|
289
|
+
return self
|
|
290
|
+
|
|
291
|
+
async def __aexit__(
|
|
292
|
+
self,
|
|
293
|
+
exc_type: type[BaseException] | None = None,
|
|
294
|
+
exc_value: BaseException | None = None,
|
|
295
|
+
traceback: TracebackType | None = None,
|
|
296
|
+
) -> None:
|
|
297
|
+
pass
|
|
298
|
+
|
|
299
|
+
async def _get_body(self, request: Request) -> bytes | None:
|
|
300
|
+
assert isinstance(request.stream, AsyncByteStream)
|
|
301
|
+
body = b"".join([x async for x in request.stream])
|
|
302
|
+
if not body:
|
|
303
|
+
return None
|
|
304
|
+
return body
|
|
305
|
+
|
|
306
|
+
async def handle_async_request(
|
|
307
|
+
self,
|
|
308
|
+
request: Request,
|
|
309
|
+
) -> Response:
|
|
310
|
+
request_body = await self._get_body(request)
|
|
311
|
+
conn_timeout, read_timeout = _compute_timeouts(request.extensions)
|
|
312
|
+
abort_controller_js = js.AbortController.new()
|
|
313
|
+
fetcher_promise_js = _do_fetch(request, request_body, abort_controller_js)
|
|
314
|
+
response_js = await _run_async_with_timeout(
|
|
315
|
+
fetcher_promise_js,
|
|
316
|
+
conn_timeout,
|
|
317
|
+
abort_controller_js,
|
|
318
|
+
ConnectTimeout,
|
|
319
|
+
ConnectError,
|
|
320
|
+
)
|
|
321
|
+
return _js_response_to_python(
|
|
322
|
+
AsyncEmscriptenStream, response_js, read_timeout, abort_controller_js
|
|
323
|
+
)
|
|
324
|
+
|
|
325
|
+
async def aclose(self) -> None:
|
|
326
|
+
pass
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
# Use XHR to do a sync request without jspi
|
|
330
|
+
def _is_in_browser_main_thread() -> bool:
|
|
331
|
+
return hasattr(js, "window") and hasattr(js, "self") and js.self == js.window
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _no_jspi_fallback(request: Request) -> Response:
|
|
335
|
+
assert isinstance(request.stream, SyncByteStream)
|
|
336
|
+
try:
|
|
337
|
+
js_xhr = js.XMLHttpRequest.new()
|
|
338
|
+
|
|
339
|
+
req_body: bytes | None = b"".join(request.stream)
|
|
340
|
+
if not req_body:
|
|
341
|
+
req_body = None
|
|
342
|
+
_, timeout = _compute_timeouts(request.extensions)
|
|
343
|
+
|
|
344
|
+
# XMLHttpRequest only supports timeouts and proper
|
|
345
|
+
# binary file reading in web-workers
|
|
346
|
+
if not _is_in_browser_main_thread():
|
|
347
|
+
js_xhr.responseType = "arraybuffer"
|
|
348
|
+
if timeout > 0.0:
|
|
349
|
+
js_xhr.timeout = int(timeout * 1000)
|
|
350
|
+
else:
|
|
351
|
+
# this is a nasty hack to be able to read binary files on
|
|
352
|
+
# main browser thread using xmlhttprequest
|
|
353
|
+
js_xhr.overrideMimeType("text/plain; charset=ISO-8859-15")
|
|
354
|
+
|
|
355
|
+
js_xhr.open(request.method, request.url, False)
|
|
356
|
+
|
|
357
|
+
for name, value in request.headers.items():
|
|
358
|
+
if name.lower() not in HEADERS_TO_IGNORE:
|
|
359
|
+
js_xhr.setRequestHeader(name, value)
|
|
360
|
+
|
|
361
|
+
js_xhr.send(to_js(req_body))
|
|
362
|
+
|
|
363
|
+
headers = dict(email.parser.Parser().parsestr(js_xhr.getAllResponseHeaders()))
|
|
364
|
+
|
|
365
|
+
if not _is_in_browser_main_thread():
|
|
366
|
+
body = js_xhr.response.to_py().tobytes()
|
|
367
|
+
else:
|
|
368
|
+
body = js_xhr.response.encode("ISO-8859-15")
|
|
369
|
+
|
|
370
|
+
return Response(status_code=js_xhr.status, headers=headers, content=body)
|
|
371
|
+
except JsException as err:
|
|
372
|
+
if err.name == "TimeoutError":
|
|
373
|
+
raise ConnectTimeout(message="Request timed out") from err
|
|
374
|
+
else:
|
|
375
|
+
raise ConnectError(message=err.message) from err
|