#!/usr/bin/env python3 """A server whose answer is complete at a chosen moment, and large. python3 scripts/late_answer_server.py [port] [seconds] [body-bytes] [delay-ms ...] Every request is answered at once with the headers of a `body-bytes` long answer and all of it but the last byte. The last byte follows `delay-ms` after the request arrived -- the first request gets the first delay, the second the second, and the last delay is used for all further ones. A delay of 0 means "never": the connection is held until the server stops, which is how to measure a client's own time-out. Why (QuickDataTask.swift:158-185): the wallet's HTTP bridge lets a cancel wait for a response callback that has already started. wallet-core cancels a request when its time-out fires; the callback copies the body twice (quickjs-libc.c handle_http_resp: malloc + memcpy), which for a small answer takes microseconds -- one nightly walk in 785 met the two at once, on a bank long-poll answered in the instant it was cancelled. With a few hundred megabytes the copy takes a tenth of a second, and an answer completed that much before the time-out is being delivered when the cancel arrives. Log (arrival and last byte, with milliseconds): /tmp/late-answer.log. `LATE_BIND` sets the address to listen on (default 127.0.0.1). """ from __future__ import annotations import datetime import os import socket import sys import threading import time LOG = "/tmp/late-answer.log" def log(msg: str) -> None: stamp = datetime.datetime.now().strftime("%H:%M:%S.%f")[:-3] with open(LOG, "a") as f: f.write(f"{stamp} {msg}\n") def serve(conn: socket.socket, nbytes: int, delay_ms: int, deadline: float) -> None: try: conn.settimeout(10) req = b"" while b"\r\n\r\n" not in req and len(req) < 65536: chunk = conn.recv(4096) if not chunk: break req += chunk arrived = time.monotonic() first = req.split(b"\r\n", 1)[0].decode("latin-1", "replace") log(f"request: {first}; {nbytes} bytes, last byte " + (f"after {delay_ms} ms" if delay_ms else "never")) conn.settimeout(None) conn.sendall(b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n" + f"Content-Length: {nbytes}\r\nConnection: close\r\n\r\n".encode()) # A JSON string, so that what is delivered is at least well-formed. left = nbytes - 1 conn.sendall(b'"') left -= 1 block = b"x" * (1 << 20) while left > 0: n = min(left, len(block)) conn.sendall(block[:n]) left -= n log(f"all but the last byte sent after {int((time.monotonic() - arrived) * 1000)} ms") if delay_ms: wait = arrived + delay_ms / 1000.0 - time.monotonic() if wait > 0: time.sleep(wait) conn.sendall(b'"') log(f"last byte sent {int((time.monotonic() - arrived) * 1000)} ms after the request") time.sleep(2.0) else: while time.monotonic() < deadline: time.sleep(0.5) except OSError as e: log(f"connection ended: {e}") finally: try: conn.close() except OSError: pass def main() -> int: port = int(sys.argv[1]) if len(sys.argv) > 1 else 8124 seconds = float(sys.argv[2]) if len(sys.argv) > 2 else 240.0 nbytes = int(sys.argv[3]) if len(sys.argv) > 3 else 64 delays = [int(a) for a in sys.argv[4:]] or [0] bind = os.environ.get("LATE_BIND", "127.0.0.1") srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind((bind, port)) srv.listen(8) srv.settimeout(1.0) deadline = time.monotonic() + seconds log(f"listening on {bind}:{port} for {int(seconds)} s; body {nbytes}; delays {delays}") served = 0 while time.monotonic() < deadline: try: conn, _ = srv.accept() except socket.timeout: continue delay = delays[min(served, len(delays) - 1)] served += 1 threading.Thread(target=serve, args=(conn, nbytes, delay, deadline), daemon=True).start() srv.close() log("stopped") return 0 if __name__ == "__main__": raise SystemExit(main())