"""Exercise the actual Go relay and Rust daemons using a simulated phone TCP endpoint. Build first with scripts/build.ps1 or scripts/build.sh. No external Python packages. """ import argparse import concurrent.futures import json import os from pathlib import Path import secrets import socket import socketserver import subprocess import threading import time import urllib.error import urllib.request ROOT = Path(__file__).resolve().parents[1] def free_port(): with socket.socket() as sock: sock.bind(("127.0.0.1", 0)) return sock.getsockname()[1] def wait_until(predicate, description, seconds=15): deadline = time.monotonic() + seconds while time.monotonic() < deadline: try: if predicate(): return except (OSError, urllib.error.URLError): pass time.sleep(0.1) raise AssertionError(f"Timed out: {description}") class Echo(socketserver.BaseRequestHandler): def handle(self): try: while data := self.request.recv(65536): self.request.sendall(data) except OSError: pass class Phone(socketserver.ThreadingTCPServer): daemon_threads = True allow_reuse_address = True def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--bin-dir", type=Path, default=ROOT / "bin") parser.add_argument("--rust-dir", type=Path) args = parser.parse_args() rust_dir = args.rust_dir or args.bin_dir suffix = ".exe" if os.name == "nt" else "" server_bin = (args.bin_dir / f"ads-server{suffix}").resolve() agent_bin = (rust_dir / f"ads-agent{suffix}").resolve() client_bin = (rust_dir / f"ads-client{suffix}").resolve() for path in (server_bin, agent_bin, client_bin): if not path.exists(): raise SystemExit(f"Build missing binary first: {path}") logs = ROOT / "work" / "e2e" logs.mkdir(parents=True, exist_ok=True) processes, handles = [], [] agent_token, client_token = secrets.token_hex(32), secrets.token_hex(32) relay_port, local_port, second_port = free_port(), free_port(), free_port() relay = f"ws://127.0.0.1:{relay_port}" api = f"http://127.0.0.1:{relay_port}" def launch(name, command, tokens): env = os.environ.copy() env.pop("ADS_AGENT_TOKEN", None) env.pop("ADS_CLIENT_TOKEN", None) env.update(tokens) handle = open(logs / f"{name}.log", "wb") handles.append(handle) process = subprocess.Popen([str(item) for item in command], env=env, stdout=handle, stderr=subprocess.STDOUT, creationflags=subprocess.CREATE_NO_WINDOW if os.name == "nt" else 0) processes.append(process) return process def stop(process): if process.poll() is None: process.terminate() try: process.wait(timeout=8) except subprocess.TimeoutExpired: process.kill() process.wait(timeout=5) def devices(token=client_token): req = urllib.request.Request(api + "/v1/devices", headers={"Authorization": "Bearer " + token}) with urllib.request.urlopen(req, timeout=2) as response: return json.load(response) def busy(): return any(device["id"] == "test-phone" and device["busy"] for device in devices()) def transfer(size): payload = secrets.token_bytes(size) with socket.create_connection(("127.0.0.1", local_port), timeout=8) as sock: sock.settimeout(10) with concurrent.futures.ThreadPoolExecutor(max_workers=1) as writer: sent = writer.submit(sock.sendall, payload) received = bytearray() while len(received) < size: chunk = sock.recv(min(65536, size - len(received))) if not chunk: raise AssertionError("Tunnel closed before complete response") received.extend(chunk) sent.result(timeout=5) assert received == payload, "Binary stream corruption" with Phone(("127.0.0.1", 0), Echo) as phone: threading.Thread(target=phone.serve_forever, daemon=True).start() phone_port = phone.server_address[1] server_command = [server_bin, "--listen", f"127.0.0.1:{relay_port}"] agent_command = [agent_bin, "--server", relay, "--allow-insecure", "--device", "test-phone", "--target", f"127.0.0.1:{phone_port}"] client_command = [client_bin, "--server", relay, "--allow-insecure", "--device", "test-phone", "--listen", f"127.0.0.1:{local_port}", "--no-auto-connect"] try: server = launch("server", server_command, {"ADS_AGENT_TOKEN": agent_token, "ADS_CLIENT_TOKEN": client_token}) wait_until(lambda: devices() == [], "relay startup") try: devices(agent_token) raise AssertionError("Agent token granted client access") except urllib.error.HTTPError as error: assert error.code == 401 agent = launch("agent", agent_command, {"ADS_AGENT_TOKEN": agent_token}) wait_until(lambda: len(devices()) == 1, "agent registration") client = launch("client", client_command, {"ADS_CLIENT_TOKEN": client_token}) wait_until(busy, "client exclusive lease") transfer(2 * 1024 * 1024) with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool: list(pool.map(transfer, [256 * 1024] * 8)) print("PASS: 2 MiB binary stream and eight concurrent streams") # Keep a data stream idle across the server's 20-second control ping. with socket.create_connection(("127.0.0.1", local_port), timeout=8) as idle: idle.settimeout(5) time.sleep(22) idle.sendall(b"after-heartbeat") received = bytearray() while len(received) < 15: chunk = idle.recv(15 - len(received)) assert chunk, "Idle tunnel was closed by heartbeat processing" received.extend(chunk) assert received == b"after-heartbeat" print("PASS: idle tunnel survives control ping/pong heartbeat") competitor_command = client_command.copy() competitor_command[competitor_command.index("--listen") + 1] = f"127.0.0.1:{second_port}" competitor = launch("competitor", competitor_command, {"ADS_CLIENT_TOKEN": client_token}) time.sleep(1) with socket.create_connection(("127.0.0.1", second_port), timeout=3) as sock: sock.settimeout(3) try: sock.sendall(b"denied") assert sock.recv(16) == b"", "Second client stole exclusive device" except (ConnectionResetError, ConnectionAbortedError): pass stop(competitor) print("PASS: competing client cannot acquire occupied device") stop(agent) wait_until(lambda: devices() == [], "offline device removal") agent = launch("agent-restarted", agent_command, {"ADS_AGENT_TOKEN": agent_token}) wait_until(busy, "client lease recovery after agent restart", seconds=40) transfer(65536) print("PASS: agent restart and client reconnection") stop(server) server = launch("server-restarted", server_command, {"ADS_AGENT_TOKEN": agent_token, "ADS_CLIENT_TOKEN": client_token}) wait_until(busy, "both daemons reconnect after relay restart", seconds=45) transfer(65536) print("PASS: relay restart and both-daemon recovery") assert agent.poll() is None and client.poll() is None finally: for process in reversed(processes): stop(process) for handle in handles: handle.close() phone.shutdown() print("PASS: all three-program integration checks") if __name__ == "__main__": main()