|
| 1 | +"""HTTP shard server: exposes one Memory over JSON so shards run as separate |
| 2 | +processes (recall fan-out then escapes the GIL). |
| 3 | +
|
| 4 | +Security: binds to 127.0.0.1 by default and has NO authentication unless a token |
| 5 | +is configured (``serve(token=...)`` or the ``WOLF_TOKEN`` env var). Do not expose |
| 6 | +to an untrusted network without a token and TLS termination in front. |
| 7 | +""" |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import json |
| 11 | +import os |
| 12 | +import threading |
| 13 | +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 14 | + |
| 15 | +from .engine import Memory |
| 16 | + |
| 17 | + |
| 18 | +def _handler(memory: Memory, token: str | None): |
| 19 | + lock = threading.Lock() # Memory is not internally thread-safe; serialize per server |
| 20 | + |
| 21 | + class Handler(BaseHTTPRequestHandler): |
| 22 | + def _auth_ok(self) -> bool: |
| 23 | + return not token or self.headers.get("Authorization") == f"Bearer {token}" |
| 24 | + |
| 25 | + def _send(self, code: int, obj) -> None: |
| 26 | + body = json.dumps(obj).encode("utf-8") |
| 27 | + self.send_response(code) |
| 28 | + self.send_header("Content-Type", "application/json") |
| 29 | + self.send_header("Content-Length", str(len(body))) |
| 30 | + self.end_headers() |
| 31 | + self.wfile.write(body) |
| 32 | + |
| 33 | + def _body(self) -> dict: |
| 34 | + n = int(self.headers.get("Content-Length", 0)) |
| 35 | + return json.loads(self.rfile.read(n) or b"{}") |
| 36 | + |
| 37 | + def log_message(self, *_a): # quiet |
| 38 | + pass |
| 39 | + |
| 40 | + def do_GET(self): |
| 41 | + if not self._auth_ok(): |
| 42 | + return self._send(401, {"error": "unauthorized"}) |
| 43 | + if self.path == "/inspect": |
| 44 | + with lock: |
| 45 | + return self._send(200, memory.inspect()) |
| 46 | + self._send(404, {"error": "not found"}) |
| 47 | + |
| 48 | + def do_POST(self): |
| 49 | + if not self._auth_ok(): |
| 50 | + return self._send(401, {"error": "unauthorized"}) |
| 51 | + try: |
| 52 | + p = self._body() |
| 53 | + with lock: |
| 54 | + self._dispatch(p) |
| 55 | + except Exception as exc: # noqa: BLE001 |
| 56 | + self._send(400, {"error": str(exc)}) |
| 57 | + |
| 58 | + def _dispatch(self, p: dict) -> None: |
| 59 | + if self.path == "/remember": |
| 60 | + self._send(200, {"ids": memory.remember(p.pop("text", ""), **p)}) |
| 61 | + elif self.path == "/recall": |
| 62 | + hits = memory.recall(p.pop("query", ""), **p) |
| 63 | + self._send(200, {"hits": [{"fact": h.fact.to_dict(), "score": h.score, |
| 64 | + "components": h.components} for h in hits]}) |
| 65 | + elif self.path == "/forget": |
| 66 | + memory.forget(p["fact_id"]) |
| 67 | + self._send(200, {"ok": True}) |
| 68 | + elif self.path == "/snapshot": |
| 69 | + self._send(200, {"facts": [f.to_dict() for f in memory.snapshot(**p)]}) |
| 70 | + elif self.path == "/compact": |
| 71 | + self._send(200, {"n": memory.compact(**p)}) |
| 72 | + elif self.path == "/gc": |
| 73 | + self._send(200, {"n": memory.gc()}) |
| 74 | + else: |
| 75 | + self._send(404, {"error": "not found"}) |
| 76 | + |
| 77 | + return Handler |
| 78 | + |
| 79 | + |
| 80 | +def serve(memory: Memory, host: str = "127.0.0.1", port: int = 8080, |
| 81 | + token: str | None = None) -> ThreadingHTTPServer: |
| 82 | + """Build a ThreadingHTTPServer for `memory`. Call serve_forever() to run it.""" |
| 83 | + return ThreadingHTTPServer((host, port), _handler(memory, token)) |
| 84 | + |
| 85 | + |
| 86 | +def main(argv=None) -> int: |
| 87 | + import argparse |
| 88 | + ap = argparse.ArgumentParser(prog="wolf-server", description="WolfDB shard server") |
| 89 | + ap.add_argument("path", help="path to this shard's .wolf store") |
| 90 | + ap.add_argument("--host", default="127.0.0.1") |
| 91 | + ap.add_argument("--port", type=int, default=8080) |
| 92 | + ap.add_argument("--namespace", default="wolf") |
| 93 | + a = ap.parse_args(argv) |
| 94 | + token = os.environ.get("WOLF_TOKEN") |
| 95 | + httpd = serve(Memory.open(a.path, namespace=a.namespace), a.host, a.port, token) |
| 96 | + note = "" if token else " [NO AUTH — bind to localhost only]" |
| 97 | + print(f"WolfDB shard serving {a.path} at http://{a.host}:{a.port}{note}", flush=True) |
| 98 | + try: |
| 99 | + httpd.serve_forever() |
| 100 | + except KeyboardInterrupt: |
| 101 | + httpd.shutdown() |
| 102 | + return 0 |
| 103 | + |
| 104 | + |
| 105 | +if __name__ == "__main__": |
| 106 | + raise SystemExit(main()) |
0 commit comments