mirror of
https://github.com/hasso5703/alzeo.git
synced 2026-12-05 12:24:28 +01:00
No body (400), a body over OCR_BODY_MAX (413), a client that leaves before the front answers (CLIENT GONE during ocr) and a front that drops the request (503 unreachable, never the 504 of the answer's wait) were untested; tests/test_proxy_ocr.py runs them now, and joins the coverage job's file list, which takes keepalive-proxy.py back over its 85% floor (the new code read as untested, 84%). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
472 lines
25 KiB
Python
472 lines
25 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 struct
|
|
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
|
|
gone = threading.Event() # its answer failed: the proxy had closed its connection (its client was gone)
|
|
|
|
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:
|
|
Front.gone.set() # the proxy answered 504, or its client was gone
|
|
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 BlackHole(http.server.BaseHTTPRequestHandler):
|
|
"""Accepts the request and never reads its body: a send into it blocks past the socket's timeout."""
|
|
protocol_version = "HTTP/1.1"
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def do_POST(self):
|
|
time.sleep(10) # the body is never read, the sender's buffers fill
|
|
|
|
|
|
class RudeFront(http.server.BaseHTTPRequestHandler):
|
|
"""Reads the request, then drops the connection without answering (a reset, SO_LINGER 0): the proxy's
|
|
getresponse() then ends in an OSError."""
|
|
protocol_version = "HTTP/1.1"
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def do_POST(self):
|
|
self.rfile.read(int(self.headers.get("Content-Length") or 0))
|
|
self.connection.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER,
|
|
struct.pack("ii", 1, 0)) # close() sends a reset
|
|
self.connection.close()
|
|
|
|
|
|
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()
|
|
Front.gone.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_a_client_that_leaves_before_the_front_answers_ends_its_document_there_too(self):
|
|
"""Not streamed: the proxy waits for the front's answer (OCR_ANSWER_S) and watches its client meanwhile;
|
|
one that leaves before any answer is ended there ("CLIENT GONE during ocr"), the front's connection
|
|
closed, so the lane stops reading that document instead of reading it for nobody."""
|
|
Front.hold = 4
|
|
port = self.spawn(active=True, CLIENT_IO_S="1", OCR_ANSWER_S="10")
|
|
body = json.dumps(self.DOC).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)
|
|
self.assertTrue(Front.gone.wait(8), "the lane read on for a client that had left before any answer")
|
|
|
|
def test_no_body_or_a_body_over_the_cap_is_refused_before_the_lane_is_asked(self):
|
|
"""400 with no body at all, 413 over OCR_BODY_MAX (a document is 64 MiB in base64, the cap is its fields
|
|
beside): refused at the proxy, the front is never asked, the text engine neither."""
|
|
port = self.spawn(active=True, OCR_BODY_MAX="1024")
|
|
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: 0\r\n\r\n")
|
|
got = b""
|
|
while True:
|
|
chunk = s.recv(65536)
|
|
if not chunk:
|
|
break
|
|
got += chunk
|
|
self.assertIn(b" 400 ", got.split(b"\r\n")[0], got[:200])
|
|
self.assertEqual(json.loads(got.split(b"\r\n\r\n", 1)[1])["error"]["type"], "invalid_request")
|
|
self.assertIn("takes a body", got.decode(errors="replace"))
|
|
status, _, raw = self.ask_h(port, {**self.DOC, "pad": "x" * 2048}, timeout=10)
|
|
self.assertEqual(status, 413, raw[:300])
|
|
self.assertEqual(json.loads(raw)["error"]["type"], "request_too_large")
|
|
self.assertIn("over", json.loads(raw)["error"]["message"])
|
|
self.assertEqual((Front.asked, TextEngine.asked), ([], []))
|
|
|
|
def test_a_front_that_drops_the_request_is_a_503_to_try_again(self):
|
|
"""The front took the request and closed without answering: getresponse() ends in an OSError, which is the
|
|
lane unreachable (the 503 that says try again), never the 504 of the answer's wait."""
|
|
rude = http.server.ThreadingHTTPServer(("127.0.0.1", 0), RudeFront)
|
|
threading.Thread(target=rude.serve_forever, daemon=True).start()
|
|
self.addCleanup(rude.server_close)
|
|
self.addCleanup(rude.shutdown)
|
|
port = self.spawn(active=True, unit_file=self.home / "no-unit",
|
|
OCR_UPSTREAM=f"http://127.0.0.1:{rude.server_port}")
|
|
status, headers, raw = self.ask_h(port, self.DOC, timeout=30)
|
|
self.assertEqual(status, 503, raw[:300])
|
|
self.assertEqual(headers.get("Retry-After"), "10")
|
|
self.assertIn("did not answer", json.loads(raw)["error"]["message"])
|
|
|
|
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_ocr_is_in_the_client_routes_not_a_case_apart_in_the_wall(self):
|
|
"""/ocr, LiteLLM's shape of the lane's route, is in CLIENT_ROUTES, the list of what a client key reaches;
|
|
the wall has no case for it beside the list."""
|
|
was = os.environ.get("HOME")
|
|
os.environ["HOME"] = str(self.home)
|
|
try:
|
|
spec = importlib.util.spec_from_file_location("kproxy_routes", 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
|
|
finally:
|
|
if was is None:
|
|
os.environ.pop("HOME", None)
|
|
else:
|
|
os.environ["HOME"] = was
|
|
self.assertIn("/ocr", mod.CLIENT_ROUTES)
|
|
self.assertNotIn('route == "/ocr"', (REPO / "keepalive-proxy.py").read_text())
|
|
|
|
def test_a_document_longer_than_client_io_waits_for_the_front_when_not_streamed(self):
|
|
"""A /v1/ocr waits OCR_ANSWER_S (NONSTREAM_S + 120 s, the front's own bound plus a margin), 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_ANSWER_S="10") # 10 s of answer allowed
|
|
status, _, raw = self.ask(port, self.DOC, timeout=30)
|
|
self.assertEqual(status, 200, raw[:300])
|
|
self.assertEqual(Front.asked, ["/v1/ocr"])
|
|
|
|
def test_the_wait_for_the_fronts_answer_is_its_own_bound_plus_a_margin(self):
|
|
"""OCR_ANSWER_S is NONSTREAM_S + 120 = 7320 s: NONSTREAM_S = 7200 s is the bound past which the front itself
|
|
answers a 504 that says to stream (ocr-server.py, v1.62), so the proxy waits a little past it. MAX_PAGES *
|
|
PAGE_S bounded nothing: PAGE_S bounds the drawing of one page, the engine's read of it goes to 600 s."""
|
|
was = os.environ.get("HOME")
|
|
os.environ["HOME"] = str(self.home)
|
|
try:
|
|
spec = importlib.util.spec_from_file_location("kproxy_ocr_bound", 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
|
|
finally:
|
|
if was is None:
|
|
os.environ.pop("HOME", None)
|
|
else:
|
|
os.environ["HOME"] = was
|
|
self.assertEqual(mod.OCR_ANSWER_S, 7320.0)
|
|
|
|
def test_a_stream_field_nested_in_fields_gets_the_same_delay_as_any_body(self):
|
|
"""The body is no longer read for a stream: a regex misses a multipart form's stream field and takes a
|
|
\"stream\": true nested in a fields schema. Every /v1/ocr gets the same wait, OCR_ANSWER_S, streamed or
|
|
not (a stream receives its pages, and \": still reading\", every 15 s)."""
|
|
Front.hold = 4
|
|
port = self.spawn(active=True, CLIENT_IO_S="1", OCR_ANSWER_S="10") # 10 s of answer allowed
|
|
nested = {**self.DOC, "fields": {"stream": True, "pages": 3}}
|
|
status, _, raw = self.ask(port, nested, timeout=30)
|
|
self.assertEqual(status, 200, raw[:300])
|
|
status, _, raw = self.ask(port, self.DOC, timeout=30)
|
|
self.assertEqual(status, 200, raw[:300])
|
|
|
|
def test_no_answer_past_the_front_s_bound_is_a_504_that_says_the_front_is_stuck_never_a_retry(self):
|
|
"""A delay past the front's own bound (NONSTREAM_S, after which the front itself answers a 504 that says to stream)
|
|
means the front is stuck: never a try-again (no Retry-After, the client would send the same document again), and
|
|
no advice to stream either, a client that streamed already would loop on it: a 504 that says how to start the
|
|
lane again."""
|
|
Front.hold = 8
|
|
port = self.spawn(active=True, CLIENT_IO_S="1", OCR_ANSWER_S="2") # 2 s of answer 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")
|
|
message = json.loads(raw)["error"]["message"]
|
|
self.assertIn("Load of the OCR lane", message)
|
|
self.assertNotIn('send "stream"', message)
|
|
|
|
def test_a_send_that_times_out_is_a_503_to_try_again_not_a_504(self):
|
|
"""Only the wait for the front's ANSWER past the bound is a 504. A connect or a send that times out (the
|
|
front not listening yet, or its buffers full) is the lane unreachable: the 503 that says try again, never a
|
|
504 that claims the lane did not answer within the whole document's bound."""
|
|
hole = http.server.ThreadingHTTPServer(("127.0.0.1", 0), BlackHole)
|
|
threading.Thread(target=hole.serve_forever, daemon=True).start()
|
|
self.addCleanup(hole.server_close)
|
|
self.addCleanup(hole.shutdown)
|
|
port = self.spawn(active=True, unit_file=self.home / "no-unit", CLIENT_IO_S="1",
|
|
OCR_UPSTREAM=f"http://127.0.0.1:{hole.server_port}")
|
|
big = {**self.DOC, "pad": "x" * (8 * 1024 * 1024)} # the send blocks once the hole's buffers are full
|
|
status, headers, raw = self.ask_h(port, big, timeout=30)
|
|
self.assertEqual(status, 503, raw[:300])
|
|
self.assertEqual(headers.get("Retry-After"), "10")
|
|
self.assertIn("try again", json.loads(raw)["error"]["message"])
|
|
|
|
def test_lane_state_is_the_one_reading_of_systemd_for_the_clipstral_and_ocr_lanes(self):
|
|
"""clipstral_lane() and ocr_lane() were a line-by-line copy of each other: one lane_state(unit, seen)
|
|
reads systemd for both, cache and \"what it said last stands\" included."""
|
|
fake = pathlib.Path(tempfile.mkdtemp(prefix="fake-systemctl-lane-"))
|
|
self.addCleanup(shutil.rmtree, fake, True)
|
|
asked = fake / "asked"
|
|
(fake / "systemctl").write_text(
|
|
"#!/bin/sh\n"
|
|
f'echo "$*" >> {asked}\n'
|
|
'case "$*" in\n'
|
|
' "is-active qwen38-clipstral.service") echo active; exit 0 ;;\n'
|
|
' "is-active qwen38-ocr.service") echo activating; exit 3 ;;\n'
|
|
"esac\n"
|
|
"exit 3\n")
|
|
(fake / "systemctl").chmod(0o755)
|
|
was_path, was_home = os.environ.get("PATH"), os.environ.get("HOME")
|
|
os.environ["PATH"] = f"{fake}:{was_path or ''}"
|
|
os.environ["HOME"] = str(self.home)
|
|
try:
|
|
spec = importlib.util.spec_from_file_location("kproxy_lane_state", 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
|
|
seen = {"ts": -1e9, "state": ""}
|
|
self.assertEqual(mod.lane_state("qwen38-ocr.service", seen), "activating")
|
|
self.assertEqual(mod.lane_state("qwen38-ocr.service", seen), "activating") # cached: asked once
|
|
self.assertEqual(asked.read_text().splitlines(), ["is-active qwen38-ocr.service"])
|
|
self.assertEqual(mod.clipstral_lane(), "active")
|
|
self.assertEqual(mod.ocr_lane(), "activating")
|
|
finally:
|
|
os.environ["PATH"] = was_path or ""
|
|
if was_home is None:
|
|
os.environ.pop("HOME", None)
|
|
else:
|
|
os.environ["HOME"] = was_home
|
|
|
|
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"])
|
|
|
|
|
|
class TheWaitFollowsTheFront(unittest.TestCase):
|
|
"""The proxy waits for /v1/ocr's answer a little longer than the front's own bound on a document read without stream
|
|
(NONSTREAM_S, after which the front stops it and answers a 504 that says to stream): the proxy cannot import the front
|
|
(it is installed alone in ~/.config/qwen38), so the two numbers are written twice and held together here."""
|
|
|
|
def test_the_proxy_waits_two_minutes_past_the_front_s_bound(self):
|
|
front = int(re.search(r"^NONSTREAM_S = (\d+)\b", (REPO / "ocr-server.py").read_text(), re.M).group(1))
|
|
proxy = re.search(r'^OCR_ANSWER_S = float\(os\.environ\.get\("OCR_ANSWER_S", str\((\d+) \+ (\d+)\)\)\)',
|
|
(REPO / "keepalive-proxy.py").read_text(), re.M)
|
|
self.assertIsNotNone(proxy, "OCR_ANSWER_S is no longer written as NONSTREAM_S + a margin")
|
|
self.assertEqual(int(proxy.group(1)), front, "the proxy's wait no longer follows the front's NONSTREAM_S")
|
|
self.assertEqual(int(proxy.group(2)), 120)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|