diff --git a/speech-server.py b/speech-server.py index f488bad1..e5290afd 100644 --- a/speech-server.py +++ b/speech-server.py @@ -26,6 +26,7 @@ import io import json import re import shutil +import socket import subprocess import sys import tempfile @@ -245,14 +246,35 @@ def make_handler(tts, asr_url, default_voice, asr_name, tts_name="kokoro-82m", a pass def _send(self, code, body, ctype, extra=None): + unread = self.command == "POST" and not self._read_whole self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(body))) for k, v in (extra or {}).items(): self.send_header(k, v) + if unread: + # what is left of the body would be read as the next request of this connection + self.send_header("Connection", "close") self.end_headers() self.wfile.write(body) log(f"{self.command} {self.path} {code} {len(body)}B {time.time() - self._t0:.2f}s\n") + if unread: + self._linger() + + def _linger(self, idle_s=2.0, total_s=10.0): + """After an answer that leaves a body unread: end our side, then read and drop what its client + still sends, for a while. Closed at once, the socket answers it with a reset, and the reset + takes the answer back: a client past the cap, still sending, met a broken pipe (2026-11-30).""" + self.close_connection = True + try: + self.wfile.flush() + self.connection.shutdown(socket.SHUT_WR) + self.connection.settimeout(idle_s) + end = time.monotonic() + total_s + while time.monotonic() < end and self.connection.recv(65536): + pass + except OSError: + pass def _json(self, code, obj): self._send(code, json.dumps(obj, ensure_ascii=False).encode(), "application/json") @@ -263,15 +285,43 @@ def make_handler(tts, asr_url, default_voice, asr_name, tts_name="kokoro-82m", a def _body(self, cap): """The body, b"" without one, or None when it is over cap or its length is not a length (a negative one would read until the client hangs up).""" + if self.headers.get("Transfer-Encoding") is not None: + return self._chunks(cap) try: n = int(self.headers.get("Content-Length") or 0) except ValueError: n = -1 if n > cap or n < 0: - self.close_connection = True return None + self._read_whole = True return self.rfile.read(n) if n else b"" + def _chunks(self, cap): + """A body sent in chunks, whole, or None when it is over cap or framed wrong (with a length + beside them, in another coding). It was read as no body at all, "'input' must be a non-empty + string" to a client that had sent one, and the connection was lost after (2026-11-30).""" + coding = self.headers.get("Transfer-Encoding", "").strip().lower() + if coding != "chunked" or self.headers.get("Content-Length") is not None: + return None + out = bytearray() + while True: + size = self.rfile.readline(1025).split(b";", 1)[0].strip() + if not re.fullmatch(rb"[0-9A-Fa-f]{1,15}", size): + return None + n = int(size, 16) + if not n: + break + if len(out) + n > cap: + return None + out += self.rfile.read(n) + if self.rfile.read(2) != b"\r\n": + return None + for _ in range(100): # its trailers, up to the empty line + if self.rfile.readline(1025) in (b"\r\n", b"\n", b""): + self._read_whole = True + return bytes(out) + return None + def do_GET(self): self._t0 = time.time() path = self.path.split("?", 1)[0] @@ -296,6 +346,7 @@ def make_handler(tts, asr_url, default_voice, asr_name, tts_name="kokoro-82m", a def do_POST(self): self._t0 = time.time() + self._read_whole = False path = self.path.split("?", 1)[0] if path == "/v1/audio/speech": return self._speech() diff --git a/tests/test_speech_server.py b/tests/test_speech_server.py index 151e316d..7c5701e1 100644 --- a/tests/test_speech_server.py +++ b/tests/test_speech_server.py @@ -7,9 +7,12 @@ handler on a free port with a fake voice that returns known samples and a fake l that answers the way the real one does, the model's "language French" prefix included, and records what it was sent. No model, no numpy, no network. """ +import http.client import importlib.util import io import json +import socket +import re import math import pathlib import subprocess @@ -239,6 +242,67 @@ class Routes(unittest.TestCase): f"Content-Length: {length}\r\n\r\n".encode()) self.assertIn(b" 413 ", s.recv(4096).split(b"\r\n")[0] + b" ") + def raw(self, *requests): + """What the server sends back to these bytes, on one connection, to its end.""" + with socket.create_connection(("127.0.0.1", self.front.server_address[1]), timeout=5) as s: + for r in requests: + try: + s.sendall(r) + except OSError: + break + got = b"" + try: + while True: + c = s.recv(65536) + if not c: + return got + got += c + except OSError as e: + return got + f" [{type(e).__name__}]".encode() + + def test_a_body_left_unread_is_no_next_request(self): + """A route it refuses kept its body on the connection, and the request after it read it: "Bad request + syntax", to the second call of an SDK whose first was wrong (2026-11-30).""" + body = json.dumps({"x": "y" * 500}).encode() + ask = b"POST /v1/audio/translations HTTP/1.1\r\nHost: x\r\nContent-Length: %d\r\n\r\n" % len(body) + body + good = b"GET /v1/models HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n" + got = self.raw(ask + good) + self.assertTrue(got.startswith(b"HTTP/1.1 404 "), got[:80]) + self.assertIn(b"Connection: close", got) + self.assertEqual(len(re.findall(rb"HTTP/1\.1 \d{3} ", got)), 1, got) + self.assertNotIn(b"Bad request", got) + + def test_a_connection_whose_bodies_are_read_serves_them_all(self): + body = json.dumps({"input": "hi"}).encode() + ask = b"POST /v1/audio/speech HTTP/1.1\r\nHost: x\r\nContent-Length: %d\r\n\r\n" % len(body) + body + got = self.raw(ask, ask, b"GET /v1/models HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n") + self.assertEqual(re.findall(rb"HTTP/1\.1 (\d{3}) ", got), [b"200"] * 3) + + def test_a_client_past_the_cap_reads_its_413(self): + """One that sends its body before it reads, as they do, met a broken pipe on the way (2026-11-30).""" + for _ in range(5): + c = http.client.HTTPConnection("127.0.0.1", self.front.server_address[1], timeout=5) + try: + c.request("POST", "/v1/audio/speech", b"a" * 8_000_000) + r = c.getresponse() + self.assertEqual(r.status, 413) + self.assertIn(b"over 65536 bytes", r.read()) + finally: + c.close() + + def test_a_body_sent_in_chunks_is_read(self): + head = b"POST /v1/audio/speech HTTP/1.1\r\nHost: x\r\nTransfer-Encoding: chunked\r\n\r\n" + body = json.dumps({"input": "hi", "voice": "af_heart"}).encode() + sent = b"".join(b"%x\r\n" % len(p) + p + b"\r\n" for p in (body[:5], body[5:])) + b"0\r\n\r\n" + got = self.raw(head + sent, b"GET /v1/models HTTP/1.1\r\nHost: x\r\nConnection: close\r\n\r\n") + self.assertEqual(re.findall(rb"HTTP/1\.1 (\d{3}) ", got), [b"200", b"200"], got[:200]) + self.assertEqual(len(self.tts.calls), 1) + for bad in (head + b"zz\r\n", head + b"5\r\n" + body + b"0\r\n\r\n", head + b"ffffffff\r\n", + head.replace(b"chunked", b"gzip") + sent, head.replace(b"\r\n\r\n", b"\r\nContent-Length: 3\r\n\r\n") + sent): + got = self.raw(bad, b"GET /v1/models HTTP/1.1\r\nHost: x\r\n\r\n") + self.assertEqual(re.findall(rb"HTTP/1\.1 (\d{3}) ", got), [b"413"], bad[:90]) + self.assertEqual(len(self.tts.calls), 1) + # ── transcriptions ──────────────────────────────────────────────────────── def test_the_models_prefix_is_taken_off(self): code, _, body = self.call("/v1/audio/transcriptions", *reversed(form({"language": "fr"})))