diff --git a/python/pythonmonkey/builtin_modules/XMLHttpRequest-internal.py b/python/pythonmonkey/builtin_modules/XMLHttpRequest-internal.py index ca716d88..a39e3755 100644 --- a/python/pythonmonkey/builtin_modules/XMLHttpRequest-internal.py +++ b/python/pythonmonkey/builtin_modules/XMLHttpRequest-internal.py @@ -135,6 +135,26 @@ def decodeStr(data: bytes, encoding='utf-8'): # XXX: Remove this once we get pr return str(data, encoding=encoding) +def requestUnref(*args): + """ + Run `request()` as an asyncio task that the program does not wait for (pm.wait() does not count it). + The last argument is a callback for the exception the request raises, if any; the others are + `request()`'s arguments. + """ + *requestArgs, onError = args + task = asyncio.get_running_loop().create_task(request(*requestArgs)) + pendingUnrefTasks.add(task) # asyncio keeps only weak references to tasks + + def done(task): + pendingUnrefTasks.discard(task) + if not task.cancelled() and task.exception() is not None: + onError(task.exception()) + task.add_done_callback(done) + + +pendingUnrefTasks = set() + # Module exports exports['request'] = request # type: ignore +exports['requestUnref'] = requestUnref # type: ignore exports['decodeStr'] = decodeStr # type: ignore diff --git a/python/pythonmonkey/builtin_modules/XMLHttpRequest.js b/python/pythonmonkey/builtin_modules/XMLHttpRequest.js index 3cbacfc1..ac6c55b5 100644 --- a/python/pythonmonkey/builtin_modules/XMLHttpRequest.js +++ b/python/pythonmonkey/builtin_modules/XMLHttpRequest.js @@ -12,7 +12,7 @@ const { EventTarget, Event } = require('event-target'); const { DOMException } = require('dom-exception'); const { URL, URLSearchParams } = require('url'); -const { request, decodeStr } = require('XMLHttpRequest-internal'); +const { request, requestUnref, decodeStr } = require('XMLHttpRequest-internal'); const debug = globalThis.python.eval('__import__("pythonmonkey").bootstrap.require')('debug'); /** @@ -412,7 +412,7 @@ class XMLHttpRequest extends XMLHttpRequestEventTarget this.#debug('xhr:headers')('headers=' + Object.entries(this.#requestHeaders)); // send() step 6 - request( + const requestArgs = [ this.#requestMethod, this.#requestURL.toString(), this.#requestHeaders, @@ -426,7 +426,33 @@ class XMLHttpRequest extends XMLHttpRequestEventTarget () => (this.#timedOutFlag = true), // onTimeoutError () => (this.#response = null /* network error */), // onNetworkError this.#debug.bind(this), - ).catch((e) => this.#handleErrors(e)); + ]; + if (this.#unrefFlag) + requestUnref(...requestArgs, (e) => this.#handleErrors(e)); + else + request(...requestArgs).catch((e) => this.#handleErrors(e)); + } + + /** + * Non-standard, like Node.js's socket.unref(): requests sent after this call do not keep the + * program running (pm.wait() and pmjs do not wait for them). + * @returns {XMLHttpRequest} this + */ + unref() + { + this.#unrefFlag = true; + return this; + } + + /** + * Non-standard, undoes unref(): requests sent after this call keep the program running until + * they complete. + * @returns {XMLHttpRequest} this + */ + ref() + { + this.#unrefFlag = false; + return this; } /** @@ -674,6 +700,7 @@ class XMLHttpRequest extends XMLHttpRequestEventTarget #uploadObject = new XMLHttpRequestUpload(); #state = XMLHttpRequest.UNSENT; // One of unsent, opened, headers received, loading, and done; initially unsent. #sendFlag = false; // A flag, initially unset. + #unrefFlag = false; // Non-standard: set by unref(), requests are not waited for #crossOriginCredentials = false; // A boolean, initially false. /** @type {Method} */ #requestMethod = null; diff --git a/tests/js/xhr-unref.bash b/tests/js/xhr-unref.bash new file mode 100755 index 00000000..3319a3a4 --- /dev/null +++ b/tests/js/xhr-unref.bash @@ -0,0 +1,50 @@ +#! /bin/bash +# +# @file xhr-unref.bash +# A program whose only pending work is an unref()'d XMLHttpRequest exits without +# waiting for the response; a ref()'d one is waited for. +# @author Wes Garland, wes@distributive.network +# @date Nov 2026 +# +# timeout: 30 + +panic() +{ + echo "FAIL: $*" >&2 + exit 2 +} + +tmpdir="$(mktemp -d)" +trap 'kill ${serverPid} 2>/dev/null; rm -rf "${tmpdir}"' EXIT + +# A server that answers each request after 5 seconds +python3 -c ' +import http.server, sys, time +class Slow(http.server.BaseHTTPRequestHandler): + def do_GET(self): + time.sleep(5) + self.send_response(200); self.end_headers(); self.wfile.write(b"late") + def log_message(self, *args): pass +server = http.server.HTTPServer(("127.0.0.1", 0), Slow) +print(server.server_address[1], flush=True) +server.serve_forever() +' > "${tmpdir}/port" & +serverPid=$! +while [ ! -s "${tmpdir}/port" ]; do sleep 0.1; done +port="$(cat "${tmpdir}/port")" + +cat > "${tmpdir}/unref.js" < console.log('response', xhr.responseText); +xhr.unref().send(); +EOF +start=$(date +%s) +output="$("${PMJS:-pmjs}" "${tmpdir}/unref.js" 2>&1)" || panic "unref program failed: ${output}" +[ $(( $(date +%s) - start )) -lt 4 ] || panic "the unref()'d request was waited for" +echo "${output}" | grep -q response && panic "the unref()'d request's response arrived: ${output}" + +sed -e 's/xhr.unref().send()/xhr.unref().ref().send()/' "${tmpdir}/unref.js" > "${tmpdir}/ref.js" +output="$("${PMJS:-pmjs}" "${tmpdir}/ref.js" 2>&1)" || panic "ref program failed: ${output}" +echo "${output}" | grep -q 'response late' || panic "the ref()'d request was not waited for: ${output}" +echo PASS