82 lines
3.4 KiB
Python
82 lines
3.4 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
from http import HTTPStatus
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
from pathlib import Path
|
|
from urllib.parse import urlparse
|
|
|
|
from .ledger import Ledger
|
|
|
|
|
|
def _json(handler: BaseHTTPRequestHandler, status: HTTPStatus, body: object) -> None:
|
|
payload = json.dumps(body).encode("utf-8")
|
|
handler.send_response(status)
|
|
handler.send_header("Content-Type", "application/json")
|
|
handler.send_header("Content-Length", str(len(payload)))
|
|
handler.end_headers()
|
|
handler.wfile.write(payload)
|
|
|
|
|
|
def make_handler(ledger: Ledger):
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def log_message(self, format: str, *args: object) -> None:
|
|
return # Avoid request payloads in stdout logs.
|
|
|
|
def _body(self) -> dict:
|
|
length = int(self.headers.get("Content-Length", "0"))
|
|
if length > 16_384:
|
|
raise ValueError("request too large")
|
|
value = json.loads(self.rfile.read(length))
|
|
if not isinstance(value, dict):
|
|
raise ValueError("JSON object required")
|
|
return value
|
|
|
|
def do_GET(self) -> None:
|
|
if urlparse(self.path).path == "/health":
|
|
_json(self, HTTPStatus.OK, {"status": "ok"})
|
|
return
|
|
_json(self, HTTPStatus.NOT_FOUND, {"error": "not found"})
|
|
|
|
def do_POST(self) -> None:
|
|
path = urlparse(self.path).path
|
|
try:
|
|
body = self._body()
|
|
if path == "/transactions":
|
|
_json(self, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "HTTP intake is disabled; use a reviewed authenticated MCP transport"})
|
|
return
|
|
if path.startswith("/transactions/") and path.endswith("/claim"):
|
|
transaction_id = path.split("/")[2]
|
|
claim = ledger.claim(transaction_id, int(body.get("lease_seconds", 60)))
|
|
if claim is None:
|
|
_json(self, HTTPStatus.CONFLICT, {"error": "transaction already claimed or missing"})
|
|
else:
|
|
_json(self, HTTPStatus.OK, claim.__dict__)
|
|
return
|
|
if path == "/operations":
|
|
_json(self, HTTPStatus.SERVICE_UNAVAILABLE, {"error": "HTTP provider operations are disabled; use reviewed MCP choreography"})
|
|
return
|
|
_json(self, HTTPStatus.NOT_FOUND, {"error": "not found"})
|
|
except (KeyError, ValueError, json.JSONDecodeError) as error:
|
|
_json(self, HTTPStatus.BAD_REQUEST, {"error": str(error)})
|
|
|
|
return Handler
|
|
|
|
|
|
def serve() -> None:
|
|
if os.environ.get("SCHEDULING_TRANSPORT_MODE") != "local-development":
|
|
raise RuntimeError("runtime is disabled pending authenticated transport provisioning")
|
|
host = os.environ.get("SCHEDULING_HOST", "localhost")
|
|
if host not in {"localhost", "::1"}:
|
|
raise RuntimeError("this service may bind only to a localhost address")
|
|
port = int(os.environ.get("SCHEDULING_PORT", "8765"))
|
|
database = Path(os.environ.get("SCHEDULING_DB", "state/scheduling-ledger.sqlite3"))
|
|
server = ThreadingHTTPServer((host, port), make_handler(Ledger(database)))
|
|
print(f"local scheduling core listening on {host}:{port}")
|
|
server.serve_forever()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
serve()
|