mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
A client that streams its body sends Transfer-Encoding: chunked and no Content-Length: .NET's PostAsJsonAsync, a fetch with a stream body, a Go or Java client, a gateway in front. The proxy read that as no body, and the engine answered "Field required" to a client that had sent one (curl, Node 24 and http.client, 2026-11-30). It is decoded under the ceilings every body has (MAX_BODY_BYTES, the budget of the bodies in flight, BODY_STALL_S), after the key, and every guard reads it as any other. Chunks beside a Content-Length or on HTTP/1.0 are a 400, another coding a 501, and the connection ends there as after every answer, so no byte of it is ever read as a request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
192 lines
8.6 KiB
Python
192 lines
8.6 KiB
Python
"""HTTP/1.0 clients, HEAD, and the methods this port does not take (v6.63).
|
|
|
|
An HTTP/1.0 client reads no chunks (RFC 9112, 6.1), and got their sizes as a part of every answer
|
|
(ab, a device whose client asks for HTTP/1.0). `curl -I` of a route read 501 "Unsupported method", an
|
|
OPTIONS too, in a page of HTML and with no line in the journal (2026-11-30)."""
|
|
import http.server
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
import socket
|
|
import sys
|
|
import threading
|
|
import time
|
|
import unittest
|
|
from pathlib import Path
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
KEY = "the-serving-key-of-this-test"
|
|
EVENTS = [b'data: {"id":"e","choices":[{"index":0,"delta":{"content":"one"}}]}\n\n',
|
|
b'data: {"id":"e","choices":[{"index":0,"delta":{"content":"two"}}]}\n\n', b"data: [DONE]\n\n"]
|
|
MODELS = json.dumps({"object": "list", "data": [{"id": "m", "owned_by": "sglang"}]}).encode()
|
|
ANSWER = json.dumps({"choices": [{"message": {"content": "plain"}}]}).encode()
|
|
|
|
|
|
class Engine(http.server.BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
methods = []
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def send(self, body, ctype="application/json"):
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", ctype)
|
|
self.send_header("Content-Length", str(len(body)))
|
|
self.end_headers()
|
|
self.wfile.write(body)
|
|
|
|
def do_GET(self):
|
|
self.methods.append((self.command, self.path))
|
|
if self.path == "/v1/nothing":
|
|
self.send_error(404)
|
|
return
|
|
self.send(MODELS if self.path == "/v1/models" else b"")
|
|
|
|
def do_POST(self):
|
|
raw = self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
|
if not json.loads(raw).get("stream"):
|
|
self.send(ANSWER)
|
|
return
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/event-stream")
|
|
self.send_header("Transfer-Encoding", "chunked")
|
|
self.end_headers()
|
|
for e in EVENTS:
|
|
time.sleep(0.5 if "slow" in raw.decode() else 0)
|
|
self.wfile.write(b"%x\r\n" % len(e) + e + b"\r\n")
|
|
self.wfile.write(b"0\r\n\r\n")
|
|
|
|
|
|
class Base(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
saved = dict(os.environ)
|
|
cls.addClassCleanup(lambda: (os.environ.clear(), os.environ.update(saved)))
|
|
cls.engine = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Engine)
|
|
cls.engine.daemon_threads = True
|
|
threading.Thread(target=cls.engine.serve_forever, daemon=True).start()
|
|
cls.addClassCleanup(cls.engine.server_close)
|
|
cls.addClassCleanup(cls.engine.shutdown)
|
|
os.environ.update(UPSTREAM=f"http://127.0.0.1:{cls.engine.server_port}", CLIENT_IO_S="5", KEEPALIVE_S="0.2",
|
|
PROMPT_CEILING_TOKENS="0", PROXY_HOLD_UNITS="", QWEN38_UPSTREAM_API_KEY=KEY)
|
|
spec = importlib.util.spec_from_file_location(f"kp_http10_{time.time_ns()}", REPO / "keepalive-proxy.py")
|
|
cls.mod = importlib.util.module_from_spec(spec)
|
|
sys.argv = ["keepalive-proxy.py"]
|
|
spec.loader.exec_module(cls.mod)
|
|
cls.journal = []
|
|
cls.mod.log = cls.journal.append
|
|
cls.mod._SERVED.update(names=("m",), engine="sglang", ts=time.time())
|
|
cls.proxy = cls.mod.Server(("127.0.0.1", 0), cls.mod.H)
|
|
threading.Thread(target=cls.proxy.serve_forever, daemon=True).start()
|
|
cls.addClassCleanup(cls.proxy.server_close)
|
|
cls.addClassCleanup(cls.proxy.shutdown)
|
|
|
|
def setUp(self):
|
|
self.journal.clear()
|
|
Engine.methods.clear()
|
|
self.mod._SAID.clear()
|
|
|
|
def raw(self, request):
|
|
"""(status line, headers, body) of the one answer, read to the connection's end."""
|
|
s = socket.create_connection(("127.0.0.1", self.proxy.server_address[1]), timeout=8)
|
|
self.addCleanup(s.close)
|
|
s.sendall(request)
|
|
got = b""
|
|
while True:
|
|
c = s.recv(65536)
|
|
if not c:
|
|
break
|
|
got += c
|
|
head, _, body = got.partition(b"\r\n\r\n")
|
|
lines = head.decode().split("\r\n")
|
|
return lines[0], {k.lower(): v.strip() for k, _, v in (ln.partition(":") for ln in lines[1:])}, body
|
|
|
|
def ask(self, method, path, version="HTTP/1.1", body=None, key=KEY, more=""):
|
|
auth = f"Authorization: Bearer {key}\r\n" if key else ""
|
|
length = f"Content-Length: {len(body)}\r\nContent-Type: application/json\r\n" if body is not None else ""
|
|
return self.raw(f"{method} {path} {version}\r\nHost: p\r\n{auth}{length}{more}\r\n".encode() + (body or b""))
|
|
|
|
|
|
class AnHttp10ClientReadsNoChunks(Base):
|
|
def test_a_plain_answer(self):
|
|
line, head, body = self.ask("POST", "/v1/chat/completions", "HTTP/1.0", json.dumps({"model": "m"}).encode())
|
|
self.assertIn(" 200 ", line)
|
|
self.assertNotIn("transfer-encoding", head)
|
|
self.assertEqual(body, ANSWER)
|
|
|
|
def test_a_stream(self):
|
|
line, head, body = self.ask("POST", "/v1/chat/completions", "HTTP/1.0",
|
|
json.dumps({"model": "m", "stream": True}).encode())
|
|
self.assertNotIn("transfer-encoding", head)
|
|
self.assertEqual(body, b"".join(EVENTS))
|
|
|
|
def test_a_stream_its_keepalives_open(self):
|
|
_, head, body = self.ask("POST", "/v1/chat/completions", "HTTP/1.0",
|
|
json.dumps({"model": "slow", "stream": True}).encode())
|
|
self.assertNotIn("transfer-encoding", head)
|
|
records = body.split(b"\n\n")
|
|
self.assertTrue(all(r.startswith(b"data: ") for r in records if r), records)
|
|
self.assertTrue(any(b'"id":"keepalive"' in r for r in records), records)
|
|
self.assertEqual([r + b"\n\n" for r in records if r and b"keepalive" not in r], EVENTS)
|
|
|
|
def test_an_http_1_1_client_still_gets_them(self):
|
|
_, head, body = self.ask("POST", "/v1/chat/completions", "HTTP/1.1", json.dumps({"model": "m"}).encode())
|
|
self.assertEqual(head.get("transfer-encoding"), "chunked")
|
|
self.assertTrue(body.endswith(b"0\r\n\r\n"))
|
|
|
|
|
|
class AHeadIsItsGetWithoutTheBody(Base):
|
|
def test_a_route_of_the_engine(self):
|
|
line, head, body = self.ask("HEAD", "/v1/models")
|
|
self.assertIn(" 200 ", line)
|
|
self.assertEqual(body, b"")
|
|
self.assertEqual(head["content-length"], str(len(MODELS)))
|
|
self.assertEqual(Engine.methods, [("GET", "/v1/models")])
|
|
self.assertTrue([ln for ln in self.journal if "HEAD /v1/models ok get" in ln], self.journal)
|
|
|
|
def test_health_is_open_and_the_rest_needs_the_key(self):
|
|
self.assertIn(" 200 ", self.ask("HEAD", "/health", key=None)[0])
|
|
line, _, body = self.ask("HEAD", "/v1/models", key=None)
|
|
self.assertIn(" 401 ", line)
|
|
self.assertEqual(body, b"")
|
|
|
|
def test_the_engine_s_own_refusal(self):
|
|
line, _, body = self.ask("HEAD", "/v1/nothing")
|
|
self.assertIn(" 404 ", line)
|
|
self.assertEqual(body, b"")
|
|
|
|
|
|
class AMethodThisPortDoesNotTake(Base):
|
|
def test_it_is_a_405_in_json_and_a_line_of_the_journal(self):
|
|
for method in ("OPTIONS", "TRACE", "PROPFIND", "get"):
|
|
with self.subTest(method=method):
|
|
self.journal.clear()
|
|
self.mod._SAID.clear()
|
|
line, head, body = self.ask(method, "/v1/chat/completions", key=None)
|
|
self.assertIn(" 405 ", line)
|
|
self.assertEqual(head["content-type"], "application/json")
|
|
self.assertIn("POST", head["allow"])
|
|
self.assertIn(method, json.loads(body)["error"]["message"])
|
|
self.assertEqual(len([ln for ln in self.journal if "REFUSED (405)" in ln]), 1, self.journal)
|
|
self.assertEqual(Engine.methods, [])
|
|
|
|
def test_a_browser_s_preflight_opens_nothing(self):
|
|
line, head, body = self.ask("OPTIONS", "/v1/chat/completions", key=None,
|
|
more="Origin: http://evil.example\r\nAccess-Control-Request-Method: POST\r\n")
|
|
self.assertIn(" 405 ", line)
|
|
self.assertFalse([h for h in head if h.startswith("access-control")], head)
|
|
self.assertIn("CORS", json.loads(body)["error"]["message"])
|
|
|
|
def test_what_the_parser_cannot_read_is_json_too_and_said_once_a_minute(self):
|
|
for _ in range(3):
|
|
line, head, body = self.raw(b"GET /v1/models HTTP/1.1\r\n" + b"".join(b"X-%d: 1\r\n" % i for i in range(120)) + b"\r\n")
|
|
self.assertIn(" 431 ", line)
|
|
self.assertEqual(head["content-type"], "application/json")
|
|
self.assertIn("header", json.loads(body)["error"]["message"])
|
|
self.assertEqual(len([ln for ln in self.journal if "REFUSED (431)" in ln]), 1, self.journal)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|