| 1 |
""" |
| 2 |
Support for streaming http requests in emscripten. |
| 3 |
|
| 4 |
A few caveats - |
| 5 |
|
| 6 |
If your browser (or Node.js) has WebAssembly JavaScript Promise Integration enabled |
| 7 |
https://github.com/WebAssembly/js-promise-integration/blob/main/proposals/js-promise-integration/Overview.md |
| 8 |
*and* you launch pyodide using `pyodide.runPythonAsync`, this will fetch data using the |
| 9 |
JavaScript asynchronous fetch api (wrapped via `pyodide.ffi.call_sync`). In this case |
| 10 |
timeouts and streaming should just work. |
| 11 |
|
| 12 |
Otherwise, it uses a combination of XMLHttpRequest and a web-worker for streaming. |
| 13 |
|
| 14 |
This approach has several caveats: |
| 15 |
|
| 16 |
Firstly, you can't do streaming http in the main UI thread, because atomics.wait isn't allowed. |
| 17 |
Streaming only works if you're running pyodide in a web worker. |
| 18 |
|
| 19 |
Secondly, this uses an extra web worker and SharedArrayBuffer to do the asynchronous fetch |
| 20 |
operation, so it requires that you have crossOriginIsolation enabled, by serving over https |
| 21 |
(or from localhost) with the two headers below set: |
| 22 |
|
| 23 |
Cross-Origin-Opener-Policy: same-origin |
| 24 |
Cross-Origin-Embedder-Policy: require-corp |
| 25 |
|
| 26 |
You can tell if cross origin isolation is successfully enabled by looking at the global crossOriginIsolated variable in |
| 27 |
JavaScript console. If it isn't, streaming requests will fallback to XMLHttpRequest, i.e. getting the whole |
| 28 |
request into a buffer and then returning it. it shows a warning in the JavaScript console in this case. |
| 29 |
|
| 30 |
Finally, the webworker which does the streaming fetch is created on initial import, but will only be started once |
| 31 |
control is returned to javascript. Call `await wait_for_streaming_ready()` to wait for streaming fetch. |
| 32 |
|
| 33 |
NB: in this code, there are a lot of JavaScript objects. They are named js_* |
| 34 |
to make it clear what type of object they are. |
| 35 |
""" |
| 36 |
|
| 37 |
from __future__ import annotations |
| 38 |
|
| 39 |
import io |
| 40 |
import json |
| 41 |
from email.parser import Parser |
| 42 |
from importlib.resources import files |
| 43 |
from typing import TYPE_CHECKING, Any |
| 44 |
|
| 45 |
import js # type: ignore[import-not-found] |
| 46 |
from pyodide.ffi import ( # type: ignore[import-not-found] |
| 47 |
JsArray, |
| 48 |
JsException, |
| 49 |
JsProxy, |
| 50 |
to_js, |
| 51 |
) |
| 52 |
|
| 53 |
if TYPE_CHECKING: |
| 54 |
from typing_extensions import Buffer |
| 55 |
|
| 56 |
from .request import EmscriptenRequest |
| 57 |
from .response import EmscriptenResponse |
| 58 |
|
| 59 |
""" |
| 60 |
There are some headers that trigger unintended CORS preflight requests. |
| 61 |
See also https://github.com/koenvo/pyodide-http/issues/22 |
| 62 |
""" |
| 63 |
HEADERS_TO_IGNORE = ("user-agent",) |
| 64 |
|
| 65 |
SUCCESS_HEADER = -1 |
| 66 |
SUCCESS_EOF = -2 |
| 67 |
ERROR_TIMEOUT = -3 |
| 68 |
ERROR_EXCEPTION = -4 |
| 69 |
|
| 70 |
|
| 71 |
class _RequestError(Exception): |
| 72 |
def __init__( |
| 73 |
self, |
| 74 |
message: str | None = None, |
| 75 |
*, |
| 76 |
request: EmscriptenRequest | None = None, |
| 77 |
response: EmscriptenResponse | None = None, |
| 78 |
): |
| 79 |
self.request = request |
| 80 |
self.response = response |
| 81 |
self.message = message |
| 82 |
super().__init__(self.message) |
| 83 |
|
| 84 |
|
| 85 |
class _StreamingError(_RequestError): |
| 86 |
pass |
| 87 |
|
| 88 |
|
| 89 |
class _TimeoutError(_RequestError): |
| 90 |
pass |
| 91 |
|
| 92 |
|
| 93 |
def _obj_from_dict(dict_val: dict[str, Any]) -> JsProxy: |
| 94 |
return to_js(dict_val, dict_converter=js.Object.fromEntries) |
| 95 |
|
| 96 |
|
| 97 |
class _ReadStream(io.RawIOBase): |
| 98 |
def __init__( |
| 99 |
self, |
| 100 |
int_buffer: JsArray, |
| 101 |
byte_buffer: JsArray, |
| 102 |
timeout: float, |
| 103 |
worker: JsProxy, |
| 104 |
connection_id: int, |
| 105 |
request: EmscriptenRequest, |
| 106 |
): |
| 107 |
self.int_buffer = int_buffer |
| 108 |
self.byte_buffer = byte_buffer |
| 109 |
self.read_pos = 0 |
| 110 |
self.read_len = 0 |
| 111 |
self.connection_id = connection_id |
| 112 |
self.worker = worker |
| 113 |
self.timeout = int(1000 * timeout) if timeout > 0 else None |
| 114 |
self.is_live = True |
| 115 |
self._is_closed = False |
| 116 |
self.request: EmscriptenRequest | None = request |
| 117 |
|
| 118 |
def __del__(self) -> None: |
| 119 |
self.close() |
| 120 |
|
| 121 |
# this is compatible with _base_connection |
| 122 |
def is_closed(self) -> bool: |
| 123 |
return self._is_closed |
| 124 |
|
| 125 |
# for compatibility with RawIOBase |
| 126 |
@property |
| 127 |
def closed(self) -> bool: |
| 128 |
return self.is_closed() |
| 129 |
|
| 130 |
def close(self) -> None: |
| 131 |
if self.is_closed(): |
| 132 |
return |
| 133 |
self.read_len = 0 |
| 134 |
self.read_pos = 0 |
| 135 |
self.int_buffer = None |
| 136 |
self.byte_buffer = None |
| 137 |
self._is_closed = True |
| 138 |
self.request = None |
| 139 |
if self.is_live: |
| 140 |
self.worker.postMessage(_obj_from_dict({"close": self.connection_id})) |
| 141 |
self.is_live = False |
| 142 |
super().close() |
| 143 |
|
| 144 |
def readable(self) -> bool: |
| 145 |
return True |
| 146 |
|
| 147 |
def writable(self) -> bool: |
| 148 |
return False |
| 149 |
|
| 150 |
def seekable(self) -> bool: |
| 151 |
return False |
| 152 |
|
| 153 |
def readinto(self, byte_obj: Buffer) -> int: |
| 154 |
if not self.int_buffer: |
| 155 |
raise _StreamingError( |
| 156 |
"No buffer for stream in _ReadStream.readinto", |
| 157 |
request=self.request, |
| 158 |
response=None, |
| 159 |
) |
| 160 |
if self.read_len == 0: |
| 161 |
# wait for the worker to send something |
| 162 |
js.Atomics.store(self.int_buffer, 0, ERROR_TIMEOUT) |
| 163 |
self.worker.postMessage(_obj_from_dict({"getMore": self.connection_id})) |
| 164 |
if ( |
| 165 |
js.Atomics.wait(self.int_buffer, 0, ERROR_TIMEOUT, self.timeout) |
| 166 |
== "timed-out" |
| 167 |
): |
| 168 |
raise _TimeoutError |
| 169 |
data_len = self.int_buffer[0] |
| 170 |
if data_len > 0: |
| 171 |
self.read_len = data_len |
| 172 |
self.read_pos = 0 |
| 173 |
elif data_len == ERROR_EXCEPTION: |
| 174 |
string_len = self.int_buffer[1] |
| 175 |
# decode the error string |
| 176 |
js_decoder = js.TextDecoder.new() |
| 177 |
json_str = js_decoder.decode(self.byte_buffer.slice(0, string_len)) |
| 178 |
raise _StreamingError( |
| 179 |
f"Exception thrown in fetch: {json_str}", |
| 180 |
request=self.request, |
| 181 |
response=None, |
| 182 |
) |
| 183 |
else: |
| 184 |
# EOF, free the buffers and return zero |
| 185 |
# and free the request |
| 186 |
self.is_live = False |
| 187 |
self.close() |
| 188 |
return 0 |
| 189 |
# copy from int32array to python bytes |
| 190 |
ret_length = min(self.read_len, len(memoryview(byte_obj))) |
| 191 |
subarray = self.byte_buffer.subarray( |
| 192 |
self.read_pos, self.read_pos + ret_length |
| 193 |
).to_py() |
| 194 |
memoryview(byte_obj)[0:ret_length] = subarray |
| 195 |
self.read_len -= ret_length |
| 196 |
self.read_pos += ret_length |
| 197 |
return ret_length |
| 198 |
|
| 199 |
|
| 200 |
class _StreamingFetcher: |
| 201 |
def __init__(self) -> None: |
| 202 |
# make web-worker and data buffer on startup |
| 203 |
self.streaming_ready = False |
| 204 |
streaming_worker_code = ( |
| 205 |
files(__package__) |
| 206 |
.joinpath("emscripten_fetch_worker.js") |
| 207 |
.read_text(encoding="utf-8") |
| 208 |
) |
| 209 |
js_data_blob = js.Blob.new( |
| 210 |
to_js([streaming_worker_code], create_pyproxies=False), |
| 211 |
_obj_from_dict({"type": "application/javascript"}), |
| 212 |
) |
| 213 |
|
| 214 |
def promise_resolver(js_resolve_fn: JsProxy, js_reject_fn: JsProxy) -> None: |
| 215 |
def onMsg(e: JsProxy) -> None: |
| 216 |
self.streaming_ready = True |
| 217 |
js_resolve_fn(e) |
| 218 |
|
| 219 |
def onErr(e: JsProxy) -> None: |
| 220 |
js_reject_fn(e) # Defensive: never happens in ci |
| 221 |
|
| 222 |
self.js_worker.onmessage = onMsg |
| 223 |
self.js_worker.onerror = onErr |
| 224 |
|
| 225 |
js_data_url = js.URL.createObjectURL(js_data_blob) |
| 226 |
self.js_worker = js.globalThis.Worker.new(js_data_url) |
| 227 |
self.js_worker_ready_promise = js.globalThis.Promise.new(promise_resolver) |
| 228 |
|
| 229 |
def send(self, request: EmscriptenRequest) -> EmscriptenResponse: |
| 230 |
headers = { |
| 231 |
k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE |
| 232 |
} |
| 233 |
|
| 234 |
body = request.body |
| 235 |
fetch_data = {"headers": headers, "body": to_js(body), "method": request.method} |
| 236 |
# start the request off in the worker |
| 237 |
timeout = int(1000 * request.timeout) if request.timeout > 0 else None |
| 238 |
js_shared_buffer = js.SharedArrayBuffer.new(1048576) |
| 239 |
js_int_buffer = js.Int32Array.new(js_shared_buffer) |
| 240 |
js_byte_buffer = js.Uint8Array.new(js_shared_buffer, 8) |
| 241 |
|
| 242 |
js.Atomics.store(js_int_buffer, 0, ERROR_TIMEOUT) |
| 243 |
js.Atomics.notify(js_int_buffer, 0) |
| 244 |
js_absolute_url = js.URL.new(request.url, js.location).href |
| 245 |
self.js_worker.postMessage( |
| 246 |
_obj_from_dict( |
| 247 |
{ |
| 248 |
"buffer": js_shared_buffer, |
| 249 |
"url": js_absolute_url, |
| 250 |
"fetchParams": fetch_data, |
| 251 |
} |
| 252 |
) |
| 253 |
) |
| 254 |
# wait for the worker to send something |
| 255 |
js.Atomics.wait(js_int_buffer, 0, ERROR_TIMEOUT, timeout) |
| 256 |
if js_int_buffer[0] == ERROR_TIMEOUT: |
| 257 |
raise _TimeoutError( |
| 258 |
"Timeout connecting to streaming request", |
| 259 |
request=request, |
| 260 |
response=None, |
| 261 |
) |
| 262 |
elif js_int_buffer[0] == SUCCESS_HEADER: |
| 263 |
# got response |
| 264 |
# header length is in second int of intBuffer |
| 265 |
string_len = js_int_buffer[1] |
| 266 |
# decode the rest to a JSON string |
| 267 |
js_decoder = js.TextDecoder.new() |
| 268 |
# this does a copy (the slice) because decode can't work on shared array |
| 269 |
# for some silly reason |
| 270 |
json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) |
| 271 |
# get it as an object |
| 272 |
response_obj = json.loads(json_str) |
| 273 |
return EmscriptenResponse( |
| 274 |
request=request, |
| 275 |
status_code=response_obj["status"], |
| 276 |
headers=response_obj["headers"], |
| 277 |
body=_ReadStream( |
| 278 |
js_int_buffer, |
| 279 |
js_byte_buffer, |
| 280 |
request.timeout, |
| 281 |
self.js_worker, |
| 282 |
response_obj["connectionID"], |
| 283 |
request, |
| 284 |
), |
| 285 |
) |
| 286 |
elif js_int_buffer[0] == ERROR_EXCEPTION: |
| 287 |
string_len = js_int_buffer[1] |
| 288 |
# decode the error string |
| 289 |
js_decoder = js.TextDecoder.new() |
| 290 |
json_str = js_decoder.decode(js_byte_buffer.slice(0, string_len)) |
| 291 |
raise _StreamingError( |
| 292 |
f"Exception thrown in fetch: {json_str}", request=request, response=None |
| 293 |
) |
| 294 |
else: |
| 295 |
raise _StreamingError( |
| 296 |
f"Unknown status from worker in fetch: {js_int_buffer[0]}", |
| 297 |
request=request, |
| 298 |
response=None, |
| 299 |
) |
| 300 |
|
| 301 |
|
| 302 |
class _JSPIReadStream(io.RawIOBase): |
| 303 |
""" |
| 304 |
A read stream that uses pyodide.ffi.run_sync to read from a JavaScript fetch |
| 305 |
response. This requires support for WebAssembly JavaScript Promise Integration |
| 306 |
in the containing browser, and for pyodide to be launched via runPythonAsync. |
| 307 |
|
| 308 |
:param js_read_stream: |
| 309 |
The JavaScript stream reader |
| 310 |
|
| 311 |
:param timeout: |
| 312 |
Timeout in seconds |
| 313 |
|
| 314 |
:param request: |
| 315 |
The request we're handling |
| 316 |
|
| 317 |
:param response: |
| 318 |
The response this stream relates to |
| 319 |
|
| 320 |
:param js_abort_controller: |
| 321 |
A JavaScript AbortController object, used for timeouts |
| 322 |
""" |
| 323 |
|
| 324 |
def __init__( |
| 325 |
self, |
| 326 |
js_read_stream: Any, |
| 327 |
timeout: float, |
| 328 |
request: EmscriptenRequest, |
| 329 |
response: EmscriptenResponse, |
| 330 |
js_abort_controller: Any, # JavaScript AbortController for timeouts |
| 331 |
): |
| 332 |
self.js_read_stream = js_read_stream |
| 333 |
self.timeout = timeout |
| 334 |
self._is_closed = False |
| 335 |
self._is_done = False |
| 336 |
self.request: EmscriptenRequest | None = request |
| 337 |
self.response: EmscriptenResponse | None = response |
| 338 |
self.current_buffer = None |
| 339 |
self.current_buffer_pos = 0 |
| 340 |
self.js_abort_controller = js_abort_controller |
| 341 |
|
| 342 |
def __del__(self) -> None: |
| 343 |
self.close() |
| 344 |
|
| 345 |
# this is compatible with _base_connection |
| 346 |
def is_closed(self) -> bool: |
| 347 |
return self._is_closed |
| 348 |
|
| 349 |
# for compatibility with RawIOBase |
| 350 |
@property |
| 351 |
def closed(self) -> bool: |
| 352 |
return self.is_closed() |
| 353 |
|
| 354 |
def close(self) -> None: |
| 355 |
if self.is_closed(): |
| 356 |
return |
| 357 |
self.read_len = 0 |
| 358 |
self.read_pos = 0 |
| 359 |
self.js_read_stream.cancel() |
| 360 |
self.js_read_stream = None |
| 361 |
self._is_closed = True |
| 362 |
self._is_done = True |
| 363 |
self.request = None |
| 364 |
self.response = None |
| 365 |
super().close() |
| 366 |
|
| 367 |
def readable(self) -> bool: |
| 368 |
return True |
| 369 |
|
| 370 |
def writable(self) -> bool: |
| 371 |
return False |
| 372 |
|
| 373 |
def seekable(self) -> bool: |
| 374 |
return False |
| 375 |
|
| 376 |
def _get_next_buffer(self) -> bool: |
| 377 |
result_js = _run_sync_with_timeout( |
| 378 |
self.js_read_stream.read(), |
| 379 |
self.timeout, |
| 380 |
self.js_abort_controller, |
| 381 |
request=self.request, |
| 382 |
response=self.response, |
| 383 |
) |
| 384 |
if result_js.done: |
| 385 |
self._is_done = True |
| 386 |
return False |
| 387 |
else: |
| 388 |
self.current_buffer = result_js.value.to_py() |
| 389 |
self.current_buffer_pos = 0 |
| 390 |
return True |
| 391 |
|
| 392 |
def readinto(self, byte_obj: Buffer) -> int: |
| 393 |
if self.current_buffer is None: |
| 394 |
if not self._get_next_buffer() or self.current_buffer is None: |
| 395 |
self.close() |
| 396 |
return 0 |
| 397 |
ret_length = min( |
| 398 |
len(byte_obj), len(self.current_buffer) - self.current_buffer_pos |
| 399 |
) |
| 400 |
byte_obj[0:ret_length] = self.current_buffer[ |
| 401 |
self.current_buffer_pos : self.current_buffer_pos + ret_length |
| 402 |
] |
| 403 |
self.current_buffer_pos += ret_length |
| 404 |
if self.current_buffer_pos == len(self.current_buffer): |
| 405 |
self.current_buffer = None |
| 406 |
return ret_length |
| 407 |
|
| 408 |
|
| 409 |
# check if we are in a worker or not |
| 410 |
def is_in_browser_main_thread() -> bool: |
| 411 |
return hasattr(js, "window") and hasattr(js, "self") and js.self == js.window |
| 412 |
|
| 413 |
|
| 414 |
def is_cross_origin_isolated() -> bool: |
| 415 |
return hasattr(js, "crossOriginIsolated") and js.crossOriginIsolated |
| 416 |
|
| 417 |
|
| 418 |
def is_in_node() -> bool: |
| 419 |
return ( |
| 420 |
hasattr(js, "process") |
| 421 |
and hasattr(js.process, "release") |
| 422 |
and hasattr(js.process.release, "name") |
| 423 |
and js.process.release.name == "node" |
| 424 |
) |
| 425 |
|
| 426 |
|
| 427 |
def is_worker_available() -> bool: |
| 428 |
return hasattr(js, "Worker") and hasattr(js, "Blob") |
| 429 |
|
| 430 |
|
| 431 |
_fetcher: _StreamingFetcher | None = None |
| 432 |
|
| 433 |
if is_worker_available() and ( |
| 434 |
(is_cross_origin_isolated() and not is_in_browser_main_thread()) |
| 435 |
and (not is_in_node()) |
| 436 |
): |
| 437 |
_fetcher = _StreamingFetcher() |
| 438 |
else: |
| 439 |
_fetcher = None |
| 440 |
|
| 441 |
|
| 442 |
NODE_JSPI_ERROR = ( |
| 443 |
"urllib3 only works in Node.js with pyodide.runPythonAsync" |
| 444 |
" and requires the flag --experimental-wasm-stack-switching in " |
| 445 |
" versions of node <24." |
| 446 |
) |
| 447 |
|
| 448 |
|
| 449 |
def send_streaming_request(request: EmscriptenRequest) -> EmscriptenResponse | None: |
| 450 |
if has_jspi(): |
| 451 |
return send_jspi_request(request, True) |
| 452 |
elif is_in_node(): |
| 453 |
raise _RequestError( |
| 454 |
message=NODE_JSPI_ERROR, |
| 455 |
request=request, |
| 456 |
response=None, |
| 457 |
) |
| 458 |
|
| 459 |
if _fetcher and streaming_ready(): |
| 460 |
return _fetcher.send(request) |
| 461 |
else: |
| 462 |
_show_streaming_warning() |
| 463 |
return None |
| 464 |
|
| 465 |
|
| 466 |
_SHOWN_TIMEOUT_WARNING = False |
| 467 |
|
| 468 |
|
| 469 |
def _show_timeout_warning() -> None: |
| 470 |
global _SHOWN_TIMEOUT_WARNING |
| 471 |
if not _SHOWN_TIMEOUT_WARNING: |
| 472 |
_SHOWN_TIMEOUT_WARNING = True |
| 473 |
message = "Warning: Timeout is not available on main browser thread" |
| 474 |
js.console.warn(message) |
| 475 |
|
| 476 |
|
| 477 |
_SHOWN_STREAMING_WARNING = False |
| 478 |
|
| 479 |
|
| 480 |
def _show_streaming_warning() -> None: |
| 481 |
global _SHOWN_STREAMING_WARNING |
| 482 |
if not _SHOWN_STREAMING_WARNING: |
| 483 |
_SHOWN_STREAMING_WARNING = True |
| 484 |
message = "Can't stream HTTP requests because: \n" |
| 485 |
if not is_cross_origin_isolated(): |
| 486 |
message += " Page is not cross-origin isolated\n" |
| 487 |
if is_in_browser_main_thread(): |
| 488 |
message += " Python is running in main browser thread\n" |
| 489 |
if not is_worker_available(): |
| 490 |
message += " Worker or Blob classes are not available in this environment." # Defensive: this is always False in browsers that we test in |
| 491 |
if streaming_ready() is False: |
| 492 |
message += """ Streaming fetch worker isn't ready. If you want to be sure that streaming fetch |
| 493 |
is working, you need to call: 'await urllib3.contrib.emscripten.fetch.wait_for_streaming_ready()`""" |
| 494 |
from js import console |
| 495 |
|
| 496 |
console.warn(message) |
| 497 |
|
| 498 |
|
| 499 |
def send_request(request: EmscriptenRequest) -> EmscriptenResponse: |
| 500 |
if has_jspi(): |
| 501 |
return send_jspi_request(request, False) |
| 502 |
elif is_in_node(): |
| 503 |
raise _RequestError( |
| 504 |
message=NODE_JSPI_ERROR, |
| 505 |
request=request, |
| 506 |
response=None, |
| 507 |
) |
| 508 |
try: |
| 509 |
js_xhr = js.XMLHttpRequest.new() |
| 510 |
|
| 511 |
if not is_in_browser_main_thread(): |
| 512 |
js_xhr.responseType = "arraybuffer" |
| 513 |
if request.timeout: |
| 514 |
js_xhr.timeout = int(request.timeout * 1000) |
| 515 |
else: |
| 516 |
js_xhr.overrideMimeType("text/plain; charset=ISO-8859-15") |
| 517 |
if request.timeout: |
| 518 |
# timeout isn't available on the main thread - show a warning in console |
| 519 |
# if it is set |
| 520 |
_show_timeout_warning() |
| 521 |
|
| 522 |
js_xhr.open(request.method, request.url, False) |
| 523 |
for name, value in request.headers.items(): |
| 524 |
if name.lower() not in HEADERS_TO_IGNORE: |
| 525 |
js_xhr.setRequestHeader(name, value) |
| 526 |
|
| 527 |
js_xhr.send(to_js(request.body)) |
| 528 |
|
| 529 |
headers = dict(Parser().parsestr(js_xhr.getAllResponseHeaders())) |
| 530 |
|
| 531 |
if not is_in_browser_main_thread(): |
| 532 |
body = js_xhr.response.to_py().tobytes() |
| 533 |
else: |
| 534 |
body = js_xhr.response.encode("ISO-8859-15") |
| 535 |
return EmscriptenResponse( |
| 536 |
status_code=js_xhr.status, headers=headers, body=body, request=request |
| 537 |
) |
| 538 |
except JsException as err: |
| 539 |
if err.name == "TimeoutError": |
| 540 |
raise _TimeoutError(err.message, request=request) |
| 541 |
elif err.name == "NetworkError": |
| 542 |
raise _RequestError(err.message, request=request) |
| 543 |
else: |
| 544 |
# general http error |
| 545 |
raise _RequestError(err.message, request=request) |
| 546 |
|
| 547 |
|
| 548 |
def send_jspi_request( |
| 549 |
request: EmscriptenRequest, streaming: bool |
| 550 |
) -> EmscriptenResponse: |
| 551 |
""" |
| 552 |
Send a request using WebAssembly JavaScript Promise Integration |
| 553 |
to wrap the asynchronous JavaScript fetch api (experimental). |
| 554 |
|
| 555 |
:param request: |
| 556 |
Request to send |
| 557 |
|
| 558 |
:param streaming: |
| 559 |
Whether to stream the response |
| 560 |
|
| 561 |
:return: The response object |
| 562 |
:rtype: EmscriptenResponse |
| 563 |
""" |
| 564 |
timeout = request.timeout |
| 565 |
js_abort_controller = js.AbortController.new() |
| 566 |
headers = {k: v for k, v in request.headers.items() if k not in HEADERS_TO_IGNORE} |
| 567 |
req_body = request.body |
| 568 |
fetch_data = { |
| 569 |
"headers": headers, |
| 570 |
"body": to_js(req_body), |
| 571 |
"method": request.method, |
| 572 |
"signal": js_abort_controller.signal, |
| 573 |
} |
| 574 |
# Node.js returns the whole response (unlike opaqueredirect in browsers), |
| 575 |
# so urllib3 can set `redirect: manual` to control redirects itself. |
| 576 |
# https://stackoverflow.com/a/78524615 |
| 577 |
if _is_node_js(): |
| 578 |
fetch_data["redirect"] = "manual" |
| 579 |
# Call JavaScript fetch (async api, returns a promise) |
| 580 |
fetcher_promise_js = js.fetch(request.url, _obj_from_dict(fetch_data)) |
| 581 |
# Now suspend WebAssembly until we resolve that promise |
| 582 |
# or time out. |
| 583 |
response_js = _run_sync_with_timeout( |
| 584 |
fetcher_promise_js, |
| 585 |
timeout, |
| 586 |
js_abort_controller, |
| 587 |
request=request, |
| 588 |
response=None, |
| 589 |
) |
| 590 |
headers = {} |
| 591 |
header_iter = response_js.headers.entries() |
| 592 |
while True: |
| 593 |
iter_value_js = header_iter.next() |
| 594 |
if getattr(iter_value_js, "done", False): |
| 595 |
break |
| 596 |
else: |
| 597 |
headers[str(iter_value_js.value[0])] = str(iter_value_js.value[1]) |
| 598 |
status_code = response_js.status |
| 599 |
body: bytes | io.RawIOBase = b"" |
| 600 |
|
| 601 |
response = EmscriptenResponse( |
| 602 |
status_code=status_code, headers=headers, body=b"", request=request |
| 603 |
) |
| 604 |
if streaming: |
| 605 |
# get via inputstream |
| 606 |
if response_js.body is not None: |
| 607 |
# get a reader from the fetch response |
| 608 |
body_stream_js = response_js.body.getReader() |
| 609 |
body = _JSPIReadStream( |
| 610 |
body_stream_js, timeout, request, response, js_abort_controller |
| 611 |
) |
| 612 |
else: |
| 613 |
# get directly via arraybuffer |
| 614 |
# n.b. this is another async JavaScript call. |
| 615 |
body = _run_sync_with_timeout( |
| 616 |
response_js.arrayBuffer(), |
| 617 |
timeout, |
| 618 |
js_abort_controller, |
| 619 |
request=request, |
| 620 |
response=response, |
| 621 |
).to_py() |
| 622 |
response.body = body |
| 623 |
return response |
| 624 |
|
| 625 |
|
| 626 |
def _run_sync_with_timeout( |
| 627 |
promise: Any, |
| 628 |
timeout: float, |
| 629 |
js_abort_controller: Any, |
| 630 |
request: EmscriptenRequest | None, |
| 631 |
response: EmscriptenResponse | None, |
| 632 |
) -> Any: |
| 633 |
""" |
| 634 |
Await a JavaScript promise synchronously with a timeout which is implemented |
| 635 |
via the AbortController |
| 636 |
|
| 637 |
:param promise: |
| 638 |
Javascript promise to await |
| 639 |
|
| 640 |
:param timeout: |
| 641 |
Timeout in seconds |
| 642 |
|
| 643 |
:param js_abort_controller: |
| 644 |
A JavaScript AbortController object, used on timeout |
| 645 |
|
| 646 |
:param request: |
| 647 |
The request being handled |
| 648 |
|
| 649 |
:param response: |
| 650 |
The response being handled (if it exists yet) |
| 651 |
|
| 652 |
:raises _TimeoutError: If the request times out |
| 653 |
:raises _RequestError: If the request raises a JavaScript exception |
| 654 |
|
| 655 |
:return: The result of awaiting the promise. |
| 656 |
""" |
| 657 |
timer_id = None |
| 658 |
if timeout > 0: |
| 659 |
timer_id = js.setTimeout( |
| 660 |
js_abort_controller.abort.bind(js_abort_controller), int(timeout * 1000) |
| 661 |
) |
| 662 |
try: |
| 663 |
from pyodide.ffi import run_sync |
| 664 |
|
| 665 |
# run_sync here uses WebAssembly JavaScript Promise Integration to |
| 666 |
# suspend python until the JavaScript promise resolves. |
| 667 |
return run_sync(promise) |
| 668 |
except JsException as err: |
| 669 |
if err.name == "AbortError": |
| 670 |
raise _TimeoutError( |
| 671 |
message="Request timed out", request=request, response=response |
| 672 |
) |
| 673 |
else: |
| 674 |
raise _RequestError(message=err.message, request=request, response=response) |
| 675 |
finally: |
| 676 |
if timer_id is not None: |
| 677 |
js.clearTimeout(timer_id) |
| 678 |
|
| 679 |
|
| 680 |
def has_jspi() -> bool: |
| 681 |
""" |
| 682 |
Return true if jspi can be used. |
| 683 |
|
| 684 |
This requires both browser support and also WebAssembly |
| 685 |
to be in the correct state - i.e. that the javascript |
| 686 |
call into python was async not sync. |
| 687 |
|
| 688 |
:return: True if jspi can be used. |
| 689 |
:rtype: bool |
| 690 |
""" |
| 691 |
try: |
| 692 |
from pyodide.ffi import can_run_sync, run_sync # noqa: F401 |
| 693 |
|
| 694 |
return bool(can_run_sync()) |
| 695 |
except ImportError: |
| 696 |
return False |
| 697 |
|
| 698 |
|
| 699 |
def _is_node_js() -> bool: |
| 700 |
""" |
| 701 |
Check if we are in Node.js. |
| 702 |
|
| 703 |
:return: True if we are in Node.js. |
| 704 |
:rtype: bool |
| 705 |
""" |
| 706 |
return ( |
| 707 |
hasattr(js, "process") |
| 708 |
and hasattr(js.process, "release") |
| 709 |
# According to the Node.js documentation, the release name is always "node". |
| 710 |
and js.process.release.name == "node" |
| 711 |
) |
| 712 |
|
| 713 |
|
| 714 |
def streaming_ready() -> bool | None: |
| 715 |
if _fetcher: |
| 716 |
return _fetcher.streaming_ready |
| 717 |
else: |
| 718 |
return None # no fetcher, return None to signify that |
| 719 |
|
| 720 |
|
| 721 |
async def wait_for_streaming_ready() -> bool: |
| 722 |
if _fetcher: |
| 723 |
await _fetcher.js_worker_ready_promise |
| 724 |
return True |
| 725 |
else: |
| 726 |
return False |