285 lines
12 KiB
Python
285 lines
12 KiB
Python
"""The LLM servers' addresses on The Kurgan's web server: /strata/... and /llama/...
|
|
|
|
http://127.0.0.1:8080/strata/v1 OpenAI-compatible base URL for Strata
|
|
http://127.0.0.1:8080/llama/v1 ... for llama.cpp (no API key needed; any key is accepted)
|
|
http://127.0.0.1:8080/strata/ each server's own chat page (and everything else it serves)
|
|
http://127.0.0.1:8080/llama/
|
|
|
|
A request starts its server if it isn't running (see AiService.claim, which also stops the other
|
|
server once that one is idle) and the reply is streamed back as it is generated. A client that
|
|
hangs up (a timeout, or the user cancelling) is noticed within a second, even while it is still
|
|
waiting: its place is given up and the connection to the server closed, which stops the work on
|
|
it. The log then says how long the client waited and at what stage. GET .../v1/models is
|
|
answered here while a server is stopped, so a client listing the models of both doesn't make
|
|
them swap.
|
|
|
|
Security: the web server's Host check applies (DNS rebinding). A request carrying an Origin
|
|
header other than this server's comes from another site's page and is refused, as is anything
|
|
else a browser marks cross-site except opening a page. Pages of this server (the chat pages) are
|
|
let through with the Origin removed, so each server treats them like any local client.
|
|
llama-server keeps its API key on its own port, and this proxy supplies it, so neither server
|
|
asks clients here for a key.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import http.client
|
|
import json
|
|
import logging
|
|
import re
|
|
import select
|
|
import socket
|
|
import time
|
|
|
|
log = logging.getLogger(__name__)
|
|
|
|
ROUTE = re.compile(r"^/(strata|llama)(/[^?#]*)?(\?.*)?$")
|
|
MAX_BODY = 64 * 1024 * 1024 # images and very long prompts are big, but not this big
|
|
CONNECT_TIMEOUT = 10.0
|
|
READ_TIMEOUT = 1800.0 # between bytes: a model load plus a long prompt can take minutes
|
|
REQUEST_SKIP = {"connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer",
|
|
"transfer-encoding", "upgrade", "host", "content-length", "origin", "expect"}
|
|
RESPONSE_SKIP = {"connection", "keep-alive", "proxy-authenticate", "te", "trailer", "transfer-encoding",
|
|
"upgrade", "server", "date"}
|
|
|
|
|
|
class BodyError(Exception):
|
|
def __init__(self, message: str, status: int):
|
|
super().__init__(message)
|
|
self.status = status
|
|
|
|
|
|
def match(path: str) -> tuple[str, str | None] | None:
|
|
"""("llama", "/v1/models?x") for "/llama/v1/models?x"; ("llama", None) for "/llama"; None otherwise."""
|
|
m = ROUTE.match(path)
|
|
if m is None:
|
|
return None
|
|
rest = m[2]
|
|
return m[1], None if rest is None else rest + (m[3] or "")
|
|
|
|
|
|
def _error(handler, status: int, message: str) -> None:
|
|
body = json.dumps({"error": {"message": message, "type": "kurgan"}}).encode()
|
|
handler.send_response(status)
|
|
handler.send_header("Content-Type", "application/json")
|
|
handler.send_header("Content-Length", str(len(body)))
|
|
handler.send_header("Cache-Control", "no-store")
|
|
handler.send_header("Connection", "close")
|
|
handler.end_headers()
|
|
handler.close_connection = True
|
|
if handler.command != "HEAD":
|
|
handler.wfile.write(body)
|
|
|
|
|
|
def _read_body(handler) -> bytes | None:
|
|
"""The request body (Content-Length or chunked), None if there is none."""
|
|
if handler.headers.get("Transfer-Encoding", "").lower() == "chunked":
|
|
parts, total = [], 0
|
|
while True:
|
|
line = handler.rfile.readline(1024)
|
|
try:
|
|
size = int(line.split(b";")[0].strip(), 16)
|
|
except ValueError:
|
|
raise BodyError("malformed chunked body", 400) from None
|
|
if size == 0:
|
|
while handler.rfile.readline(1024) not in (b"\r\n", b"\n", b""): # trailers
|
|
pass
|
|
return b"".join(parts)
|
|
total += size
|
|
if total > MAX_BODY:
|
|
raise BodyError("request body too large", 413)
|
|
parts.append(handler.rfile.read(size))
|
|
handler.rfile.readline(8)
|
|
length = handler.headers.get("Content-Length")
|
|
if length is None:
|
|
return None
|
|
try:
|
|
length = int(length)
|
|
except ValueError:
|
|
raise BodyError("bad Content-Length", 400) from None
|
|
if length < 0:
|
|
raise BodyError("bad Content-Length", 400)
|
|
if length > MAX_BODY:
|
|
remaining = min(length, 1024 * 1024) # read a little so the client sees the answer; beyond that, give up
|
|
while remaining > 0:
|
|
chunk = handler.rfile.read(min(remaining, 65536))
|
|
if not chunk:
|
|
break
|
|
remaining -= len(chunk)
|
|
raise BodyError("request body too large", 413)
|
|
return handler.rfile.read(length)
|
|
|
|
|
|
def _models(handler, backend, rest: str) -> None:
|
|
"""OpenAI's model list, without starting the server."""
|
|
path = rest.split("?", 1)[0].rstrip("/")
|
|
models = [{"id": m, "object": "model", "created": 0, "owned_by": backend.key} for m in backend.model_ids()]
|
|
if path == "/v1/models":
|
|
data = {"object": "list", "data": models}
|
|
else:
|
|
wanted = path[len("/v1/models/"):]
|
|
data = next((m for m in models if m["id"] == wanted), None)
|
|
if data is None:
|
|
_error(handler, 404, f"model {wanted!r} not found")
|
|
return
|
|
body = json.dumps(data).encode()
|
|
handler.send_response(200)
|
|
handler.send_header("Content-Type", "application/json")
|
|
handler.send_header("Content-Length", str(len(body)))
|
|
handler.send_header("Connection", "close")
|
|
handler.end_headers()
|
|
handler.close_connection = True
|
|
handler.wfile.write(body)
|
|
|
|
|
|
def _location(value: str, backend) -> str:
|
|
"""Map a redirect from the server's own address onto its path here."""
|
|
internal = f"http://127.0.0.1:{backend.port}"
|
|
if value.startswith(internal):
|
|
value = value[len(internal):] or "/"
|
|
if not value.startswith("/"):
|
|
return value
|
|
if backend.prefix and value.startswith(backend.prefix):
|
|
value = value[len(backend.prefix):] or "/"
|
|
return f"/{backend.key}{value}"
|
|
|
|
|
|
class ClientGone(Exception):
|
|
"""The client closed its connection (it timed out or was cancelled); args[0] says when."""
|
|
|
|
|
|
def client_gone(handler) -> bool:
|
|
"""True once the client has closed its connection. The request has been read in full by
|
|
then, so a readable socket with nothing to read means the client hung up."""
|
|
sock = handler.connection
|
|
try:
|
|
readable, _, _ = select.select([sock], [], [], 0)
|
|
return bool(readable) and sock.recv(1, socket.MSG_PEEK) == b""
|
|
except (OSError, ValueError):
|
|
return True
|
|
|
|
|
|
def handle(handler, ai, hosts: set[str], origins: set[str]) -> None:
|
|
"""Serve one request for /strata/... or /llama/... (handler is a BaseHTTPRequestHandler)."""
|
|
started = time.monotonic()
|
|
try:
|
|
_serve(handler, ai, hosts, origins, started)
|
|
except (ClientGone, ConnectionError) as e:
|
|
handler.close_connection = True
|
|
when = e.args[0] if isinstance(e, ClientGone) else "before its answer was sent"
|
|
log.info("%s %s: the client gave up after %.0f s, %s", handler.command, handler.path,
|
|
time.monotonic() - started, when)
|
|
|
|
|
|
def _serve(handler, ai, hosts: set[str], origins: set[str], started: float) -> None:
|
|
key, rest = match(handler.path)
|
|
try:
|
|
body = _read_body(handler) # before any answer: unread data would reset the connection on Windows
|
|
except BodyError as e:
|
|
_error(handler, e.status, str(e))
|
|
return
|
|
if handler.headers.get("Host") not in hosts:
|
|
_error(handler, 403, "forbidden host")
|
|
return
|
|
origin = handler.headers.get("Origin")
|
|
if origin is not None and origin not in origins:
|
|
_error(handler, 403, f"web pages of {origin} may not use The Kurgan's AI servers")
|
|
return
|
|
# An <img> or <script> on another site's page sends no Origin but could still make the servers
|
|
# swap; browsers mark it cross-site. Following a link (a top-level page load) is fine.
|
|
if handler.headers.get("Sec-Fetch-Site") == "cross-site" and handler.headers.get("Sec-Fetch-Dest") != "document":
|
|
_error(handler, 403, "other sites' pages may not use The Kurgan's AI servers")
|
|
return
|
|
if rest is None: # /llama -> /llama/, so the chat page's relative links resolve under it
|
|
handler.send_response(308)
|
|
handler.send_header("Location", f"/{key}/")
|
|
handler.send_header("Content-Length", "0")
|
|
handler.end_headers()
|
|
return
|
|
if ai is None:
|
|
_error(handler, 503, "AI management is off for this run of The Kurgan (--no-ai)")
|
|
return
|
|
path = rest.split("?", 1)[0].rstrip("/")
|
|
if handler.command == "GET" and (path == "/v1/models" or path.startswith("/v1/models/")) and not ai.running(key):
|
|
_models(handler, ai.slots[key].backend, rest)
|
|
return
|
|
|
|
from kurgan.ai.service import CLIENT_GONE, RouteError
|
|
|
|
try:
|
|
# A client that leaves while waiting (for the other server to finish, or for this one to
|
|
# start) releases its place, so an abandoned request never makes the servers swap.
|
|
backend = ai.claim(key, gone=lambda: client_gone(handler))
|
|
except RouteError as e:
|
|
if e.status == CLIENT_GONE:
|
|
raise ClientGone(str(e)) from None
|
|
log.warning("%s %s: %s", handler.command, handler.path, e)
|
|
_error(handler, e.status, str(e))
|
|
return
|
|
try:
|
|
status = _relay(handler, backend, rest, body)
|
|
finally:
|
|
ai.release(key)
|
|
if handler.command != "GET" or status >= 400:
|
|
log.info("%s %s -> %s in %.1f s", handler.command, handler.path, status, time.monotonic() - started)
|
|
|
|
|
|
def _await_reply(handler, upstream: socket.socket, backend) -> None:
|
|
"""Wait for the server's reply to start: a request can sit in its queue, or its prompt be read,
|
|
for minutes, and a reply that isn't streamed arrives all at once at the end. If the client
|
|
hangs up meanwhile, give up: closing the connection tells the server to drop the request."""
|
|
deadline = time.monotonic() + READ_TIMEOUT
|
|
while not select.select([upstream], [], [], 0.5)[0]:
|
|
if client_gone(handler):
|
|
raise ClientGone(f"before {backend.label} started its reply")
|
|
if time.monotonic() > deadline:
|
|
raise TimeoutError(f"no reply within {READ_TIMEOUT:.0f} s")
|
|
|
|
|
|
def _relay(handler, backend, rest: str, body: bytes | None) -> int:
|
|
extra = backend.proxy_headers() if hasattr(backend, "proxy_headers") else {}
|
|
skip = REQUEST_SKIP | {k.lower() for k in extra}
|
|
headers = {k: v for k, v in handler.headers.items() if k.lower() not in skip}
|
|
headers.update(extra)
|
|
headers["Host"] = f"127.0.0.1:{backend.port}"
|
|
if body is not None:
|
|
headers["Content-Length"] = str(len(body))
|
|
connection = http.client.HTTPConnection("127.0.0.1", backend.port, timeout=CONNECT_TIMEOUT)
|
|
try:
|
|
try:
|
|
connection.connect()
|
|
connection.sock.settimeout(READ_TIMEOUT)
|
|
connection.request(handler.command, backend.prefix + rest, body=body, headers=headers)
|
|
_await_reply(handler, connection.sock, backend)
|
|
response = connection.getresponse()
|
|
except (OSError, http.client.HTTPException) as e:
|
|
_error(handler, 502, f"{backend.label} isn't answering: {e}")
|
|
return 502
|
|
handler.send_response(response.status, response.reason)
|
|
for name, value in response.getheaders():
|
|
if name.lower() in RESPONSE_SKIP:
|
|
continue
|
|
handler.send_header(name, _location(value, backend) if name.lower() == "location" else value)
|
|
handler.send_header("Connection", "close") # HTTP/1.0: the end of the stream ends the reply
|
|
handler.end_headers()
|
|
handler.close_connection = True
|
|
if handler.command == "HEAD":
|
|
return response.status
|
|
sent = 0
|
|
while True:
|
|
try:
|
|
chunk = response.read1(65536)
|
|
except (OSError, http.client.HTTPException) as e:
|
|
log.warning("%s stopped answering mid-reply: %s", backend.label, e)
|
|
break
|
|
if not chunk:
|
|
break
|
|
try:
|
|
handler.wfile.write(chunk)
|
|
except OSError: # closing our side (finally, below) stops the generation
|
|
raise ClientGone(f"mid-reply, after {sent:,} bytes") from None
|
|
sent += len(chunk)
|
|
return response.status
|
|
finally:
|
|
connection.close()
|