"""Forward framed HTTP calls from a source daemon to this host's daemon. A source daemon moving a session here runs this over ssh, from the bundle the host probe staged (robot-docs/workspaces.md, "moving a session to another daemon"). It reads ``daemon.json`` from ``$ALBEDO_HOME`` (default ``~/.albedo``) and calls the loopback daemon it names with that token, so the token never leaves this host. Every frame is a 4-byte big-endian length and its payload, on stdin and stdout. The relay first writes a hello, ``{"home", "port"}`` or ``{"error"}`` when no daemon is recorded here. Each call is two frames, a JSON header ``{"method", "path", "content_type", "timeout"}`` (``timeout`` in seconds, optional) and the raw body; each answer is two frames, ``{"status"}`` (or ``{"error"}`` when the daemon did not answer) and the raw response body. stdin closing ends the relay. """ from __future__ import annotations import http.client import json import os import struct import sys from typing import BinaryIO TIMEOUT = 60 # seconds a call to the local daemon may take, unless it says def read_frame(stream: BinaryIO) -> bytes | None: header = stream.read(4) if len(header) < 4: return None (length,) = struct.unpack(">I", header) payload = stream.read(length) return payload if len(payload) == length else None def write_frame(stream: BinaryIO, payload: bytes) -> None: stream.write(struct.pack(">I", len(payload)) + payload) stream.flush() def write_json(stream: BinaryIO, value: object) -> None: write_frame(stream, json.dumps(value).encode()) def record(home: str) -> tuple[int, str] | str: """The port and token of this home's daemon, or why there are none.""" path = os.path.join(home, "daemon.json") try: with open(path, encoding="utf-8") as handle: data = json.load(handle) except FileNotFoundError: return f"no albedo daemon has run here ({path} is missing)" except (OSError, ValueError) as error: return f"{path} is unreadable: {error}" port, token = data.get("port"), data.get("token") if not isinstance(port, int) or not isinstance(token, str): return f"{path} names no daemon port and token" return port, token class Daemon: """One keep-alive connection to the loopback daemon, reopened on failure.""" def __init__(self, port: int, token: str) -> None: self.port = port self.token = token self.connection: http.client.HTTPConnection | None = None def call( self, method: str, path: str, content_type: str, body: bytes, timeout: float ) -> tuple[int, bytes]: for attempt in (1, 2): if self.connection is None: self.connection = http.client.HTTPConnection( "127.0.0.1", self.port, timeout=timeout ) self.connection.timeout = timeout if self.connection.sock is not None: self.connection.sock.settimeout(timeout) headers = {"Authorization": f"Bearer {self.token}"} if content_type: headers["Content-Type"] = content_type try: self.connection.request(method, path, body or None, headers) response = self.connection.getresponse() return response.status, response.read() except (OSError, http.client.HTTPException): self.connection.close() self.connection = None # A kept-alive connection the daemon closed fails once. if attempt == 2: raise raise AssertionError("unreachable") def main() -> int: source, sink = sys.stdin.buffer, sys.stdout.buffer home = os.environ.get("ALBEDO_HOME") or os.path.expanduser("~/.albedo") found = record(home) if isinstance(found, str): write_json(sink, {"error": found}) return 0 daemon = Daemon(*found) write_json(sink, {"home": home, "port": found[0]}) while True: header = read_frame(source) body = read_frame(source) if header is None or body is None: return 0 call = json.loads(header) try: status, answer = daemon.call( call["method"], call["path"], call.get("content_type", ""), body, float(call.get("timeout") or TIMEOUT), ) except (OSError, http.client.HTTPException) as error: write_json( sink, {"error": f"the albedo daemon here is not answering: {error}"}, ) write_frame(sink, b"") continue write_json(sink, {"status": status}) write_frame(sink, answer) if __name__ == "__main__": sys.exit(main())