Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions python/pythonmonkey/builtin_modules/XMLHttpRequest-internal.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
33 changes: 30 additions & 3 deletions python/pythonmonkey/builtin_modules/XMLHttpRequest.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');

/**
Expand Down Expand Up @@ -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,
Expand All @@ -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;
}

/**
Expand Down Expand Up @@ -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;
Expand Down
50 changes: 50 additions & 0 deletions tests/js/xhr-unref.bash
Original file line number Diff line number Diff line change
@@ -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, [email protected]
# @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" <<EOF
const xhr = new XMLHttpRequest();
xhr.open('GET', 'http://127.0.0.1:${port}/');
xhr.onload = () => 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
Loading