response.read() returns as soon as the body is complete, but the handler thread records ai.release() after that (and http.client closes the socket before it), so asserting on ai.calls right away could catch a missing or a stray entry -- and a stray could land in the next test after its setUp cleared the list. FakeAi now tracks in-flight claims and request()/tearDown wait for them (settle()).
332 lines
15 KiB
Python
332 lines
15 KiB
Python
import http.client
|
|
import json
|
|
import socket
|
|
import threading
|
|
import time
|
|
import unittest
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from types import SimpleNamespace
|
|
from unittest.mock import patch
|
|
|
|
from kurgan.ai.service import CLIENT_GONE, RouteError
|
|
from kurgan.web import proxy
|
|
from kurgan.web.server import WebServer
|
|
|
|
|
|
def free_port() -> int:
|
|
with socket.socket() as s:
|
|
s.bind(("127.0.0.1", 0))
|
|
return s.getsockname()[1]
|
|
|
|
|
|
class Upstream:
|
|
"""A stand-in LLM server: records each request; /stream sends one event, waits, then another."""
|
|
|
|
def __init__(self):
|
|
self.requests = []
|
|
self.release_stream = threading.Event()
|
|
self.release_slow = threading.Event()
|
|
upstream = self
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def log_message(self, *args):
|
|
pass
|
|
|
|
def _any(self):
|
|
length = int(self.headers.get("Content-Length", "0"))
|
|
body = self.rfile.read(length) if length else b""
|
|
upstream.requests.append({"method": self.command, "path": self.path,
|
|
"headers": dict(self.headers.items()), "body": body})
|
|
if self.path.endswith("/stream"):
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/event-stream")
|
|
self.end_headers()
|
|
self.wfile.write(b"data: one\n\n")
|
|
self.wfile.flush()
|
|
upstream.release_stream.wait(5)
|
|
self.wfile.write(b"data: two\n\n")
|
|
return
|
|
if self.path.endswith("/slow"): # a queued request: nothing until the server gets to it
|
|
upstream.release_slow.wait(10)
|
|
if self.path.endswith("/moved"):
|
|
self.send_response(302)
|
|
self.send_header("Location", f"http://127.0.0.1:{upstream.port}{upstream.prefix}/elsewhere")
|
|
self.send_header("Content-Length", "0")
|
|
self.end_headers()
|
|
return
|
|
data = json.dumps({"path": self.path}).encode()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
|
|
do_GET = do_POST = do_DELETE = do_HEAD = _any
|
|
|
|
self.prefix = ""
|
|
self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
|
|
self.httpd.daemon_threads = True
|
|
self.httpd.handle_error = lambda request, address: None # a reply to a dropped request fails; expected
|
|
self.port = self.httpd.server_address[1]
|
|
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
|
|
|
|
def close(self):
|
|
self.release_stream.set()
|
|
self.release_slow.set()
|
|
self.httpd.shutdown()
|
|
self.httpd.server_close()
|
|
|
|
|
|
class FakeBackend:
|
|
def __init__(self, key, port, prefix, model):
|
|
self.key, self.label, self.port, self.prefix, self.model = key, key.capitalize(), port, prefix, model
|
|
|
|
def model_ids(self):
|
|
return [self.model]
|
|
|
|
def proxy_headers(self):
|
|
return {"Authorization": "Bearer sk-local"} if self.key == "llama" else {}
|
|
|
|
|
|
class FakeAi:
|
|
def __init__(self, backends):
|
|
self.slots = {b.key: SimpleNamespace(backend=b) for b in backends}
|
|
self.up = {b.key: True for b in backends}
|
|
self.calls = []
|
|
self.pending = 0 # claims without a matching release: handler threads still working
|
|
self.error = None
|
|
self.wait_for_client = False # act like a claim waiting for the other server
|
|
|
|
def running(self, key):
|
|
return self.up[key]
|
|
|
|
def claim(self, key, gone=None):
|
|
self.calls.append(("claim", key))
|
|
if self.error is not None:
|
|
raise self.error
|
|
deadline = time.monotonic() + 10
|
|
while self.wait_for_client and time.monotonic() < deadline:
|
|
if gone():
|
|
raise RouteError("while waiting for Strata to finish", CLIENT_GONE)
|
|
time.sleep(0.05)
|
|
self.pending += 1
|
|
return self.slots[key].backend
|
|
|
|
def release(self, key):
|
|
self.pending -= 1
|
|
self.calls.append(("release", key))
|
|
|
|
|
|
class FakeApp:
|
|
def __init__(self, ai):
|
|
self.ai = ai
|
|
|
|
def state(self):
|
|
return {"ok": True}
|
|
|
|
|
|
class ProxyTest(unittest.TestCase):
|
|
@classmethod
|
|
def setUpClass(cls):
|
|
cls.upstream = Upstream()
|
|
cls.upstream.prefix = "/llama"
|
|
cls.llama = FakeBackend("llama", cls.upstream.port, "/llama", "qwen")
|
|
cls.strata = FakeBackend("strata", cls.upstream.port, "", "orca")
|
|
cls.ai = FakeAi([cls.strata, cls.llama])
|
|
cls.port = free_port()
|
|
cls.server = WebServer(FakeApp(cls.ai), cls.port)
|
|
cls.server.start()
|
|
|
|
@classmethod
|
|
def tearDownClass(cls):
|
|
cls.server.close()
|
|
cls.upstream.close()
|
|
|
|
def setUp(self):
|
|
self.upstream.requests.clear()
|
|
self.ai.calls.clear()
|
|
self.ai.pending = 0
|
|
self.ai.up = {"strata": True, "llama": True}
|
|
self.ai.error = None
|
|
self.ai.wait_for_client = False
|
|
self.llama.port = self.upstream.port
|
|
self.upstream.release_slow.clear()
|
|
|
|
def tearDown(self):
|
|
self.settle() # no handler thread may still append to ai.calls for the next test
|
|
|
|
def settle(self, timeout=5):
|
|
"""Wait until every claimed request has been released.
|
|
|
|
The proxy's handler thread records release() after the client already has its reply
|
|
(and http.client closes the connection before that), so assertions on ai.calls must
|
|
wait for the bookkeeping instead of racing it.
|
|
"""
|
|
deadline = time.monotonic() + timeout
|
|
while self.ai.pending > 0 and time.monotonic() < deadline:
|
|
time.sleep(0.01)
|
|
self.assertEqual(self.ai.pending, 0, f"unfinished claims: {self.ai.calls}")
|
|
|
|
def request(self, method, path, body=None, headers=None, chunked=False):
|
|
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
|
|
try:
|
|
base = {"Host": f"127.0.0.1:{self.port}", **(headers or {})}
|
|
connection.request(method, path, body=body, headers=base, encode_chunked=chunked)
|
|
response = connection.getresponse()
|
|
data = response.read()
|
|
self.settle()
|
|
return response.status, dict(response.getheaders()), data
|
|
finally:
|
|
connection.close()
|
|
|
|
def test_a_request_is_relayed_under_the_server_s_own_path(self):
|
|
body = json.dumps({"model": "qwen", "messages": []}).encode()
|
|
status, _, raw = self.request("POST", "/llama/v1/chat/completions?x=1", body,
|
|
{"Content-Type": "application/json", "Authorization": "Bearer whatever",
|
|
"Origin": f"http://127.0.0.1:{self.port}"})
|
|
self.assertEqual(status, 200)
|
|
self.assertEqual(json.loads(raw), {"path": "/llama/v1/chat/completions?x=1"})
|
|
seen = self.upstream.requests[0]
|
|
self.assertEqual((seen["method"], seen["body"]), ("POST", body))
|
|
self.assertEqual(seen["headers"]["Host"], f"127.0.0.1:{self.upstream.port}")
|
|
self.assertEqual(seen["headers"]["Authorization"], "Bearer sk-local") # the server's key, whatever was sent
|
|
self.assertNotIn("Origin", seen["headers"]) # our own page: the server sees a plain local client
|
|
self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")])
|
|
|
|
self.assertEqual(json.loads(self.request("GET", "/strata/")[2]), {"path": "/"}) # Strata serves from the root
|
|
self.assertNotIn("Authorization", self.upstream.requests[-1]["headers"])
|
|
self.assertEqual(json.loads(self.request("DELETE", "/strata/v1/x")[2]), {"path": "/v1/x"})
|
|
|
|
def test_a_chunked_request_body_is_passed_on_whole(self):
|
|
status, _, _ = self.request("POST", "/strata/v1/completions", iter([b'{"prompt":', b'"hi"}']),
|
|
{"Content-Type": "application/json"}, chunked=True)
|
|
self.assertEqual(status, 200)
|
|
seen = self.upstream.requests[0]
|
|
self.assertEqual((seen["body"], seen["headers"]["Content-Length"]), (b'{"prompt":"hi"}', "15"))
|
|
|
|
def test_bare_route_redirects_and_redirects_are_mapped_back(self):
|
|
status, headers, _ = self.request("GET", "/llama")
|
|
self.assertEqual((status, headers["Location"]), (308, "/llama/"))
|
|
self.assertEqual(self.ai.calls, [])
|
|
status, headers, _ = self.request("GET", "/llama/moved")
|
|
self.assertEqual((status, headers["Location"]), (302, "/llama/elsewhere"))
|
|
|
|
def test_other_sites_are_refused_before_anything_starts(self):
|
|
refused = ({"Origin": "https://attacker.example"}, {"Origin": "null"},
|
|
{"Sec-Fetch-Site": "cross-site", "Sec-Fetch-Dest": "image"},
|
|
{"Host": "attacker.example"})
|
|
for headers in refused:
|
|
with self.subTest(headers=headers):
|
|
status, _, raw = self.request("POST", "/llama/v1/chat/completions", b"{}", headers)
|
|
self.assertEqual(status, 403)
|
|
self.assertIn("error", json.loads(raw))
|
|
self.assertEqual((self.ai.calls, self.upstream.requests), ([], []))
|
|
# Following a link from another site to the chat page is fine.
|
|
status, _, _ = self.request("GET", "/llama/", headers={"Sec-Fetch-Site": "cross-site",
|
|
"Sec-Fetch-Dest": "document"})
|
|
self.assertEqual(status, 200)
|
|
|
|
def test_model_list_is_answered_here_while_the_server_is_stopped(self):
|
|
self.ai.up["llama"] = False
|
|
status, _, raw = self.request("GET", "/llama/v1/models")
|
|
self.assertEqual(status, 200)
|
|
self.assertEqual([m["id"] for m in json.loads(raw)["data"]], ["qwen"])
|
|
self.assertEqual(json.loads(self.request("GET", "/llama/v1/models/qwen")[2])["id"], "qwen")
|
|
self.assertEqual(self.request("GET", "/llama/v1/models/other")[0], 404)
|
|
self.assertEqual((self.ai.calls, self.upstream.requests), ([], []))
|
|
self.ai.up["llama"] = True # running: the server answers for itself
|
|
self.assertEqual(json.loads(self.request("GET", "/llama/v1/models")[2]), {"path": "/llama/v1/models"})
|
|
|
|
def test_errors_are_reported_openai_style(self):
|
|
self.ai.error = RouteError("Strata is still busy with another request", 503)
|
|
status, _, raw = self.request("POST", "/llama/v1/chat/completions", b"{}")
|
|
self.assertEqual((status, json.loads(raw)["error"]["message"]), (503, "Strata is still busy with another request"))
|
|
self.assertEqual(self.ai.calls, [("claim", "llama")]) # a failed claim releases itself
|
|
|
|
self.ai.error = None
|
|
self.ai.calls.clear()
|
|
self.llama.port = free_port() # nothing listening
|
|
status, _, raw = self.request("POST", "/llama/v1/chat/completions", b"{}")
|
|
self.assertEqual(status, 502)
|
|
self.assertIn("isn't answering", json.loads(raw)["error"]["message"])
|
|
self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")])
|
|
|
|
with patch.object(proxy, "MAX_BODY", 10):
|
|
self.assertEqual(self.request("POST", "/llama/v1/chat/completions", b"x" * 11)[0], 413)
|
|
|
|
def test_replies_are_streamed_as_they_are_generated(self):
|
|
self.upstream.release_stream.clear()
|
|
connection = http.client.HTTPConnection("127.0.0.1", self.port, timeout=10)
|
|
try:
|
|
connection.request("POST", "/llama/v1/stream", b"{}", {"Host": f"127.0.0.1:{self.port}"})
|
|
response = connection.getresponse()
|
|
self.assertEqual(response.getheader("Content-Type"), "text/event-stream")
|
|
self.assertEqual(response.read1(1024), b"data: one\n\n") # before the server sends the rest
|
|
self.upstream.release_stream.set()
|
|
self.assertEqual(response.read(), b"data: two\n\n")
|
|
finally:
|
|
connection.close()
|
|
self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")])
|
|
|
|
def hang_up_after_sending(self, path):
|
|
"""Send a request, then close the connection without reading the reply."""
|
|
sock = socket.create_connection(("127.0.0.1", self.port), timeout=5)
|
|
sock.sendall(f"POST {path} HTTP/1.1\r\nHost: 127.0.0.1:{self.port}\r\nContent-Type: application/json\r\n"
|
|
f"Content-Length: 2\r\n\r\n{{}}".encode())
|
|
time.sleep(0.3)
|
|
sock.close()
|
|
|
|
def wait_for_log(self, logs, text):
|
|
deadline = time.monotonic() + 5
|
|
while time.monotonic() < deadline and not any(text in line for line in logs.output):
|
|
time.sleep(0.05)
|
|
return [line for line in logs.output if text in line]
|
|
|
|
def test_a_client_that_hangs_up_while_queued_is_noticed_and_the_server_told(self):
|
|
with self.assertLogs("kurgan.web", "INFO") as logs:
|
|
self.hang_up_after_sending("/llama/v1/slow")
|
|
lines = self.wait_for_log(logs, "gave up")
|
|
self.assertEqual(len(lines), 1)
|
|
self.assertRegex(lines[0], r"POST /llama/v1/slow: the client gave up after [01] s, before Llama started its reply")
|
|
self.assertEqual(self.ai.calls, [("claim", "llama"), ("release", "llama")]) # before the server answered
|
|
self.assertFalse(any("ERROR" in line for line in logs.output))
|
|
|
|
def test_a_client_that_hangs_up_while_waiting_for_its_server_gives_up_its_place(self):
|
|
self.ai.wait_for_client = True
|
|
with self.assertLogs("kurgan.web", "INFO") as logs:
|
|
self.hang_up_after_sending("/strata/v1/chat/completions")
|
|
lines = self.wait_for_log(logs, "gave up")
|
|
self.assertRegex(lines[0], r"the client gave up after [01] s, while waiting for Strata to finish")
|
|
self.assertEqual(self.ai.calls, [("claim", "strata")]) # nothing reserved, so nothing to release
|
|
self.assertEqual(self.upstream.requests, [])
|
|
|
|
def test_other_methods_elsewhere_are_not_allowed(self):
|
|
self.assertEqual(self.request("DELETE", "/api/state")[0], 405)
|
|
self.assertEqual(self.request("PUT", "/api/lighting", b"{}")[0], 405)
|
|
self.assertEqual(self.request("OPTIONS", "/api/state")[0], 405)
|
|
|
|
def test_without_ai_management_the_routes_say_so(self):
|
|
port = free_port()
|
|
server = WebServer(SimpleNamespace(), port)
|
|
server.start()
|
|
try:
|
|
connection = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
|
|
connection.request("GET", "/llama/v1/models", headers={"Host": f"127.0.0.1:{port}"})
|
|
response = connection.getresponse()
|
|
self.assertEqual(response.status, 503)
|
|
self.assertIn("--no-ai", json.loads(response.read())["error"]["message"])
|
|
connection.close()
|
|
finally:
|
|
server.close()
|
|
|
|
def test_match(self):
|
|
self.assertEqual(proxy.match("/llama/v1/models?x=1"), ("llama", "/v1/models?x=1"))
|
|
self.assertEqual(proxy.match("/strata"), ("strata", None))
|
|
self.assertEqual(proxy.match("/strata?x"), ("strata", None))
|
|
self.assertIsNone(proxy.match("/stratax/v1"))
|
|
self.assertIsNone(proxy.match("/api/state"))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|