"""Shared fixtures for morly's integration suite. The unit layer runs through the compiler's own harness (`make test-unit`); this is the layer that drives a real relay process: the ORLY_* env contract, the WebSocket round-trip, and the policy limits. It replaces the browser with a socket, so it needs no selenium and no app build. Test regime uses 127.0.0.1 on a non-standard port so a dev relay on the production port (3334) is not disturbed: 127.0.0.1:23335 — test relay (WebSocket + static files, when one is given) """ import os import re import shutil import signal import subprocess import time import pytest PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # MORLY_RELAY_BIN forces a specific binary, which is how `make test-integration` # points the suite at the one it just built. The fallbacks cover a hand-run # `make build` and the instrumented build (`make build-test-relay`). _bins = ["morly", "morly-test"] RELAY_BIN = os.environ.get("MORLY_RELAY_BIN") or next( (os.path.join(PROJECT_ROOT, b) for b in _bins if os.path.exists(os.path.join(PROJECT_ROOT, b))), "") # Optional: the relay serves this tree. Unset means the static-file checks are # not in play; nothing in the relay layer requires a frontend build. STATIC_DIR = os.environ.get("ORLY_STATIC_DIR") or "" DATA_DIR = "/tmp/morly-test-data" RELAY_HOST = "127.0.0.1" RELAY_PORT = 23335 RELAY_URL = f"http://{RELAY_HOST}:{RELAY_PORT}" WS_URL = f"ws://{RELAY_HOST}:{RELAY_PORT}" def relay_tree_pids(): """PIDs running this checkout's relay binary, from any earlier run. The relay is started as an absolute path, and every domain spawn()ed from it forks a child that keeps the same argv, so anchoring the pattern on the path finds the whole tree and nothing else. """ if not RELAY_BIN: return [] try: out = subprocess.run( ["pgrep", "-f", "^" + re.escape(RELAY_BIN)], capture_output=True, text=True, timeout=5, ).stdout except Exception: return [] return sorted({int(p) for p in out.split() if p.isdigit()}) def kill_stale_relays(): """Kill any relay left behind by a previous (crashed or killed) run. A leftover relay keeps listening on the test port, so a new fixture would talk to it instead of the one it started: its store is the old one and its process group outlives ours. A quit run cleans up after itself; this is the guard for the runs that do not get to. """ pids = relay_tree_pids() if not pids: return print(f"\nrelay fixture: killing {len(pids)} leftover relay process(es) {pids}") for pid in pids: try: os.killpg(os.getpgid(pid), signal.SIGKILL) except Exception: try: os.kill(pid, signal.SIGKILL) except Exception: pass for _ in range(50): if not relay_tree_pids(): return time.sleep(0.1) def port_pids(port): """PIDs listening on a TCP port, via ss. Empty if ss cannot say.""" try: out = subprocess.run( ["ss", "-ltnpH", f"sport = :{port}"], capture_output=True, text=True, timeout=5, ).stdout except Exception: return [] return sorted({int(m.group(1)) for m in re.finditer(r"pid=(\d+)", out)}) def stop_relay(proc): """Terminate the relay's whole process group, then reap it. The relay forks a child per spawn()ed domain; signalling only the parent leaves those children holding resources (and their copy of the store), so the group gets the signal. """ if proc.poll() is not None: return try: pgid = os.getpgid(proc.pid) except Exception: pgid = None for sig in (signal.SIGTERM, signal.SIGKILL): try: if pgid is not None: os.killpg(pgid, sig) else: proc.send_signal(sig) except Exception: pass try: proc.wait(timeout=5 if sig == signal.SIGTERM else 2) break except subprocess.TimeoutExpired: continue @pytest.fixture(scope="session") def relay(): """Start the relay for the test session.""" if not RELAY_BIN or not os.path.exists(RELAY_BIN): pytest.skip("relay binary not found — run: make build") os.makedirs(DATA_DIR, exist_ok=True) # Start from an empty store. The data dir survives across sessions, and the # relay replays the whole WAL at open: after a few runs the accumulated # events made startup take longer than the readiness wait below and every # test in the session errored on "relay failed to start". Tests also # expect a known store, not whatever earlier runs left behind. shutil.rmtree(os.path.join(DATA_DIR, "db"), ignore_errors=True) env = os.environ.copy() env["ORLY_DATA_DIR"] = DATA_DIR env["ORLY_LISTEN"] = RELAY_HOST env["ORLY_PORT"] = str(RELAY_PORT) env["ORLY_HTTP_GUARD_ENABLED"] = "false" if STATIC_DIR: env["ORLY_STATIC_DIR"] = STATIC_DIR # Nothing may be listening before we bind: a stale relay would answer the # readiness probe below and every request in this session. kill_stale_relays() holders = port_pids(RELAY_PORT) if holders: pytest.fail( f"port {RELAY_PORT} is already held by pid(s) {holders}; " f"stop them before running the suite" ) # Log to a file, not a pipe: the relay logs every store and request event, # and a pipe nobody drains fills up and stalls the relay mid-suite. relay_log_path = "/tmp/morly-test-relay.log" relay_log = open(relay_log_path, "wb") # own session/process group: the relay forks a child per spawned domain, # and only a group signal reaches all of them at teardown. proc = subprocess.Popen( [RELAY_BIN], env=env, stdout=relay_log, stderr=subprocess.STDOUT, start_new_session=True, ) import urllib.error import urllib.request # Probe /health, not /. This suite does not require a frontend build, and # without ORLY_STATIC_DIR a request for / is a 404 - which urlopen raises # on, so a probe against / would never report a relay that is serving # perfectly well. Any HTTP status here means the listener is up. ready = False for _ in range(300): if proc.poll() is not None: break try: urllib.request.urlopen(RELAY_URL + "/health", timeout=1) ready = True break except urllib.error.HTTPError: ready = True break except Exception: time.sleep(0.2) if not ready: # Read the exit state before stop_relay reaps it: after the SIGTERM the # return code is ours, and reporting that as "exited during startup" # sends the reader looking for a crash that never happened. exited = proc.poll() stop_relay(proc) relay_log.flush() relay_log.close() with open(relay_log_path, errors="replace") as f: print(f"\n=== RELAY LOG ===\n{f.read()[-4000:]}\n=== END ===\n") pytest.fail( "Relay failed to start within 60 seconds" if exited is None else f"Relay exited with {exited} during startup" ) # The readiness probe only proves *something* served that port. holders = port_pids(RELAY_PORT) if holders and proc.pid not in holders: stop_relay(proc) pytest.fail( f"port {RELAY_PORT} answered from pid(s) {holders}, " f"not the relay this fixture started (pid {proc.pid})" ) info = { "proc": proc, "url": RELAY_URL, "ws": WS_URL, "host": RELAY_HOST, "port": RELAY_PORT, } yield info if proc.poll() is not None: relay_log.flush() with open(relay_log_path, errors="replace") as f: out = f.read() if out: print(f"\n=== RELAY LOG ===\n{out[-4000:]}\n=== END ===\n") stop_relay(proc) relay_log.close() kill_stale_relays() leftovers = port_pids(RELAY_PORT) if leftovers: print(f"\nrelay fixture: port {RELAY_PORT} still held by {leftovers} after teardown")