hugpy-queue 0.1.1.3__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.
Potentially problematic release.
This version of hugpy-queue might be problematic. Click here for more details.
- hugpy_queue/__init__.py +1 -0
- hugpy_queue/__main__.py +5 -0
- hugpy_queue/calls.py +70 -0
- hugpy_queue/cli.py +81 -0
- hugpy_queue/core_sql.py +62 -0
- hugpy_queue/door.py +305 -0
- hugpy_queue/imports/__init__.py +37 -0
- hugpy_queue/imports/constants.py +47 -0
- hugpy_queue/rows.py +205 -0
- hugpy_queue/store.py +166 -0
- hugpy_queue/system/__init__.py +19 -0
- hugpy_queue/system/system.py +170 -0
- hugpy_queue-0.1.1.3.dist-info/METADATA +34 -0
- hugpy_queue-0.1.1.3.dist-info/RECORD +17 -0
- hugpy_queue-0.1.1.3.dist-info/WHEEL +5 -0
- hugpy_queue-0.1.1.3.dist-info/entry_points.txt +2 -0
- hugpy_queue-0.1.1.3.dist-info/top_level.txt +1 -0
hugpy_queue/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""hugpy-queue: the queue as a part of its own (see README.md)."""
|
hugpy_queue/__main__.py
ADDED
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)")
|
hugpy_queue/core_sql.py
ADDED
|
@@ -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"))
|
hugpy_queue/rows.py
ADDED
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
"""A call's own row as the run keeps it, and the rows of its stages: brought here from the wrapper (2026-12-03).
|
|
2
|
+
|
|
3
|
+
The operator, 2026-12-03: the queue "is the actual component that is responsible for the calls". Until this move the
|
|
4
|
+
text of these tables and every statement that writes a call's row lived in hugpy-resources (`sql/statements.py`,
|
|
5
|
+
`sql/wrapper.py`, `queue/rows.py`, `queue/run.py`, `queue/telemetry.py`). They are here now, unchanged in what they
|
|
6
|
+
do, and the wrapper calls them.
|
|
7
|
+
|
|
8
|
+
Every function takes the connection it is to write on. Today that is the wrapper's database (wrapper.sqlite3), where
|
|
9
|
+
the tables `queue` and `call_stages` still are: the wrapper's process makes the launch and writes the call's row as it
|
|
10
|
+
goes. These are NOT the door's tables of queue.sqlite3 (`calls`, and a `call_stages` keyed by call_id: store.py),
|
|
11
|
+
and `QUEUE_TABLE` / `CALL_STAGES_TABLE` must not be run on that file while the two shapes are apart.
|
|
12
|
+
|
|
13
|
+
What stays with whoever calls: trying a write again while the database is locked, and waking its own run loop after
|
|
14
|
+
a write. Both belong to the process that holds the connection, so they are handed in (`retry`, `changed`) or done
|
|
15
|
+
around the call; nothing here waits on anything.
|
|
16
|
+
"""
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
from .imports import json, sqlite3, sys, time
|
|
20
|
+
|
|
21
|
+
TERMINAL = ("done", "failed", "cancelled")
|
|
22
|
+
|
|
23
|
+
# The call's row. (hugpy-resources sql/statements.py, in WRAPPER_SCHEMA.)
|
|
24
|
+
QUEUE_TABLE = """
|
|
25
|
+
CREATE TABLE IF NOT EXISTS queue (
|
|
26
|
+
id INTEGER PRIMARY KEY, arrived_at REAL, model TEXT, key TEXT, variation TEXT, engine TEXT,
|
|
27
|
+
body TEXT, tokens_in INTEGER, tokens_out_hi INTEGER, endpoint TEXT,
|
|
28
|
+
state TEXT, -- waiting | turn | done | failed
|
|
29
|
+
-- the predictions, saved once at dispatch to compare with what happened
|
|
30
|
+
p_gpu_bytes INTEGER, p_ram_bytes INTEGER, p_swap_bytes INTEGER, p_disk_bytes INTEGER,
|
|
31
|
+
p_engine_lo_s REAL, p_engine_hi_s REAL, p_reap_s REAL, p_evict_s REAL, p_load_s REAL, p_eta_s REAL,
|
|
32
|
+
p_ready_s REAL, p_base_ms REAL, p_reads_gpu_bytes INTEGER, p_kappa REAL,
|
|
33
|
+
-- what happened
|
|
34
|
+
turn_at REAL, accommodated_at REAL, loaded_at REAL, done_at REAL, load_run INTEGER,
|
|
35
|
+
tokens_out INTEGER, prompt_ms REAL, decode_ms REAL, response TEXT, error TEXT,
|
|
36
|
+
-- the nested co-load group a waiting call joined on arrival (queue/groups: assigned by a co-load query
|
|
37
|
+
-- against the groups' lower bounds), so group priority is a column the admission read orders by, not Python state
|
|
38
|
+
group_id INTEGER, cpu_preempted_at REAL
|
|
39
|
+
);
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
QUEUE_INDEXES = """
|
|
43
|
+
CREATE INDEX IF NOT EXISTS queue_state ON queue(state);
|
|
44
|
+
CREATE INDEX IF NOT EXISTS queue_unit ON queue(key, variation, state);
|
|
45
|
+
"""
|
|
46
|
+
|
|
47
|
+
# one row per finished stage of a call, in the order they finished (STAGE_ORDER names; DISCOVERIES 12): the sort's
|
|
48
|
+
# predictions as the row arrives, then each step of the run with when it started and ended. Written once, never
|
|
49
|
+
# changed, so core follows it by row id (the wrapper's queue/telemetry.py).
|
|
50
|
+
CALL_STAGES_TABLE = """
|
|
51
|
+
CREATE TABLE IF NOT EXISTS call_stages (
|
|
52
|
+
id INTEGER PRIMARY KEY, queue_id INTEGER NOT NULL, stage TEXT NOT NULL, started_at REAL, finished_at REAL,
|
|
53
|
+
predicted_s REAL, note TEXT
|
|
54
|
+
);
|
|
55
|
+
CREATE INDEX IF NOT EXISTS call_stages_queue ON call_stages(queue_id);
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
# Columns the call's row gained after its table was first made: added to a database that lacks them.
|
|
59
|
+
# (hugpy-resources sql/wrapper.py, the "queue" entry of its column loop.)
|
|
60
|
+
QUEUE_COLUMNS = (
|
|
61
|
+
("p_ready_s", "REAL"), ("p_base_ms", "REAL"), ("p_reads_gpu_bytes", "INTEGER"),
|
|
62
|
+
("p_kappa", "REAL"), ("endpoint", "TEXT"), ("p_reload_s", "REAL"), ("cancel_requested_at", "REAL"),
|
|
63
|
+
("cpu_preempted_at", "REAL"),
|
|
64
|
+
# a failed row: the step it failed at, who failed (client | wrapper | wrapper-internal | discovery | engine),
|
|
65
|
+
# and the engine's own HTTP status
|
|
66
|
+
("error_stage", "TEXT"), ("error_source", "TEXT"), ("error_status", "INTEGER"),
|
|
67
|
+
("resolved", "TEXT"),
|
|
68
|
+
# the output-length range the prediction used, and how the call ended
|
|
69
|
+
("p_tokens_out_lo", "INTEGER"), ("p_tokens_out_hi", "INTEGER"),
|
|
70
|
+
("p_tokens_out", "INTEGER"), ("finish_reason", "TEXT"),
|
|
71
|
+
# its place in the queue's plan at dispatch, and the capacity rows ahead of it
|
|
72
|
+
("p_position", "INTEGER"), ("p_capacity", "TEXT"),
|
|
73
|
+
# the id a caller sent with the call (core's request id): cancel and retry by it
|
|
74
|
+
("parent_request_id", "TEXT"),
|
|
75
|
+
("env", "TEXT"), # JSON: the env the unit was judged against, its status
|
|
76
|
+
# the input's bound on the fit (the wrapper's resources/fit.bounds_of): {start, only}, no names
|
|
77
|
+
("tier_bounds", "TEXT"),
|
|
78
|
+
# what the row is doing now, said plainly (shown while it is at its turn)
|
|
79
|
+
("doing", "TEXT"),
|
|
80
|
+
# the nested co-load group the waiting call joined on arrival: group priority is a column the admission read
|
|
81
|
+
# orders by, not Python state
|
|
82
|
+
("group_id", "INTEGER"),
|
|
83
|
+
# its plan as admission made it, before its load starts: the context and KV the fit chose and where the KV goes,
|
|
84
|
+
# and everything it will take: on the card (its weights there, its KV when there, its engine's own room) and in
|
|
85
|
+
# host memory. p_gpu_bytes .. p_disk_bytes are the weights alone, per tier.
|
|
86
|
+
("p_ctx", "INTEGER"), ("p_kv_bytes", "INTEGER"), ("p_kv_tier", "TEXT"),
|
|
87
|
+
("p_engine_bytes", "INTEGER"), ("p_card_bytes", "INTEGER"), ("p_host_bytes", "INTEGER"),
|
|
88
|
+
# the KV is a range until the call is offered its turn: the least and the most its column keeps on that
|
|
89
|
+
# resource. p_ctx / p_kv_bytes are set only then, sized into the room the offer leaves it, up to the most.
|
|
90
|
+
("p_ctx_min", "INTEGER"), ("p_kv_min_bytes", "INTEGER"),
|
|
91
|
+
("p_ctx_max", "INTEGER"), ("p_kv_max_bytes", "INTEGER"),
|
|
92
|
+
)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def tokens_in_estimate(body: dict) -> int:
|
|
96
|
+
"""Tokens in before any engine holds a tokenizer: characters / 4 (the actual count is recorded after)."""
|
|
97
|
+
chars = 0
|
|
98
|
+
for m in body.get("messages") or []:
|
|
99
|
+
c = m.get("content")
|
|
100
|
+
if isinstance(c, list):
|
|
101
|
+
c = " ".join(p.get("text", "") for p in c if isinstance(p, dict))
|
|
102
|
+
chars += len(c or "")
|
|
103
|
+
return max(1, chars // 4)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def stage(conn: sqlite3.Connection, queue_id: int, name: str, started: float, finished: float,
|
|
107
|
+
predicted: float = None, note: str = None) -> None:
|
|
108
|
+
"""One finished stage of a call (call_stages). Recording a stage must never fail the call: a database error
|
|
109
|
+
here is reported on stderr and the run carries on."""
|
|
110
|
+
try:
|
|
111
|
+
with conn:
|
|
112
|
+
conn.execute("INSERT INTO call_stages (queue_id, stage, started_at, finished_at, predicted_s, note) "
|
|
113
|
+
"VALUES (?,?,?,?,?,?)", (queue_id, name, started, finished, predicted, (note or None) and str(note)[:1000]))
|
|
114
|
+
except sqlite3.Error as exc:
|
|
115
|
+
# `module` names the process that writes these rows today, as its journal has always had it
|
|
116
|
+
print(json.dumps(dict(ts=time.time(), module="test-wrapper", level="warning", event="call_stage.failed",
|
|
117
|
+
ids=dict(queue_id=queue_id, stage=name), error=f"{type(exc).__name__}: {exc}")),
|
|
118
|
+
file=sys.stderr, flush=True)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def arrived(conn: sqlite3.Connection, body: dict, endpoint: str, unit: dict, env, bounds, tokens_in: int,
|
|
122
|
+
tokens_out_hi: int, parent_request_id: str = None, retry=None, changed=None) -> int:
|
|
123
|
+
"""A call arrives (stage 10): its row is written, waiting, and its `received` stage. Returns the row's id.
|
|
124
|
+
|
|
125
|
+
`unit` is the unit the call was resolved to (key, variation, engine, and `resolved` when a name matched several);
|
|
126
|
+
`env` and `bounds` are kept as JSON when there are any. The row is inserted cheaply: no fit, no plan. Its
|
|
127
|
+
predictions are left unset and derived later from the database, so many calls arriving at once each cost one
|
|
128
|
+
indexed insert. `retry(fn)` is the caller's way of trying a write again on a lock that passes, so a queued call is
|
|
129
|
+
never lost to it; `changed()` is called once the row is committed (the caller's run loop plans it)."""
|
|
130
|
+
def _insert():
|
|
131
|
+
with conn:
|
|
132
|
+
return conn.execute(
|
|
133
|
+
"INSERT INTO queue (arrived_at, model, key, variation, engine, body, tokens_in, tokens_out_hi, "
|
|
134
|
+
"state, endpoint, resolved, env, tier_bounds) VALUES (?,?,?,?,?,?,?,?,'waiting',?,?,?,?)",
|
|
135
|
+
(time.time(), body.get("model"), unit["key"], unit["variation"], unit["engine"], json.dumps(body),
|
|
136
|
+
tokens_in, tokens_out_hi, endpoint, json.dumps(unit["resolved"]) if unit.get("resolved") else None,
|
|
137
|
+
json.dumps(env) if env else None, json.dumps(bounds) if bounds else None)).lastrowid
|
|
138
|
+
rid = retry(_insert) if retry else _insert()
|
|
139
|
+
if changed:
|
|
140
|
+
changed()
|
|
141
|
+
now = time.time()
|
|
142
|
+
if parent_request_id:
|
|
143
|
+
with conn:
|
|
144
|
+
conn.execute("UPDATE queue SET parent_request_id = ? WHERE id = ?", (str(parent_request_id)[:200], rid))
|
|
145
|
+
stage(conn, rid, "received", now, now)
|
|
146
|
+
return rid
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def mark(conn: sqlite3.Connection, row_id: int, **cols) -> None:
|
|
150
|
+
"""Write columns of a call's row, in one transaction. (The wrapper's run._mark tries it again on a lock and wakes
|
|
151
|
+
its run loop after: both stay with it.)"""
|
|
152
|
+
sets = ", ".join(f"{k} = ?" for k in cols)
|
|
153
|
+
with conn:
|
|
154
|
+
conn.execute(f"UPDATE queue SET {sets} WHERE id = ?", (*cols.values(), row_id))
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
class Cancelled(Exception):
|
|
158
|
+
"""A client cancelled the row (DELETE /v1/queue/{id}); the run stops at the next step boundary."""
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def cancel_requested(conn: sqlite3.Connection, row_id: int) -> bool:
|
|
162
|
+
at = conn.execute("SELECT cancel_requested_at FROM queue WHERE id = ?", (row_id,)).fetchone()
|
|
163
|
+
return bool(at and at[0])
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def check_cancel(conn: sqlite3.Connection, row_id: int) -> None:
|
|
167
|
+
if cancel_requested(conn, row_id):
|
|
168
|
+
raise Cancelled("cancelled by client (at a step boundary; what was done stays done)")
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def cancel_row(conn: sqlite3.Connection, row_id: int, now: float) -> tuple:
|
|
172
|
+
"""The row's part of a cancel, to be run inside the caller's transaction (and under its claim lock): a waiting
|
|
173
|
+
row is cancelled at once; one at its turn is marked as asked to stop. Returns (state, loaded_at, at_once):
|
|
174
|
+
the row's state after this, when it was loaded if it was, and whether it was cancelled here before its turn.
|
|
175
|
+
What is then done to an engine that is loading or answering for it is not the row's and stays with the caller."""
|
|
176
|
+
row = conn.execute("SELECT state, loaded_at FROM queue WHERE id = ?", (row_id,)).fetchone()
|
|
177
|
+
if not row:
|
|
178
|
+
raise LookupError(f"no queue row {row_id}")
|
|
179
|
+
state, loaded = row
|
|
180
|
+
if state == "waiting":
|
|
181
|
+
n = conn.execute("UPDATE queue SET state = 'cancelled', done_at = ?, cancel_requested_at = ?, "
|
|
182
|
+
"error = 'cancelled by client before its turn' WHERE id = ? AND state = 'waiting'",
|
|
183
|
+
(now, now, row_id)).rowcount
|
|
184
|
+
if n:
|
|
185
|
+
return "cancelled", loaded, True
|
|
186
|
+
state = conn.execute("SELECT state FROM queue WHERE id = ?", (row_id,)).fetchone()[0]
|
|
187
|
+
if state == "turn":
|
|
188
|
+
conn.execute("UPDATE queue SET cancel_requested_at = ? WHERE id = ? AND state = 'turn'", (now, row_id))
|
|
189
|
+
return state, loaded, False
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def request_id(sid: str, queue_id: int) -> str:
|
|
193
|
+
"""A call's stable id on the store `sid`: core keys call_log by it."""
|
|
194
|
+
return f"hw-{sid[:12]}-{queue_id}"
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def queue_id_of(conn: sqlite3.Connection, rid: str, sid: str):
|
|
198
|
+
"""The queue row a request id names: the store's own id for it (`sid` is that store's identity), or the id a
|
|
199
|
+
caller sent with the call (Idempotency-Key / X-Hugpy-Parent-Request-Id). None when it names none."""
|
|
200
|
+
prefix = f"hw-{sid[:12]}-"
|
|
201
|
+
if rid.startswith(prefix) and rid[len(prefix):].isdigit():
|
|
202
|
+
r = conn.execute("SELECT id FROM queue WHERE id = ?", (int(rid[len(prefix):]),)).fetchone()
|
|
203
|
+
return r[0] if r else None
|
|
204
|
+
r = conn.execute("SELECT id FROM queue WHERE parent_request_id = ? ORDER BY id DESC LIMIT 1", (rid,)).fetchone()
|
|
205
|
+
return r[0] if r else None
|
hugpy_queue/store.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""The queue's own database: queue.sqlite3, written by ONE thread of this process and by nothing else.
|
|
2
|
+
|
|
3
|
+
Every write goes through `write(fn)`: the function is run on the writer thread with the one writing connection, in a
|
|
4
|
+
transaction. A door thread that needs what was written (the id of a call's row) waits for it; a record nobody waits
|
|
5
|
+
on (a door row, a count) is handed over and left. Anything may read (`reader()`: a read-only connection).
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from .imports import DEFAULTS, QUEUE_DB, STAGE_ORDER, connect_wal, os, queue, sqlite3, threading, time
|
|
10
|
+
|
|
11
|
+
SCHEMA = """
|
|
12
|
+
CREATE TABLE IF NOT EXISTS settings (name TEXT PRIMARY KEY, value TEXT NOT NULL, by TEXT, at REAL);
|
|
13
|
+
-- The operator's order as data: a stage's number, its name, the part that owns it, and whether it predicts or acts.
|
|
14
|
+
CREATE TABLE IF NOT EXISTS stage_order (
|
|
15
|
+
stage_no INTEGER PRIMARY KEY, stage TEXT NOT NULL UNIQUE, owner TEXT NOT NULL, phase TEXT NOT NULL, what TEXT
|
|
16
|
+
);
|
|
17
|
+
-- A call: what it is and has. One row for every POST at the door, written when it arrives. `body` is held only
|
|
18
|
+
-- while the call is in flight (it is what each owner is handed) and removed when the call ends.
|
|
19
|
+
CREATE TABLE IF NOT EXISTS calls (
|
|
20
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
21
|
+
arrived_at REAL NOT NULL,
|
|
22
|
+
endpoint TEXT NOT NULL,
|
|
23
|
+
model TEXT, -- as the caller named it
|
|
24
|
+
stream INTEGER,
|
|
25
|
+
max_tokens INTEGER,
|
|
26
|
+
caller TEXT,
|
|
27
|
+
bytes_in INTEGER,
|
|
28
|
+
body BLOB,
|
|
29
|
+
state TEXT NOT NULL DEFAULT 'received', -- received | handed | done | failed
|
|
30
|
+
kind TEXT, -- call: the part it was handed to took it into its queue; refused: it would
|
|
31
|
+
-- not (status 400 and over); command: answered without being queued
|
|
32
|
+
handed_to TEXT, -- the part holding it now, or last
|
|
33
|
+
handed_ref TEXT, -- the id that part knows it by
|
|
34
|
+
status INTEGER, -- the HTTP status it was answered with
|
|
35
|
+
bytes_out INTEGER,
|
|
36
|
+
done_at REAL,
|
|
37
|
+
responded_at REAL,
|
|
38
|
+
error TEXT,
|
|
39
|
+
bytes_back INTEGER, -- what came back from the part it was handed to
|
|
40
|
+
verified INTEGER -- 1: all that part said it would send came back and all of it reached the caller
|
|
41
|
+
);
|
|
42
|
+
CREATE INDEX IF NOT EXISTS calls_state ON calls(state);
|
|
43
|
+
-- A row for each stage a call passes: when it began and ended, and the part that did it. `stage_no` is its number
|
|
44
|
+
-- in stage_order; NULL for `handed`, the hand-off of several stages at once to a part that still does them itself.
|
|
45
|
+
CREATE TABLE IF NOT EXISTS call_stages (
|
|
46
|
+
id INTEGER PRIMARY KEY, call_id INTEGER NOT NULL, stage_no INTEGER, stage TEXT NOT NULL, owner TEXT NOT NULL,
|
|
47
|
+
started_at REAL NOT NULL, finished_at REAL, note TEXT
|
|
48
|
+
);
|
|
49
|
+
CREATE INDEX IF NOT EXISTS call_stages_call ON call_stages(call_id);
|
|
50
|
+
-- Every request that reaches the door, of any kind (operator 2026-12-03: "anything that hits the front door should
|
|
51
|
+
-- be on record"): when, how long until its reply was written, what was asked, the status, bytes each way, who.
|
|
52
|
+
CREATE TABLE IF NOT EXISTS front_door (
|
|
53
|
+
id INTEGER PRIMARY KEY, at REAL NOT NULL, ms REAL, method TEXT, path TEXT, status INTEGER, bytes_in INTEGER,
|
|
54
|
+
bytes_out INTEGER, caller TEXT, call_id INTEGER
|
|
55
|
+
);
|
|
56
|
+
CREATE INDEX IF NOT EXISTS front_door_at ON front_door(at);
|
|
57
|
+
-- What is kept of the routine reads once their own rows are removed: an hour, route, status and caller.
|
|
58
|
+
CREATE TABLE IF NOT EXISTS front_door_hours (
|
|
59
|
+
hour INTEGER NOT NULL, method TEXT NOT NULL, route TEXT NOT NULL, status INTEGER NOT NULL, caller TEXT NOT NULL,
|
|
60
|
+
requests INTEGER NOT NULL, ms REAL, max_ms REAL, bytes_out INTEGER, first_at REAL, last_at REAL,
|
|
61
|
+
PRIMARY KEY (hour, method, route, status, caller)
|
|
62
|
+
);
|
|
63
|
+
-- Derived, not stored.
|
|
64
|
+
DROP VIEW IF EXISTS front_door_routes;
|
|
65
|
+
CREATE VIEW front_door_routes AS
|
|
66
|
+
SELECT method, route, status, SUM(requests) AS requests, SUM(ms) / SUM(requests) AS avg_ms, MAX(max_ms) AS max_ms,
|
|
67
|
+
SUM(bytes_out) AS bytes_out, MIN(first_at) AS first_at, MAX(last_at) AS last_at
|
|
68
|
+
FROM (SELECT method, CASE WHEN instr(path, '?') THEN substr(path, 1, instr(path, '?') - 1) ELSE path END AS route,
|
|
69
|
+
status, 1 AS requests, ms, ms AS max_ms, bytes_out, at AS first_at, at AS last_at FROM front_door
|
|
70
|
+
UNION ALL
|
|
71
|
+
SELECT method, route, status, requests, ms, max_ms, bytes_out, first_at, last_at FROM front_door_hours)
|
|
72
|
+
GROUP BY method, route, status;
|
|
73
|
+
DROP VIEW IF EXISTS call_times;
|
|
74
|
+
CREATE VIEW call_times AS
|
|
75
|
+
SELECT c.id, c.kind, c.endpoint, c.model, c.state, c.status, c.verified, c.bytes_back, c.bytes_out,
|
|
76
|
+
c.handed_to, c.handed_ref, c.arrived_at,
|
|
77
|
+
h.started_at AS handed_at, c.done_at, c.responded_at,
|
|
78
|
+
h.started_at - c.arrived_at AS held_s, -- in the queue's own hands before the hand-off
|
|
79
|
+
h.finished_at - h.started_at AS handed_s, -- with the part it was handed to, until its answer began
|
|
80
|
+
c.responded_at - h.finished_at AS reply_s, -- the answer passed back to the caller
|
|
81
|
+
c.responded_at - c.arrived_at AS total_s
|
|
82
|
+
FROM calls c LEFT JOIN call_stages h ON h.call_id = c.id AND h.stage = 'handed';
|
|
83
|
+
"""
|
|
84
|
+
|
|
85
|
+
_JOBS = queue.Queue()
|
|
86
|
+
_STARTED = []
|
|
87
|
+
_LOCK = threading.Lock()
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def open_db(path: str = QUEUE_DB) -> sqlite3.Connection:
|
|
91
|
+
"""The writing connection: the tables made, the operator's order written as this source has it."""
|
|
92
|
+
os.makedirs(os.path.dirname(path), exist_ok=True)
|
|
93
|
+
conn = connect_wal(path)
|
|
94
|
+
have = {row[1] for row in conn.execute("PRAGMA table_info(calls)")}
|
|
95
|
+
for column in ("bytes_back INTEGER", "verified INTEGER"): # a database made before these were kept
|
|
96
|
+
if have and column.split()[0] not in have:
|
|
97
|
+
conn.execute(f"ALTER TABLE calls ADD COLUMN {column}")
|
|
98
|
+
conn.executescript(SCHEMA)
|
|
99
|
+
with conn:
|
|
100
|
+
conn.execute("DELETE FROM stage_order")
|
|
101
|
+
conn.executemany("INSERT INTO stage_order VALUES (?,?,?,?,?)", STAGE_ORDER)
|
|
102
|
+
return conn
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def reader(path: str = QUEUE_DB) -> sqlite3.Connection:
|
|
106
|
+
conn = sqlite3.connect(f"file:{path}?mode=ro", uri=True, timeout=5)
|
|
107
|
+
conn.row_factory = sqlite3.Row
|
|
108
|
+
return conn
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def _write_loop(path: str) -> None:
|
|
112
|
+
conn = open_db(path)
|
|
113
|
+
while True:
|
|
114
|
+
fn, done = _JOBS.get()
|
|
115
|
+
try:
|
|
116
|
+
with conn:
|
|
117
|
+
value = fn(conn)
|
|
118
|
+
if done is not None:
|
|
119
|
+
done["value"] = value
|
|
120
|
+
except Exception as exc: # noqa: BLE001 — the one who asked is told; the writer goes on
|
|
121
|
+
if done is not None:
|
|
122
|
+
done["error"] = exc
|
|
123
|
+
else:
|
|
124
|
+
print(f"queue.write_failed {type(exc).__name__}: {exc}", flush=True)
|
|
125
|
+
finally:
|
|
126
|
+
if done is not None:
|
|
127
|
+
done["event"].set()
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def write(fn, wait: bool = True, path: str = QUEUE_DB):
|
|
131
|
+
"""Run fn(conn) on the writer thread, in a transaction. wait=True: its value is returned (its error raised)."""
|
|
132
|
+
with _LOCK:
|
|
133
|
+
if not _STARTED:
|
|
134
|
+
_STARTED.append(True)
|
|
135
|
+
threading.Thread(target=_write_loop, args=(path,), daemon=True, name="queue-writer").start()
|
|
136
|
+
done = {"event": threading.Event()} if wait else None
|
|
137
|
+
_JOBS.put((fn, done))
|
|
138
|
+
if not wait:
|
|
139
|
+
return None
|
|
140
|
+
done["event"].wait()
|
|
141
|
+
if "error" in done:
|
|
142
|
+
raise done["error"]
|
|
143
|
+
return done.get("value")
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def settings(conn=None) -> dict:
|
|
147
|
+
"""Every setting: what a person saved, else its default."""
|
|
148
|
+
own = conn is None
|
|
149
|
+
out = dict(DEFAULTS)
|
|
150
|
+
try:
|
|
151
|
+
conn = conn or reader()
|
|
152
|
+
out.update({row[0]: row[1] for row in conn.execute("SELECT name, value FROM settings") if row[0] in DEFAULTS})
|
|
153
|
+
except sqlite3.Error:
|
|
154
|
+
pass # no database yet: the defaults hold
|
|
155
|
+
finally:
|
|
156
|
+
if own and conn is not None:
|
|
157
|
+
conn.close()
|
|
158
|
+
return out
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def save_setting(name: str, value: str, by: str) -> None:
|
|
162
|
+
if name not in DEFAULTS:
|
|
163
|
+
raise KeyError(f"{name}: not a setting ({', '.join(DEFAULTS)})")
|
|
164
|
+
write(lambda conn: conn.execute("INSERT INTO settings VALUES (?,?,?,?) ON CONFLICT(name) DO UPDATE SET "
|
|
165
|
+
"value = excluded.value, by = excluded.by, at = excluded.at",
|
|
166
|
+
(name, str(value), by, time.time())))
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"""The system layer: `hugpy-queue system install | status | uninstall` (system.py).
|
|
2
|
+
|
|
3
|
+
A system command speaks of the service, so it runs with the host's data directory (HUGPY_DATA_DIR=/var/lib/hugpy),
|
|
4
|
+
where the service's database is. A command started without it starts itself again with it (the constants read the
|
|
5
|
+
data directory once, when they are loaded)."""
|
|
6
|
+
from ..imports import HOST_DATA_DIR, os, sys
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def main(argv=None, given=None) -> int:
|
|
10
|
+
"""``given`` is HUGPY_DATA_DIR as this process was started with it."""
|
|
11
|
+
argv = sys.argv[1:] if argv is None else list(argv)
|
|
12
|
+
if given != HOST_DATA_DIR:
|
|
13
|
+
os.execve(sys.executable, [sys.executable, "-P", "-m", "hugpy_queue", "system", *argv],
|
|
14
|
+
dict(os.environ, HUGPY_DATA_DIR=HOST_DATA_DIR))
|
|
15
|
+
from .system import main as run
|
|
16
|
+
return run(argv)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
__all__ = ["main"]
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
"""`hugpy-queue system install | status | uninstall`: the queue as a service of the host.
|
|
2
|
+
|
|
3
|
+
install (as root) lays down, saying each step:
|
|
4
|
+
the group hugpy, and in it the person who ran the install
|
|
5
|
+
the account hugpy-queue (it runs the door), in the group hugpy
|
|
6
|
+
/var/lib/hugpy/queue queue.sqlite3 (the calls, their stages, the door's record, the settings): shared by
|
|
7
|
+
the group hugpy, so a person at a terminal reads the same record
|
|
8
|
+
hugpy-queue.service the front door
|
|
9
|
+
|
|
10
|
+
This installer acts only on its own unit and its own folder; it never touches another tool's units, and it does not
|
|
11
|
+
change where anything else sends its calls: the door listens on its own port until a person points callers at it.
|
|
12
|
+
"""
|
|
13
|
+
from .. import store
|
|
14
|
+
from ..imports import (
|
|
15
|
+
DEFAULTS,
|
|
16
|
+
FOLDER,
|
|
17
|
+
HOST_DATA_DIR,
|
|
18
|
+
HOST_GROUP,
|
|
19
|
+
QUEUE_DB,
|
|
20
|
+
SERVICE_ACCOUNT,
|
|
21
|
+
SERVICE_BACKUPS,
|
|
22
|
+
SERVICE_UNIT,
|
|
23
|
+
SHARED_FOLDER_MODE,
|
|
24
|
+
TOOL,
|
|
25
|
+
argparse,
|
|
26
|
+
data_folder_refusal,
|
|
27
|
+
ensure_account,
|
|
28
|
+
ensure_folder,
|
|
29
|
+
ensure_group,
|
|
30
|
+
ensure_member,
|
|
31
|
+
os,
|
|
32
|
+
remove_unit,
|
|
33
|
+
service_interpreter,
|
|
34
|
+
share_folder,
|
|
35
|
+
share_new_files,
|
|
36
|
+
sqlite3,
|
|
37
|
+
start_unit,
|
|
38
|
+
system_say,
|
|
39
|
+
systemctl,
|
|
40
|
+
tool_version,
|
|
41
|
+
unit_state,
|
|
42
|
+
write_unit,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
UNIT_TEXT = """[Unit]
|
|
46
|
+
Description=hugpy queue: the front door, every call and the stages it passes (hugpy-queue {version})
|
|
47
|
+
After=network.target local-fs.target
|
|
48
|
+
|
|
49
|
+
[Service]
|
|
50
|
+
Type=simple
|
|
51
|
+
User={account}
|
|
52
|
+
Group={group}
|
|
53
|
+
# what the service makes in its folder is the group's to read and write
|
|
54
|
+
UMask=0002
|
|
55
|
+
# every hugpy tool of this host keeps its folder here
|
|
56
|
+
Environment=HUGPY_DATA_DIR={data}
|
|
57
|
+
Environment=HOME={home}
|
|
58
|
+
Environment=PYTHONUNBUFFERED=1
|
|
59
|
+
UnsetEnvironment=PYTHONPATH
|
|
60
|
+
ExecStart={python} -P -m hugpy_queue serve
|
|
61
|
+
Restart=on-failure
|
|
62
|
+
RestartSec=5
|
|
63
|
+
|
|
64
|
+
[Install]
|
|
65
|
+
WantedBy=multi-user.target
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def version() -> str:
|
|
70
|
+
return tool_version("hugpy_queue", __file__)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def unit_text(python: str) -> str:
|
|
74
|
+
return UNIT_TEXT.format(version=version(), account=SERVICE_ACCOUNT, group=HOST_GROUP, data=HOST_DATA_DIR,
|
|
75
|
+
home=FOLDER, python=python)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def install(args) -> int:
|
|
79
|
+
if os.geteuid() != 0:
|
|
80
|
+
raise SystemExit(f"{TOOL} system install changes /: run it as root (sudo {TOOL} system install)")
|
|
81
|
+
print(f"{TOOL} system install ({version()})", flush=True)
|
|
82
|
+
ensure_group(HOST_GROUP)
|
|
83
|
+
ensure_account(SERVICE_ACCOUNT, FOLDER, (HOST_GROUP,))
|
|
84
|
+
# before anything else is laid down: an install the account cannot run (a venv in a person's home) stops here
|
|
85
|
+
python = service_interpreter(SERVICE_ACCOUNT, "hugpy_queue")
|
|
86
|
+
ensure_folder(FOLDER, SHARED_FOLDER_MODE, SERVICE_ACCOUNT, HOST_GROUP)
|
|
87
|
+
share_folder(FOLDER, HOST_GROUP)
|
|
88
|
+
share_new_files(FOLDER)
|
|
89
|
+
person = args.operator or os.environ.get("SUDO_USER")
|
|
90
|
+
if person and person != "root":
|
|
91
|
+
ensure_member(person, HOST_GROUP)
|
|
92
|
+
store.open_db().close()
|
|
93
|
+
system_say("ok", QUEUE_DB, "the calls, their stages, the door's record and the settings")
|
|
94
|
+
share_folder(FOLDER, HOST_GROUP) # what this run made as root is the group's as well
|
|
95
|
+
write_unit(SERVICE_UNIT, unit_text(python))
|
|
96
|
+
if args.no_start:
|
|
97
|
+
system_say("skip", "start", "--no-start")
|
|
98
|
+
return 0
|
|
99
|
+
started = start_unit(SERVICE_UNIT)
|
|
100
|
+
found = store.settings()
|
|
101
|
+
print(f"\nThe queue's door is at http://{found['host']}:{found['port']} and hands its calls to the wrapper at "
|
|
102
|
+
f"{found['wrapper_url']}.\n {TOOL} calls the latest calls and their stages\n"
|
|
103
|
+
f" journalctl -u {SERVICE_UNIT} -f\n"
|
|
104
|
+
"Nothing else was changed: callers still go where they went until a person points them here.", flush=True)
|
|
105
|
+
return 0 if started in ("active", "activating") else 1
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def status(_args) -> int:
|
|
109
|
+
print(f"{SERVICE_UNIT:<28} {unit_state(SERVICE_UNIT)}")
|
|
110
|
+
print(f"data {FOLDER} ({'present' if os.path.isdir(FOLDER) else f'not made yet: sudo {TOOL} system install'})")
|
|
111
|
+
refusal = data_folder_refusal(FOLDER)
|
|
112
|
+
if refusal:
|
|
113
|
+
print(f"access {refusal}")
|
|
114
|
+
return 1
|
|
115
|
+
if not os.path.isfile(QUEUE_DB):
|
|
116
|
+
return 1
|
|
117
|
+
found = store.settings()
|
|
118
|
+
print(f"door http://{found['host']}:{found['port']}")
|
|
119
|
+
print(f"wrapper {found['wrapper_url']}")
|
|
120
|
+
conn = store.reader()
|
|
121
|
+
try:
|
|
122
|
+
total, flying = conn.execute("SELECT COUNT(*), SUM(state IN ('received','handed')) FROM calls").fetchone()
|
|
123
|
+
print(f"calls {total} on record, {flying or 0} in flight")
|
|
124
|
+
except sqlite3.Error as exc:
|
|
125
|
+
print(f"calls {exc}")
|
|
126
|
+
finally:
|
|
127
|
+
conn.close()
|
|
128
|
+
return 0
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def uninstall(_args) -> int:
|
|
132
|
+
if os.geteuid() != 0:
|
|
133
|
+
raise SystemExit("run as root")
|
|
134
|
+
if not remove_unit(SERVICE_UNIT, SERVICE_BACKUPS):
|
|
135
|
+
system_say("ok", SERVICE_UNIT, "not installed")
|
|
136
|
+
system_say("keep", FOLDER, "the record and the settings are never removed")
|
|
137
|
+
return 0
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def set_one(args) -> int:
|
|
141
|
+
"""`system set NAME VALUE`: save one setting; the service is restarted so that it takes hold at once."""
|
|
142
|
+
if os.geteuid() != 0:
|
|
143
|
+
raise SystemExit(f"{TOOL} system set restarts the service: run it as root (sudo {TOOL} system set NAME VALUE)")
|
|
144
|
+
if args.name not in DEFAULTS:
|
|
145
|
+
raise SystemExit(f"{args.name} is not one of: {', '.join(DEFAULTS)}")
|
|
146
|
+
if store.settings().get(args.name) == args.value:
|
|
147
|
+
system_say("keep", args.name, f"already {args.value}")
|
|
148
|
+
return 0
|
|
149
|
+
store.save_setting(args.name, args.value, by=f"{TOOL} system set")
|
|
150
|
+
share_folder(FOLDER, HOST_GROUP)
|
|
151
|
+
system_say("save", QUEUE_DB, f"{args.name} = {args.value}")
|
|
152
|
+
if systemctl("is-active", SERVICE_UNIT, check=False).stdout.strip() == "active":
|
|
153
|
+
systemctl("restart", SERVICE_UNIT)
|
|
154
|
+
system_say("restart", SERVICE_UNIT, "the setting takes hold now; calls in flight at the door ended with it")
|
|
155
|
+
return 0
|
|
156
|
+
|
|
157
|
+
|
|
158
|
+
def main(argv=None) -> int:
|
|
159
|
+
parser = argparse.ArgumentParser(prog=f"{TOOL} system")
|
|
160
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
161
|
+
p = sub.add_parser("install", help="the account, the shared folder, the database and the door's unit; start")
|
|
162
|
+
p.add_argument("--operator", metavar="USER", help="a person to put in the group hugpy (default: whoever ran this with sudo)")
|
|
163
|
+
p.add_argument("--no-start", action="store_true")
|
|
164
|
+
sub.add_parser("status")
|
|
165
|
+
sub.add_parser("uninstall", help="stop and remove the unit (the record and the settings are kept)")
|
|
166
|
+
one = sub.add_parser("set", help="save one setting (host, port, wrapper_url); the service restarts so it takes hold")
|
|
167
|
+
one.add_argument("name")
|
|
168
|
+
one.add_argument("value")
|
|
169
|
+
args = parser.parse_args(argv)
|
|
170
|
+
return {"install": install, "status": status, "uninstall": uninstall, "set": set_one}[args.command](args)
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: hugpy-queue
|
|
3
|
+
Version: 0.1.1.3
|
|
4
|
+
Summary: The queue: the front door, every call as it is and what it has, and who each of its stages is handed to
|
|
5
|
+
Requires-Python: >=3.11
|
|
6
|
+
Description-Content-Type: text/markdown
|
|
7
|
+
Requires-Dist: hugpy-utilities
|
|
8
|
+
|
|
9
|
+
# hugpy-queue
|
|
10
|
+
|
|
11
|
+
The queue as a part of its own: the fourth of the operator's four parts (Discovery: where it is stored; Resources:
|
|
12
|
+
where it is loaded; Engines: what it is doing and needs; Queue: what it is and has). Until 2026-12-03 its rows lived
|
|
13
|
+
inside the wrapper's database and its code inside the wrapper's process.
|
|
14
|
+
|
|
15
|
+
What it has now:
|
|
16
|
+
|
|
17
|
+
- its own service (`hugpy-queue.service`), account, folder (`/var/lib/hugpy/queue`) and database
|
|
18
|
+
(`queue.sqlite3`), written by one thread of its own process and by nothing else;
|
|
19
|
+
- the front door: every request of any kind is on record (`front_door`; answered reads are counted into
|
|
20
|
+
`front_door_hours` after two minutes and their rows removed);
|
|
21
|
+
- every POST as a row (`calls`: what it is and has) with a row for each stage it passes (`call_stages`);
|
|
22
|
+
- the operator's order of stages as data (`stage_order`: number, stage, the part that owns it, sort or run).
|
|
23
|
+
|
|
24
|
+
What it does not have yet: the sort and the turn. A call is handed to the wrapper whole, and the wrapper still does
|
|
25
|
+
stages 20 to 90 itself; that hand-off is on record as one stage row (`handed`, owner `wrapper`). Each stage moves
|
|
26
|
+
to its owner's door as that door is made.
|
|
27
|
+
|
|
28
|
+
hugpy-queue serve the front door (the service runs this)
|
|
29
|
+
hugpy-queue calls the latest calls and their stages
|
|
30
|
+
hugpy-queue door what is asked of the door, a route
|
|
31
|
+
hugpy-queue settings host, port, the wrapper's address
|
|
32
|
+
hugpy-queue set NAME VALUE save one setting
|
|
33
|
+
sudo hugpy-queue system install | status | uninstall
|
|
34
|
+
sudo hugpy-queue system set NAME VALUE save one setting and restart the service on it
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
hugpy_queue/__init__.py,sha256=9LHH7IG3dtnSBtU9_UTcSs3sbMWtYozImuRzKJwjfK8,67
|
|
2
|
+
hugpy_queue/__main__.py,sha256=E6Gls0DNz8GQK2K-kOUIx8cYhgANW_CH54VKrfCfs14,52
|
|
3
|
+
hugpy_queue/calls.py,sha256=QDnsvUPqe3H_jNpYFVwBlai4jVYGIdI7tnPZkQRbGuQ,4208
|
|
4
|
+
hugpy_queue/cli.py,sha256=3okdEbs2EWZKJ39wBMRz_RApUTqaiM2Mm5v1N1TouzI,3733
|
|
5
|
+
hugpy_queue/core_sql.py,sha256=jn8Uk5NCG99Lql4CENNDFayllez2k2YiiqZTS7lRves,3945
|
|
6
|
+
hugpy_queue/door.py,sha256=5kTUraLQuNmIdo2WjmfawBkO1r2Yzgpf5evhpDMZhsk,14631
|
|
7
|
+
hugpy_queue/rows.py,sha256=BfubjznUj2ZiVZkZyX5Fh-LoavKqz-RDPRcgTtQSvwg,12064
|
|
8
|
+
hugpy_queue/store.py,sha256=UTe0-6-9w0J-90al6d-GWk71G7u7jZBFTDjwfBQDb28,8448
|
|
9
|
+
hugpy_queue/imports/__init__.py,sha256=UtZfvvwZzbY_kwMaKMtr5U-Dv3h8DOfG2xLv-g98Qms,809
|
|
10
|
+
hugpy_queue/imports/constants.py,sha256=FDCiKEZSkIiqIHm3cAmFBzZcMdspgSfsSnVF_mNV3d8,2588
|
|
11
|
+
hugpy_queue/system/__init__.py,sha256=cK9qQLfeRwaPpgz8qUD7bKdKGjfyFVyFN3UbPdC7P7o,850
|
|
12
|
+
hugpy_queue/system/system.py,sha256=9URAY50y30TQfs2TbBKloqxckBs92wlc-6dZkJ6-Db0,6789
|
|
13
|
+
hugpy_queue-0.1.1.3.dist-info/METADATA,sha256=7LsgajOBVaJLn1zftYlHZ8LXYglsWyk29_QeGThvFoA,1926
|
|
14
|
+
hugpy_queue-0.1.1.3.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
15
|
+
hugpy_queue-0.1.1.3.dist-info/entry_points.txt,sha256=GBVHKrLzT38EhWK6tSZh0TrCuKkBgbRBe7h3N8Kv3CY,53
|
|
16
|
+
hugpy_queue-0.1.1.3.dist-info/top_level.txt,sha256=e6Prka6gKyhTrMnm2-HlBmbj4oec2hRB9vew-k3KSPY,12
|
|
17
|
+
hugpy_queue-0.1.1.3.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
hugpy_queue
|