mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-06 12:54:19 +01:00
With the identity wall on, /ocr was neither a CLIENT_ROUTE nor under a CLIENT_ROUTE_PREFIXES, so _wall_refused answered it the 404 that says the base URL is set wrong, before the relay, while the relay itself accepts /ocr (LiteLLM's shape of the lane's route, no /v1). A listed client key now reaches /ocr as it reaches /v1/ocr, and the front is still asked its own /v1/ocr. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
268 lines
14 KiB
Python
268 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""The proxy and the OCR lane (keepalive-proxy v6.69): POST /v1/ocr, Mistral's route, goes to the OCR lane's front while
|
|
qwen38-ocr.service is active, its answer relayed as it comes (a JSON body, or the pages as server-sent events, each passed on
|
|
when it arrives); with the lane stopped it is a 404 that says how to load it, and the text engine is never asked. The door
|
|
checks the box's key, and no key is sent to the front. A client that leaves during a stream ends the front's connection, so the
|
|
lane stops reading that document. systemd is asked through PATH, as in test_proxy_embeddings.py."""
|
|
import http.server
|
|
import importlib.util
|
|
import io
|
|
import json
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import shutil
|
|
import socket
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import time
|
|
import unittest
|
|
import urllib.error
|
|
import urllib.request
|
|
|
|
REPO = pathlib.Path(__file__).resolve().parents[1]
|
|
KEY = "test-key"
|
|
|
|
|
|
class Front(http.server.BaseHTTPRequestHandler):
|
|
"""The OCR lane's front as the proxy meets it: a JSON answer, or three pages streamed a quarter of a second apart."""
|
|
protocol_version = "HTTP/1.1"
|
|
asked, auths, bodies, left = [], [], [], threading.Event()
|
|
slow = False
|
|
hold = 0 # seconds the front "reads" a non-streamed document before answering
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def do_POST(self):
|
|
Front.asked.append(self.path)
|
|
Front.auths.append(self.headers.get("Authorization"))
|
|
req = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)))
|
|
Front.bodies.append(req)
|
|
if not req.get("stream"):
|
|
out = json.dumps({"pages": [{"index": 0, "markdown": "# Facture"}], "model": "ovisocr3",
|
|
"usage_info": {"pages_processed": 1}}).encode()
|
|
try:
|
|
if Front.hold:
|
|
time.sleep(Front.hold) # the front reading a long document before it answers at all
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(out)))
|
|
self.end_headers()
|
|
self.wfile.write(out)
|
|
except OSError:
|
|
pass # the proxy answered 504 and left
|
|
return
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/event-stream")
|
|
self.send_header("Connection", "close")
|
|
self.end_headers()
|
|
try:
|
|
for i in range(30 if Front.slow else 3):
|
|
self.wfile.write(b"data: " + json.dumps({"type": "page", "page": {"index": i, "markdown": f"page {i}"}}).encode() + b"\n\n")
|
|
self.wfile.flush()
|
|
time.sleep(0.25)
|
|
self.wfile.write(b'data: {"type": "done"}\n\n')
|
|
except OSError:
|
|
Front.left.set()
|
|
|
|
|
|
class TextEngine(http.server.BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
asked = []
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def do_POST(self):
|
|
TextEngine.asked.append(self.path)
|
|
self.send_response(400)
|
|
self.send_header("Content-Length", "2")
|
|
self.end_headers()
|
|
self.wfile.write(b"{}")
|
|
|
|
|
|
class TheRoute(unittest.TestCase):
|
|
def setUp(self):
|
|
home = pathlib.Path(tempfile.mkdtemp(prefix="proxy-ocr-home-"))
|
|
self.addCleanup(shutil.rmtree, home, True)
|
|
(home / ".config/qwen38").mkdir(parents=True)
|
|
(home / ".config/qwen38/api-key").write_text(KEY + "\n")
|
|
self.home = home
|
|
self.front = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Front)
|
|
self.text = http.server.ThreadingHTTPServer(("127.0.0.1", 0), TextEngine)
|
|
for s in (self.front, self.text):
|
|
threading.Thread(target=s.serve_forever, daemon=True).start()
|
|
self.addCleanup(s.server_close)
|
|
self.addCleanup(s.shutdown)
|
|
Front.asked[:], Front.auths[:], Front.bodies[:], TextEngine.asked[:] = [], [], [], []
|
|
Front.slow = False
|
|
Front.hold = 0
|
|
Front.left.clear()
|
|
|
|
def spawn(self, active, unit_file=None, state=None, **more):
|
|
fake = pathlib.Path(tempfile.mkdtemp(prefix="fake-systemctl-"))
|
|
self.addCleanup(shutil.rmtree, fake, True)
|
|
said = state if state is not None else ("active" if active else "inactive")
|
|
(fake / "systemctl").write_text(
|
|
"#!/bin/sh\n"
|
|
f'[ "$*" = "is-active --quiet qwen38-ocr.service" ] && exit {0 if said == "active" else 3}\n'
|
|
f'[ "$*" = "is-active qwen38-ocr.service" ] && {{ echo {said}; exit {0 if said == "active" else 3}; }}\n'
|
|
"exit 3\n")
|
|
(fake / "systemctl").chmod(0o755)
|
|
env = dict(UPSTREAM=f"http://127.0.0.1:{self.text.server_port}", PATH=f"{fake}:{os.environ.get('PATH', '')}",
|
|
HOME=str(self.home), **more)
|
|
if unit_file is None:
|
|
env["OCR_UPSTREAM"] = f"http://127.0.0.1:{self.front.server_port}"
|
|
else:
|
|
env["OCR_UNIT_FILE"] = str(unit_file)
|
|
was = {k: os.environ.get(k) for k in (*env, "OCR_UPSTREAM", "OCR_UNIT_FILE")}
|
|
self.addCleanup(lambda: [os.environ.pop(k, None) if v is None else os.environ.__setitem__(k, v) for k, v in was.items()])
|
|
for k in ("OCR_UPSTREAM", "OCR_UNIT_FILE"):
|
|
os.environ.pop(k, None)
|
|
os.environ.update(env)
|
|
spec = importlib.util.spec_from_file_location("kproxy_ocr", REPO / "keepalive-proxy.py")
|
|
mod = importlib.util.module_from_spec(spec)
|
|
err, sys.stderr = sys.stderr, io.StringIO()
|
|
try:
|
|
spec.loader.exec_module(mod)
|
|
finally:
|
|
sys.stderr = err
|
|
mod.log = lambda line: None
|
|
srv = mod.Server(("127.0.0.1", 0), mod.H)
|
|
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
|
self.addCleanup(srv.server_close)
|
|
self.addCleanup(srv.shutdown)
|
|
return srv.server_address[1]
|
|
|
|
def ask(self, port, body, key=KEY, path="/v1/ocr", timeout=20):
|
|
status, headers, raw = self.ask_h(port, body, key, path, timeout)
|
|
return status, headers.get("Content-Type"), raw
|
|
|
|
def ask_h(self, port, body, key=KEY, path="/v1/ocr", timeout=20):
|
|
headers = {"Content-Type": "application/json"}
|
|
if key is not None:
|
|
headers["Authorization"] = f"Bearer {key}"
|
|
req = urllib.request.Request(f"http://127.0.0.1:{port}{path}", data=json.dumps(body).encode(), headers=headers, method="POST")
|
|
try:
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
return r.status, r.headers, r.read()
|
|
except urllib.error.HTTPError as e:
|
|
return e.code, e.headers, e.read()
|
|
|
|
DOC = {"model": "ovisocr3", "document": {"type": "document_url", "document_url": "data:application/pdf;base64,JVBERi0xLjcK"}}
|
|
|
|
def test_with_the_lane_active_a_document_goes_to_its_front_and_back(self):
|
|
port = self.spawn(active=True)
|
|
status, ctype, raw = self.ask(port, self.DOC)
|
|
self.assertEqual((status, json.loads(raw)["pages"][0]["markdown"]), (200, "# Facture"), raw[:200])
|
|
self.assertEqual(Front.asked, ["/v1/ocr"])
|
|
self.assertEqual(Front.bodies[0], self.DOC)
|
|
self.assertEqual(Front.auths, [None], "the box's key stays at the door")
|
|
self.assertEqual(TextEngine.asked, [])
|
|
|
|
def test_its_pages_stream_as_they_come(self):
|
|
port = self.spawn(active=True)
|
|
body = json.dumps({**self.DOC, "stream": True}).encode()
|
|
with socket.create_connection(("127.0.0.1", port), timeout=10) as s:
|
|
s.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nAuthorization: Bearer " + KEY.encode()
|
|
+ b"\r\nContent-Length: %d\r\n\r\n" % len(body) + body)
|
|
t0, got, first = time.monotonic(), b"", None
|
|
while b'"type": "done"' not in got:
|
|
chunk = s.recv(65536)
|
|
if not chunk:
|
|
break
|
|
got += chunk
|
|
if first is None and b'"index": 0' in got:
|
|
first = time.monotonic() - t0
|
|
self.assertIn(b"text/event-stream", got)
|
|
self.assertEqual(got.count(b'"type": "page"'), 3)
|
|
self.assertLess(first, 0.45, "the first page waited for the others")
|
|
|
|
def test_a_client_that_leaves_ends_the_document_at_the_lane(self):
|
|
Front.slow = True
|
|
port = self.spawn(active=True)
|
|
body = json.dumps({**self.DOC, "stream": True}).encode()
|
|
with socket.create_connection(("127.0.0.1", port), timeout=10) as s:
|
|
s.sendall(b"POST /v1/ocr HTTP/1.1\r\nHost: x\r\nContent-Type: application/json\r\nAuthorization: Bearer " + KEY.encode()
|
|
+ b"\r\nContent-Length: %d\r\n\r\n" % len(body) + body)
|
|
s.recv(4096)
|
|
self.assertTrue(Front.left.wait(8), "the lane read on for a client that had left")
|
|
|
|
def test_with_the_lane_stopped_it_is_a_404_that_says_how_to_load_it(self):
|
|
port = self.spawn(active=False)
|
|
status, _, raw = self.ask(port, self.DOC)
|
|
self.assertEqual(status, 404)
|
|
self.assertIn("OCR lane is not running", json.loads(raw)["error"]["message"])
|
|
self.assertEqual((Front.asked, TextEngine.asked), ([], []))
|
|
|
|
def test_a_lane_that_moves_is_a_503_to_try_again_not_a_404(self):
|
|
"""Its start (its preflight runs up to 60 s), or the 10 s systemd waits after a death: a 404 is final to a
|
|
client, no SDK asks again, so the same rule as the Clipstral lane's (v6.66) applies to the OCR lane."""
|
|
for state, want in (("activating", 503), ("deactivating", 503), ("reloading", 503), ("", 503),
|
|
("inactive", 404), ("failed", 404)):
|
|
with self.subTest(state=state):
|
|
port = self.spawn(active=False, state=state)
|
|
status, headers, raw = self.ask_h(port, self.DOC)
|
|
err = json.loads(raw)["error"]
|
|
if want == 503:
|
|
self.assertEqual((status, err["type"], headers.get("Retry-After")), (503, "engine_unavailable", "10"), raw[:300])
|
|
self.assertIn("is starting or stopping" if state else "systemd does not say whether", err["message"])
|
|
else:
|
|
self.assertEqual((status, err["type"], headers.get("Retry-After")), (404, "model_not_found", None), raw[:300])
|
|
self.assertEqual((Front.asked, TextEngine.asked), ([], []))
|
|
|
|
def test_a_client_key_reaches_the_lane_on_ocr_as_on_v1_ocr(self):
|
|
"""LiteLLM's shape of the lane's route is /ocr, without /v1: with the clients' key wall on, it passes the
|
|
wall like /v1/ocr, instead of the 404 that says the base URL is set wrong."""
|
|
keys = pathlib.Path(tempfile.mkdtemp(prefix="ocr-keys-")) / "keys.json"
|
|
self.addCleanup(shutil.rmtree, keys.parent, True)
|
|
keys.write_text(json.dumps({"tok-client": "alice"}))
|
|
port = self.spawn(active=True, QWEN38_CLIENT_KEYS_FILE=str(keys))
|
|
for path in ("/v1/ocr", "/ocr"):
|
|
with self.subTest(path=path):
|
|
status, _, raw = self.ask(port, self.DOC, key="tok-client", path=path)
|
|
self.assertEqual(status, 200, (path, raw[:300]))
|
|
self.assertEqual(Front.asked, ["/v1/ocr", "/v1/ocr"], "the front is always asked its own /v1/ocr")
|
|
|
|
def test_a_document_longer_than_client_io_waits_for_the_front_when_not_streamed(self):
|
|
"""A non-streamed /v1/ocr waits as long as the front can read the longest document it accepts, MAX_PAGES pages
|
|
of PAGE_S each (ocr_pages.py), not CLIENT_IO_S: at 0.22 page/s beside the 27B a 200-page document takes over
|
|
900 s, and was answered a 503 to try again, which sends the same document again, forever."""
|
|
Front.hold = 4
|
|
port = self.spawn(active=True, CLIENT_IO_S="1", OCR_MAX_PAGES="5", OCR_PAGE_S="2") # 10 s of reading allowed
|
|
status, _, raw = self.ask(port, self.DOC, timeout=30)
|
|
self.assertEqual(status, 200, raw[:300])
|
|
self.assertEqual(Front.asked, ["/v1/ocr"])
|
|
|
|
def test_no_answer_past_the_longest_document_is_a_504_that_says_stream_never_a_retry(self):
|
|
"""A delay past what the front can take is never a try-again (no Retry-After, the client would send the same
|
|
document again): a 504 that says to send "stream": true for a long document."""
|
|
Front.hold = 8
|
|
port = self.spawn(active=True, CLIENT_IO_S="1", OCR_MAX_PAGES="1", OCR_PAGE_S="2") # 2 s of reading allowed
|
|
status, headers, raw = self.ask_h(port, self.DOC, timeout=30)
|
|
self.assertEqual(status, 504, raw[:300])
|
|
self.assertIsNone(headers.get("Retry-After"), "a delay past the bound is never a try-again")
|
|
self.assertIn("stream", json.loads(raw)["error"]["message"])
|
|
|
|
def test_without_the_key_the_door_refuses_it(self):
|
|
port = self.spawn(active=True)
|
|
self.assertEqual(self.ask(port, self.DOC, key=None)[0], 401)
|
|
self.assertEqual(Front.asked, [])
|
|
|
|
def test_the_fronts_port_is_read_after_ocr_server_in_its_unit(self):
|
|
unit = pathlib.Path(tempfile.mkdtemp(prefix="ocr-unit-")) / "qwen38-ocr.service"
|
|
self.addCleanup(shutil.rmtree, unit.parent, True)
|
|
# the lane's own template, its ports given and every other placeholder a word: the engine's --port follows the front's
|
|
tpl = (REPO / "qwen38-ocr.service.template").read_text()
|
|
unit.write_text(re.sub(r"__[A-Z][A-Z0-9_]*__", "x", tpl.replace("__OCR_PORT__", str(self.front.server_port))
|
|
.replace("__OCR_ENGINE_PORT__", "30034")))
|
|
port = self.spawn(active=True, unit_file=unit)
|
|
self.assertEqual(self.ask(port, self.DOC)[0], 200)
|
|
self.assertEqual(Front.asked, ["/v1/ocr"])
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|