"""Run one batch of cases through the other language's side of a contract. A contract checks a wire format that two languages share: each side's encoder against the other side's decoder (robot-docs/testing.md#cross-language-contracts). Each side runs one long-lived peer process for a whole run and answers batches over a pipe, so the cost is one process start per run and one round trip per generated batch, also while a property library shrinks a failure. A message either way is one JSON object behind a 4-byte big-endian length. A request is ``{"contract", "op", "cases"}`` and the answer ``{"results": [...]}``, one result per case, or ``{"error": text}``. The Gleam peer runs from compiled beams: those ``ALBEDO_CONTRACT_EBIN`` names, as `test/contract/run.py` sets, or else what `test/beams.py` finds, which builds the checkout first outside the gate, so a peer never runs stale code. """ from __future__ import annotations import json import os from pathlib import Path import struct import subprocess import sys from typing import BinaryIO ROOT = Path(__file__).resolve().parents[2] sys.path.insert(0, str(ROOT / "test")) import beams # noqa: E402 def write_message(stream: BinaryIO, message: object) -> None: data = json.dumps(message, separators=(",", ":")).encode() stream.write(struct.pack(">I", len(data)) + data) stream.flush() def read_message(stream: BinaryIO) -> object: head = _read_exact(stream, 4) return json.loads(_read_exact(stream, struct.unpack(">I", head)[0])) def _read_exact(stream: BinaryIO, size: int) -> bytes: data = bytearray() while len(data) < size: chunk = stream.read(size - len(data)) if not chunk: raise EOFError("contract peer closed its pipe") data.extend(chunk) return bytes(data) def ebin_dirs() -> list[str]: """The beam directories the Gleam peer loads, built from this checkout.""" given = os.environ.get("ALBEDO_CONTRACT_EBIN") return given.split(os.pathsep) if given else beams.ebins() class GleamPeer: """The Gleam side of every contract, in one `erl` process.""" def __init__(self) -> None: requests_in, self._requests = os.pipe() self._answers, answers_out = os.pipe() args = ["erl"] for directory in ebin_dirs(): args += ["-pa", directory] args += ["-noshell", "-noinput", "-eval", "albedo@contract@runner:serve()"] env = dict(os.environ, ALBEDO_CONTRACT_FDS=f"{requests_in},{answers_out}") self._process = subprocess.Popen( args, pass_fds=(requests_in, answers_out), env=env ) os.close(requests_in) os.close(answers_out) self._write = os.fdopen(self._requests, "wb") self._read = os.fdopen(self._answers, "rb") def call(self, contract: str, op: str, cases: list[object]) -> list[object]: write_message(self._write, {"contract": contract, "op": op, "cases": cases}) answer = read_message(self._read) if not isinstance(answer, dict) or "results" not in answer: raise RuntimeError(f"Gleam peer failed: {answer!r}") results = answer["results"] assert isinstance(results, list) and len(results) == len(cases) return results def close(self) -> None: self._write.close() self._read.close() try: self._process.wait(timeout=10) except subprocess.TimeoutExpired: self._process.kill() self._process.wait() def __enter__(self) -> GleamPeer: return self def __exit__(self, *_: object) -> None: self.close()