hugpy-queue 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ """hugpy-queue: the queue of a Hugpy worker: the front door, a record of every call, and its stages (README.md)."""
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
hugpy_queue/calls.py ADDED
@@ -0,0 +1,70 @@
1
+ """A call's row and the rows of its stages: what the queue writes as a call passes through its hands."""
2
+ from __future__ import annotations
3
+
4
+ from .imports import json, time
5
+
6
+
7
+ def fields(body: bytes) -> dict:
8
+ """What the queue reads of a call's body: the model as named, whether it streams, its cap on tokens."""
9
+ try:
10
+ doc = json.loads(body) if body else {}
11
+ except ValueError:
12
+ return {}
13
+ if not isinstance(doc, dict):
14
+ return {}
15
+ cap = doc.get("max_tokens", doc.get("max_completion_tokens"))
16
+ return {"model": doc.get("model") if isinstance(doc.get("model"), str) else None,
17
+ "stream": int(bool(doc.get("stream"))) if "stream" in doc else None,
18
+ "max_tokens": cap if isinstance(cap, int) else None}
19
+
20
+
21
+ def received(conn, at: float, endpoint: str, read: dict, caller: str, body: bytes) -> int:
22
+ """Stage 10: the call is recorded as it arrived. Returns its id."""
23
+ call_id = conn.execute(
24
+ "INSERT INTO calls (arrived_at, endpoint, model, stream, max_tokens, caller, bytes_in, body) "
25
+ "VALUES (?,?,?,?,?,?,?,?)",
26
+ (at, endpoint, read.get("model"), read.get("stream"), read.get("max_tokens"), caller, len(body), body)).lastrowid
27
+ conn.execute("INSERT INTO call_stages (call_id, stage_no, stage, owner, started_at, finished_at) "
28
+ "VALUES (?, 10, 'received', 'queue', ?, ?)", (call_id, at, time.time()))
29
+ return call_id
30
+
31
+
32
+ def handed(conn, call_id: int, to: str, at: float, note: str) -> None:
33
+ """The call leaves the queue's hands for a part that does several stages itself."""
34
+ conn.execute("UPDATE calls SET state = 'handed', handed_to = ? WHERE id = ?", (to, call_id))
35
+ conn.execute("INSERT INTO call_stages (call_id, stage, owner, started_at, note) VALUES (?, 'handed', ?, ?, ?)",
36
+ (call_id, to, at, note))
37
+
38
+
39
+ def answered(conn, call_id: int, at: float, status, ref, error) -> None:
40
+ """Stage 100: the part it was handed to has answered (or could not be reached)."""
41
+ conn.execute("UPDATE call_stages SET finished_at = ? WHERE call_id = ? AND stage = 'handed' AND finished_at IS NULL",
42
+ (at, call_id))
43
+ ok = status is not None and status < 500 and not error
44
+ conn.execute("UPDATE calls SET state = ?, kind = ?, handed_ref = ?, status = ?, done_at = ?, error = ? WHERE id = ?",
45
+ ("done" if ok else "failed",
46
+ "call" if ref else "refused" if status is not None and status >= 400 else "command",
47
+ ref, status, at, error, call_id))
48
+ conn.execute("INSERT INTO call_stages (call_id, stage_no, stage, owner, started_at, finished_at) "
49
+ "VALUES (?, 100, 'done', 'queue', ?, ?)", (call_id, at, at))
50
+
51
+
52
+ def responded(conn, call_id: int, began: float, at: float, bytes_out: int, error, bytes_back=None, verified=None) -> None:
53
+ """Stage 110: the reply is written to the caller (or the caller had gone). The body is held no longer.
54
+ `verified`: all that the part said it would send came back, and all of it was written to the caller."""
55
+ conn.execute("UPDATE calls SET responded_at = ?, bytes_out = ?, bytes_back = ?, verified = ?, body = NULL, "
56
+ "error = COALESCE(error, ?), state = CASE WHEN ? IS NULL THEN state ELSE 'failed' END WHERE id = ?",
57
+ (at, bytes_out, bytes_back, verified, error, error, call_id))
58
+ conn.execute("INSERT INTO call_stages (call_id, stage_no, stage, owner, started_at, finished_at, note) "
59
+ "VALUES (?, 110, 'responded', 'queue', ?, ?, ?)", (call_id, began, at, error))
60
+
61
+
62
+ def left_from_before(conn) -> int:
63
+ """Calls a process before this one left in flight: it ended with them, and they say so."""
64
+ now = time.time()
65
+ count = conn.execute("UPDATE calls SET state = 'failed', body = NULL, done_at = COALESCE(done_at, ?), "
66
+ "error = COALESCE(error, 'the queue stopped while it was in flight') "
67
+ "WHERE state IN ('received', 'handed')", (now,)).rowcount
68
+ conn.execute("UPDATE call_stages SET finished_at = ?, note = COALESCE(note || '; ', '') || 'the queue stopped' "
69
+ "WHERE finished_at IS NULL", (now,))
70
+ return count
hugpy_queue/cli.py ADDED
@@ -0,0 +1,81 @@
1
+ """`hugpy-queue`: serve | calls | door | settings | set | system."""
2
+ from __future__ import annotations
3
+
4
+ from . import store
5
+ from .imports import DEFAULTS, QUEUE_DB, TOOL, argparse, os, sqlite3, sys, time
6
+
7
+
8
+ def _clock(at) -> str:
9
+ return time.strftime("%H:%M:%S", time.localtime(at)) if at else "-"
10
+
11
+
12
+ def _calls(args) -> int:
13
+ conn = store.reader()
14
+ try:
15
+ for call in conn.execute("SELECT * FROM call_times ORDER BY id DESC LIMIT ?", (args.limit,)).fetchall():
16
+ took = "-" if call["total_s"] is None else f"{call['total_s']:.2f}s"
17
+ proof = {1: "verified", 0: "NOT verified"}.get(call["verified"], "")
18
+ print(f"{call['id']:>6} {_clock(call['arrived_at'])} {call['state']:<8} {str(call['status'] or '-'):<4} {proof:<12} "
19
+ f"{took:>9} {call['kind'] or '-':<8} {call['endpoint']} {call['model'] or ''}"
20
+ + (f" -> {call['handed_to']} {call['handed_ref']}" if call["handed_ref"] else ""))
21
+ for stage in conn.execute("SELECT * FROM call_stages WHERE call_id = ? ORDER BY started_at, id", (call["id"],)):
22
+ lasted = "" if stage["finished_at"] is None else f"{stage['finished_at'] - stage['started_at']:.3f}s"
23
+ print(f" {str(stage['stage_no'] or ''):>3} {stage['stage']:<10} {stage['owner']:<8} "
24
+ f"{_clock(stage['started_at'])} {lasted:>9} {stage['note'] or ''}")
25
+ finally:
26
+ conn.close()
27
+ return 0
28
+
29
+
30
+ def _door(_args) -> int:
31
+ conn = store.reader()
32
+ try:
33
+ for row in conn.execute("SELECT * FROM front_door_routes ORDER BY requests DESC").fetchall():
34
+ print(f"{row['requests']:>8} {row['method'] or '-':<7} {str(row['status'] or '-'):<4} "
35
+ f"{(row['avg_ms'] or 0):>9.1f} ms {row['route']}")
36
+ finally:
37
+ conn.close()
38
+ return 0
39
+
40
+
41
+ def _settings(_args) -> int:
42
+ found = store.settings()
43
+ for name in DEFAULTS:
44
+ print(f"{name:<12} {found[name]}" + ("" if found[name] != DEFAULTS[name] else " (default)"))
45
+ print(f"{'database':<12} {QUEUE_DB}")
46
+ return 0
47
+
48
+
49
+ def _set(args) -> int:
50
+ try:
51
+ store.save_setting(args.name, args.value, by=f"{TOOL} set")
52
+ except KeyError as exc:
53
+ raise SystemExit(str(exc.args[0]))
54
+ print(f"{args.name} = {args.value} (the service reads it when it next starts)")
55
+ return 0
56
+
57
+
58
+ def main(argv=None) -> int:
59
+ argv = sys.argv[1:] if argv is None else list(argv)
60
+ if argv[:1] == ["system"]:
61
+ from .system import main as system_main
62
+ return system_main(argv[1:], given=os.environ.get("HUGPY_DATA_DIR"))
63
+ parser = argparse.ArgumentParser(prog=TOOL, description="The queue: the front door, every call and its stages")
64
+ sub = parser.add_subparsers(dest="command", required=True)
65
+ sub.add_parser("serve", help="the front door (the service runs this)")
66
+ shown = sub.add_parser("calls", help="the latest calls and their stages")
67
+ shown.add_argument("--limit", type=int, default=10)
68
+ sub.add_parser("door", help="what is asked of the door, a route and status")
69
+ sub.add_parser("settings", help="every setting and its value")
70
+ one = sub.add_parser("set", help="save one setting")
71
+ one.add_argument("name")
72
+ one.add_argument("value")
73
+ sub.add_parser("system", help="install | status | uninstall: this tool as a service of the host")
74
+ args = parser.parse_args(argv)
75
+ if args.command == "serve":
76
+ from .door import serve
77
+ return serve()
78
+ try:
79
+ return {"calls": _calls, "door": _door, "settings": _settings, "set": _set}[args.command](args)
80
+ except sqlite3.OperationalError as exc:
81
+ raise SystemExit(f"{QUEUE_DB}: {exc} (is the service installed? sudo {TOOL} system install)")
@@ -0,0 +1,62 @@
1
+ """The core statements of queue: one named query for each derivation this part owns.
2
+
3
+ Each is a SELECT that takes no call as input and answers for every model as things stand. `views(conn)`
4
+ makes them temporary views of a connection, under these names, in this order (a later one reads an earlier).
5
+ """
6
+
7
+ # Q1 call_units: the model a call is for, as a unit. The queue's own row has the model as the caller named it; which unit that is (the quant chosen, a person's approved fallbacks) is still resolved in the wrapper (queue/rows.py choose, auto_quant, resolve: about 150 lines) and is on the wrapper's row
8
+ CALL_UNITS_SQL = """
9
+ SELECT c.id AS call_id, c.arrived_at, c.endpoint, c.model AS named, c.state, c.kind,
10
+ q.id AS wrapper_id, q.key, q.variation, COALESCE(NULLIF(q.engine, ''), u.engine) AS engine,
11
+ COALESCE(q.tokens_in, 0) AS tokens_in, COALESCE(c.max_tokens, q.tokens_out_hi) AS output_top
12
+ FROM main.calls c
13
+ LEFT JOIN w.queue q ON c.handed_to = 'wrapper'
14
+ AND q.id = CAST(replace(c.handed_ref, rtrim(c.handed_ref, '0123456789'), '') AS INTEGER)
15
+ LEFT JOIN w.units_mat u ON u.key = q.key AND u.variation = q.variation
16
+ WHERE c.endpoint LIKE '/v1/%'
17
+ """
18
+
19
+ # Q2 model_readiness: the readiness of all three components for every model, with no call. accommodated Discovery: its files are whole where its route loads it from resident wrapper: it is in the resources (a load that is ready and not ended) engine_here engines: its engine can start o
20
+ MODEL_READINESS_SQL = """
21
+ SELECT u.key, u.variation, u.engine,
22
+ COALESCE(du.route_present, 0) AS accommodated, du.route_role AS loaded_from,
23
+ EXISTS (SELECT 1 FROM w.load_runs r WHERE r.key = u.key AND r.variation = u.variation
24
+ AND r.state = 'ready' AND r.ended_at IS NULL) AS resident,
25
+ EXISTS (SELECT 1 FROM w.load_runs r WHERE r.key = u.key AND r.variation = u.variation
26
+ AND r.state = 'requested' AND r.ended_at IS NULL) AS loading,
27
+ COALESCE(en.ready, 0) AS engine_here, en.why AS engine_why,
28
+ EXISTS (SELECT 1 FROM w.load_runs r JOIN e.starts s ON s.pid = r.pid AND s.port = r.port
29
+ WHERE r.key = u.key AND r.variation = u.variation AND r.state = 'ready' AND r.ended_at IS NULL
30
+ AND s.ready_at IS NOT NULL AND s.stopped_at IS NULL) AS engine_up
31
+ FROM w.units_mat u
32
+ LEFT JOIN d.api_units_v1 du ON du.key = u.key AND du.variation = u.variation
33
+ LEFT JOIN e.engines en ON en.engine = u.engine
34
+ """
35
+
36
+ # Q3 call_readiness: for any call in the queue, whether all three are ready for it, and the stage still wanted (the operator's order, stage_order: 60 accommodate, 70 evict and 80 load, 90 intake).
37
+ CALL_READINESS_SQL = """
38
+ SELECT c.call_id, c.arrived_at, c.named, c.key, c.variation, c.state,
39
+ m.accommodated, m.resident, m.engine_here, m.engine_up,
40
+ (m.accommodated AND m.resident AND m.engine_up) AS ready,
41
+ CASE WHEN c.key IS NULL THEN 'not a model this worker has'
42
+ WHEN NOT m.engine_here THEN 'none: its engine cannot start here (' || COALESCE(m.engine_why, 'no reason on record') || ')'
43
+ WHEN NOT m.accommodated THEN '60 accommodate (Discovery)'
44
+ WHEN NOT m.resident THEN CASE WHEN m.loading THEN '80 load (under way)' ELSE '70 evict, 80 load (wrapper)' END
45
+ WHEN NOT m.engine_up THEN '80 load: no engine on record for it'
46
+ ELSE '90 intake (engines)' END AS wanted
47
+ FROM call_units c LEFT JOIN model_readiness m ON m.key = c.key AND m.variation = c.variation
48
+ """
49
+
50
+ CORE = {
51
+ 'call_units': CALL_UNITS_SQL,
52
+ 'model_readiness': MODEL_READINESS_SQL,
53
+ 'call_readiness': CALL_READINESS_SQL,
54
+ }
55
+
56
+
57
+ def views(conn) -> list:
58
+ """Make every core statement a temporary view of `conn`; the names made."""
59
+ for name, sql in CORE.items():
60
+ conn.execute(f"DROP VIEW IF EXISTS temp.{name}")
61
+ conn.execute(f"CREATE TEMP VIEW {name} AS {sql}")
62
+ return list(CORE)
hugpy_queue/door.py ADDED
@@ -0,0 +1,305 @@
1
+ """The front door: every request on record, every POST a call with its stages, and the hand-off.
2
+
3
+ As it stands (2026-12-03) a call is handed to the wrapper whole: the wrapper still does stages 20 to 90 itself, so
4
+ the hand-off is one stage row (`handed`, owner `wrapper`) from the moment it is sent until the wrapper's answer
5
+ begins. Requests that are not calls (reads, commands) pass straight through and are on record at the door all the
6
+ same. The reply is passed back as it comes, so a reply written piece by piece arrives piece by piece.
7
+
8
+ Who may call is still the wrapper's to decide: every header is passed on as it came, and a caller that is not this
9
+ box is named to the wrapper (X-Forwarded-For), so the wrapper asks it for its key exactly as it would at its own door.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ from ipaddress import ip_address
14
+
15
+ from . import calls, store
16
+ from .imports import (
17
+ DOOR_READ_KEEP_S,
18
+ HOP_HEADERS,
19
+ SERVICE,
20
+ TOOL,
21
+ BaseHTTPRequestHandler,
22
+ ThreadingHTTPServer,
23
+ http,
24
+ json,
25
+ parse_qs,
26
+ threading,
27
+ time,
28
+ tool_version,
29
+ urlparse,
30
+ )
31
+
32
+ HANDED_NOTE = "stages 20 to 90 are still the wrapper's own"
33
+ _DOOR_LOCK = threading.Lock()
34
+ _DOOR_ROWS = []
35
+ _DOOR_KEEPER = []
36
+ _DOOR_READS = "method = 'GET' AND status BETWEEN 200 AND 399 AND path IS NOT NULL AND at < ?"
37
+
38
+
39
+ def _door_flush() -> None:
40
+ with _DOOR_LOCK:
41
+ rows = _DOOR_ROWS[:]
42
+ del _DOOR_ROWS[:]
43
+ if rows:
44
+ store.write(lambda conn: conn.executemany(
45
+ "INSERT INTO front_door (at, ms, method, path, status, bytes_in, bytes_out, caller, call_id) "
46
+ "VALUES (?,?,?,?,?,?,?,?,?)", rows), wait=False)
47
+
48
+
49
+ def _door_rollup() -> None:
50
+ """What is needed of the routine reads is taken and their rows are removed: every answered GET older than
51
+ DOOR_READ_KEEP_S is counted into front_door_hours and deleted, in one transaction. A call, a request that was
52
+ refused or failed, and one that got no answer keep their own rows."""
53
+ cutoff = time.time() - DOOR_READ_KEEP_S
54
+
55
+ def roll(conn):
56
+ conn.execute(
57
+ "INSERT INTO front_door_hours (hour, method, route, status, caller, requests, ms, max_ms, bytes_out, "
58
+ "first_at, last_at) "
59
+ "SELECT CAST(at / 3600 AS INTEGER) * 3600, method, "
60
+ "CASE WHEN instr(path, '?') THEN substr(path, 1, instr(path, '?') - 1) ELSE path END, status, "
61
+ "COALESCE(caller, ''), COUNT(*), SUM(ms), MAX(ms), SUM(bytes_out), MIN(at), MAX(at) "
62
+ f"FROM front_door WHERE {_DOOR_READS} GROUP BY 1, 2, 3, 4, 5 "
63
+ "ON CONFLICT (hour, method, route, status, caller) DO UPDATE SET "
64
+ "requests = requests + excluded.requests, ms = COALESCE(ms, 0) + COALESCE(excluded.ms, 0), "
65
+ "max_ms = MAX(COALESCE(max_ms, 0), COALESCE(excluded.max_ms, 0)), "
66
+ "bytes_out = COALESCE(bytes_out, 0) + COALESCE(excluded.bytes_out, 0), "
67
+ "first_at = MIN(first_at, excluded.first_at), last_at = MAX(last_at, excluded.last_at)", (cutoff,))
68
+ conn.execute(f"DELETE FROM front_door WHERE {_DOOR_READS}", (cutoff,))
69
+ store.write(roll, wait=False)
70
+
71
+
72
+ def _door_keep() -> None:
73
+ rolled = time.monotonic()
74
+ while True:
75
+ time.sleep(1.0)
76
+ _door_flush()
77
+ if time.monotonic() - rolled >= 60.0:
78
+ rolled = time.monotonic()
79
+ _door_rollup()
80
+
81
+
82
+ def _door_record(row: tuple, now: bool) -> None:
83
+ with _DOOR_LOCK:
84
+ if len(_DOOR_ROWS) < 20_000: # nobody writing: the newest are dropped rather than memory filled
85
+ _DOOR_ROWS.append(row)
86
+ start = not _DOOR_KEEPER
87
+ if start:
88
+ _DOOR_KEEPER.append(True)
89
+ if start:
90
+ threading.Thread(target=_door_keep, daemon=True, name="front-door-record").start()
91
+ if now:
92
+ _door_flush()
93
+
94
+
95
+ def _this_box(peer: str) -> bool:
96
+ try:
97
+ return ip_address(peer).is_loopback
98
+ except ValueError:
99
+ return False
100
+
101
+
102
+ class Handler(BaseHTTPRequestHandler):
103
+ protocol_version = "HTTP/1.1"
104
+ server_version = TOOL
105
+
106
+ def log_message(self, fmt, *args):
107
+ pass
108
+
109
+ def parse_request(self):
110
+ self._door = dict(at=time.time(), status=None, out=None, call_id=None) # this request's front_door row
111
+ return super().parse_request()
112
+
113
+ def log_request(self, code="-", size="-"):
114
+ door = getattr(self, "_door", None)
115
+ if door is not None:
116
+ try:
117
+ door["status"] = int(code)
118
+ except (TypeError, ValueError):
119
+ pass
120
+
121
+ def handle_one_request(self):
122
+ self._door = None
123
+ try:
124
+ super().handle_one_request()
125
+ finally:
126
+ door = getattr(self, "_door", None)
127
+ if door is not None:
128
+ headers = getattr(self, "headers", None)
129
+ length = headers.get("Content-Length") if headers is not None else None
130
+ method = getattr(self, "command", None)
131
+ try:
132
+ bytes_in = int(length) if length else None
133
+ except ValueError:
134
+ bytes_in = None
135
+ _door_record((door["at"], 1000 * (time.time() - door["at"]), method,
136
+ (getattr(self, "path", None) or "")[:2000] or None, door["status"], bytes_in,
137
+ door["out"], self.client_address[0], door["call_id"]),
138
+ now=method != "GET" or not door["status"] or door["status"] >= 400)
139
+
140
+ def _send(self, status: int, doc) -> None:
141
+ data = json.dumps(doc).encode()
142
+ self.send_response(status)
143
+ self.send_header("Content-Type", "application/json")
144
+ self.send_header("Content-Length", str(len(data)))
145
+ self.end_headers()
146
+ self.wfile.write(data)
147
+ self._door["out"] = len(data)
148
+
149
+ def _health(self) -> None:
150
+ """The worker's health, answered by its queue under its own name: who answers here, the worker it is the
151
+ door of, and each part behind it with that part's own health as the part gave it."""
152
+ target = urlparse(self.server.wrapper_url)
153
+ part, reasons, code = {"url": self.server.wrapper_url}, [], 503
154
+ upstream = http.client.HTTPConnection(target.hostname, target.port or 80, timeout=5)
155
+ try:
156
+ upstream.request("GET", "/health", headers={"Connection": "close"})
157
+ answer = upstream.getresponse()
158
+ code, found = answer.status, json.loads(answer.read())
159
+ if isinstance(found, dict):
160
+ part["health"] = found
161
+ except (OSError, http.client.HTTPException, ValueError) as exc:
162
+ reasons.append(f"the wrapper at {self.server.wrapper_url} does not answer: {exc}")
163
+ finally:
164
+ upstream.close()
165
+ inner = part.get("health") or {}
166
+ if inner.get("worker"):
167
+ self.server.worker = inner["worker"] # who this door is the door of, kept while it is away
168
+ if inner and inner.get("status") != "ok":
169
+ reasons.append(f"its wrapper says it is {inner.get('status')}")
170
+ self._send(code if inner else 503, {
171
+ "service": SERVICE, "package": TOOL, "version": tool_version("hugpy_queue", __file__),
172
+ "status": "ok" if inner.get("status") == "ok" else "degraded",
173
+ "worker": getattr(self.server, "worker", None), "reasons": reasons, "warnings": [],
174
+ "parts": {"wrapper": part}})
175
+
176
+ def _own(self, url) -> None:
177
+ """The queue's own reads, under /_queue/: its health, its calls, its door, the order of stages."""
178
+ query = parse_qs(url.query)
179
+ conn = store.reader()
180
+ try:
181
+ def rows(sql, args=()):
182
+ return [dict(row) for row in conn.execute(sql, args).fetchall()]
183
+ if url.path == "/_queue/health":
184
+ return self._send(200, {
185
+ "service": TOOL, "version": tool_version("hugpy_queue", __file__),
186
+ "wrapper_url": self.server.wrapper_url,
187
+ "in_flight": conn.execute("SELECT COUNT(*) FROM calls WHERE state IN ('received','handed')").fetchone()[0]})
188
+ if url.path == "/_queue/calls":
189
+ limit = min(500, int((query.get("limit") or ["20"])[0]))
190
+ found = rows("SELECT * FROM call_times ORDER BY id DESC LIMIT ?", (limit,))
191
+ for call in found:
192
+ call["stages"] = rows("SELECT stage_no, stage, owner, started_at, finished_at, note FROM call_stages "
193
+ "WHERE call_id = ? ORDER BY started_at, id", (call["id"],))
194
+ return self._send(200, {"calls": found})
195
+ if url.path == "/_queue/door":
196
+ return self._send(200, {"routes": rows("SELECT * FROM front_door_routes ORDER BY requests DESC")})
197
+ if url.path == "/_queue/stages":
198
+ return self._send(200, {"stages": rows("SELECT * FROM stage_order ORDER BY stage_no")})
199
+ return self._send(404, {"error": f"{url.path}: not one of the queue's reads", "source": "client"})
200
+ finally:
201
+ conn.close()
202
+
203
+ def _pass(self) -> None:
204
+ url = urlparse(self.path)
205
+ if self.command == "GET" and url.path == "/health":
206
+ return self._health()
207
+ if self.command == "GET" and url.path.startswith("/_queue/"):
208
+ return self._own(url)
209
+ try:
210
+ length = int(self.headers.get("Content-Length") or 0)
211
+ except ValueError:
212
+ return self._send(400, {"error": "Content-Length is not a number", "source": "client"})
213
+ body = self.rfile.read(length) if length > 0 else b""
214
+ call_id = None
215
+ if self.command == "POST": # stage 10: received
216
+ at, peer = self._door["at"], self.client_address[0]
217
+ call_id = store.write(lambda conn: calls.received(conn, at, url.path, calls.fields(body), peer, body))
218
+ self._door["call_id"] = call_id
219
+ self._hand(body, call_id)
220
+
221
+ do_GET = do_POST = do_PUT = do_PATCH = do_DELETE = do_OPTIONS = do_HEAD = _pass
222
+
223
+ def _hand(self, body: bytes, call_id) -> None:
224
+ """Hand the request to the wrapper and pass its answer back as it comes."""
225
+ target = urlparse(self.server.wrapper_url)
226
+ headers = {name: value for name, value in self.headers.items() if name.lower() not in HOP_HEADERS}
227
+ headers["Connection"] = "close"
228
+ if body or self.command in ("POST", "PUT", "PATCH"):
229
+ headers["Content-Length"] = str(len(body))
230
+ if not _this_box(self.client_address[0]):
231
+ prior = self.headers.get("X-Forwarded-For")
232
+ headers["X-Forwarded-For"] = (prior + ", " if prior else "") + self.client_address[0]
233
+ sent = time.time()
234
+ if call_id:
235
+ headers["X-Hugpy-Queue-Call"] = str(call_id)
236
+ store.write(lambda conn: calls.handed(conn, call_id, "wrapper", sent, HANDED_NOTE), wait=False)
237
+ upstream = http.client.HTTPConnection(target.hostname, target.port or 80, timeout=None if call_id else 120)
238
+ try:
239
+ upstream.request(self.command, self.path, body=body or None, headers=headers)
240
+ answer = upstream.getresponse()
241
+ except (OSError, http.client.HTTPException) as exc:
242
+ upstream.close()
243
+ failed, said = time.time(), f"the wrapper at {self.server.wrapper_url} could not be reached: {exc}"
244
+ if call_id:
245
+ store.write(lambda conn: calls.answered(conn, call_id, failed, 502, None, said), wait=False)
246
+ self._send(502, {"error": said, "source": "queue"})
247
+ if call_id:
248
+ store.write(lambda conn: calls.responded(conn, call_id, failed, time.time(), self._door["out"], None),
249
+ wait=False)
250
+ return
251
+ answered = time.time()
252
+ if call_id:
253
+ status, ref = answer.status, answer.getheader("X-Hugpy-Execution-Request-Id")
254
+ store.write(lambda conn: calls.answered(conn, call_id, answered, status, ref, None), wait=False)
255
+ out, back, error, length = 0, 0, None, None
256
+ try:
257
+ self.send_response(answer.status)
258
+ for name, value in answer.getheaders():
259
+ if name.lower() not in HOP_HEADERS and name.lower() not in ("server", "date"):
260
+ self.send_header(name, value)
261
+ length = answer.getheader("Content-Length")
262
+ if length is not None:
263
+ self.send_header("Content-Length", length)
264
+ else: # a reply of no stated length ends when the connection does
265
+ self.send_header("Connection", "close")
266
+ self.close_connection = True
267
+ self.end_headers()
268
+ if self.command != "HEAD":
269
+ while True:
270
+ piece = answer.read1(65536)
271
+ if not piece:
272
+ break
273
+ back += len(piece)
274
+ self.wfile.write(piece)
275
+ self.wfile.flush()
276
+ out += len(piece)
277
+ except OSError:
278
+ error, self.close_connection = "the caller had gone before the reply was written", True
279
+ except http.client.HTTPException as exc:
280
+ error, self.close_connection = f"the wrapper's answer broke off: {exc}", True
281
+ finally:
282
+ upstream.close()
283
+ self._door["out"] = out
284
+ if call_id: # received, sent out, got back, replied: was all of it delivered
285
+ whole = length is None or (length.isdigit() and back == int(length))
286
+ verified = int(error is None and whole and out == back)
287
+ store.write(lambda conn: calls.responded(conn, call_id, answered, time.time(), out, error, back, verified),
288
+ wait=False)
289
+
290
+
291
+ def serve() -> int:
292
+ """The door, until the process is stopped."""
293
+ left = store.write(calls.left_from_before)
294
+ found = store.settings()
295
+ server = ThreadingHTTPServer((found["host"], int(found["port"])), Handler)
296
+ server.daemon_threads = True
297
+ server.wrapper_url = found["wrapper_url"].rstrip("/")
298
+ print(f"{TOOL} {tool_version('hugpy_queue', __file__)}: the door at http://{found['host']}:{found['port']}, "
299
+ f"calls handed to the wrapper at {server.wrapper_url}"
300
+ + (f"; {left} call(s) of a process before this one marked as ended with it" if left else ""), flush=True)
301
+ try:
302
+ server.serve_forever()
303
+ except KeyboardInterrupt:
304
+ pass
305
+ return 0
@@ -0,0 +1,37 @@
1
+ """The one import hub: the standard library, the shared functions (hugpy_utilities) and this tool's constants."""
2
+ import argparse
3
+ import http.client
4
+ import json
5
+ import os
6
+ import queue
7
+ import sqlite3
8
+ import sys
9
+ import threading
10
+ import time
11
+ from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
12
+ from pathlib import Path
13
+ from urllib.parse import parse_qs, urlparse
14
+
15
+ from hugpy_utilities import (
16
+ HOST_DATA_DIR,
17
+ HOST_GROUP,
18
+ SHARED_FOLDER_MODE,
19
+ connect_wal,
20
+ data_folder_refusal,
21
+ ensure_account,
22
+ ensure_folder,
23
+ ensure_group,
24
+ ensure_member,
25
+ remove_unit,
26
+ service_interpreter,
27
+ share_folder,
28
+ share_new_files,
29
+ start_unit,
30
+ system_say,
31
+ systemctl,
32
+ tool_version,
33
+ unit_state,
34
+ write_unit,
35
+ )
36
+
37
+ from .constants import * # noqa: F401,F403
@@ -0,0 +1,47 @@
1
+ """Names, places and the operator's order of stages."""
2
+ import os
3
+
4
+ TOOL = "hugpy-queue"
5
+ MODULE = "hugpy_queue"
6
+ SERVICE = "hugpy-queue" # what this door's /health says it is: a worker's queue, under its own name
7
+ ENV_PREFIX = "HUGPY_QUEUE_" # its own keys, never another tool's
8
+
9
+ # every hugpy tool of a host keeps its folder under one data directory (the service is started with it)
10
+ DATA_DIR = os.environ.get("HUGPY_DATA_DIR") or os.path.join(os.path.expanduser("~"), ".local", "share", "hugpy")
11
+ FOLDER = os.environ.get(ENV_PREFIX + "STATE") or os.path.join(DATA_DIR, "queue")
12
+ QUEUE_DB = os.path.join(FOLDER, "queue.sqlite3")
13
+
14
+ SERVICE_ACCOUNT = TOOL
15
+ SERVICE_UNIT = TOOL + ".service"
16
+ SERVICE_BACKUPS = "/var/backups/" + TOOL
17
+
18
+ # settings a person may change (table `settings`; `hugpy-queue set NAME VALUE`), and what holds until one does
19
+ DEFAULTS = {
20
+ "host": "127.0.0.1", # the door listens here
21
+ "port": "15203",
22
+ "wrapper_url": "http://127.0.0.1:15202", # where a call is handed while the wrapper still does stages 20 to 90
23
+ }
24
+
25
+ # The operator's order (KNOWN_GOOD/DOCS/FLOWCHART, 2026-11-04): sorting only predicts, running acts, strictly in order.
26
+ # (stage_no, stage, the part that owns it, phase, what it is)
27
+ STAGE_ORDER = (
28
+ (10, "received", "queue", "sort", "recorded: what it is"),
29
+ (20, "engine_range", "engine", "sort", "time-to-processed range from tokens in and out; impossible placements out"),
30
+ (30, "reap_prediction", "discovery", "sort", "seconds to place the model on a worker drive"),
31
+ (40, "evict_prediction", "resources", "sort", "seconds to make room in memory; finishes the sort"),
32
+ (50, "turn", "queue", "run", "this row is next"),
33
+ (60, "accommodate", "discovery", "run", "the model placed on a worker drive"),
34
+ (70, "evict", "resources", "run", "room made"),
35
+ (80, "load", "resources", "run", "the engine loads"),
36
+ (90, "intake", "engine", "run", "the engine takes the call"),
37
+ (100, "done", "queue", "run", "answered"),
38
+ (110, "responded", "queue", "run", "the reply written to the caller"),
39
+ )
40
+
41
+ # An answered read keeps its own row this long; then it is counted into its hour and the row removed
42
+ # (operator 2026-12-03: "deffinately take whats needed and remove as often as possible").
43
+ DOOR_READ_KEEP_S = 120.0
44
+
45
+ # headers that belong to one connection and are never passed on
46
+ HOP_HEADERS = frozenset(("connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "te", "trailer",
47
+ "transfer-encoding", "upgrade", "host", "content-length"))