tests/client.py

"""Socket client for ez-agent JSONL protocol."""

from __future__ import annotations

import json
import select
import socket
import time
from pathlib import Path
from typing import Optional


def find_frame(frames: list[dict], frame_type: str) -> dict | None:
    """Find the first frame with the given type in a list of frames."""
    for f in frames:
        if f.get("type") == frame_type:
            return f
    return None


def find_error(frames: list[dict], code: str) -> dict | None:
    """Find the first error frame with the given code in a list of frames.

    Checks both ``type="error"`` with ``code=code`` and ``type=code``
    (legacy error format).
    """
    for f in frames:
        if f.get("type") == "error" and f.get("code") == code:
            return f
        if f.get("type") == code:
            return f
    return None


class SocketClient:
    """Sync JSONL client for ez-agent Unix domain socket."""

    def __init__(self, socket_path: str | Path) -> None:
        self.socket_path = str(socket_path)
        self._sock: socket.socket | None = None
        self._buf = b""
        self._connected = False

    def connect(self, timeout: float = 5.0) -> None:
        """Connect to the Unix domain socket."""
        self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
        self._sock.settimeout(timeout)
        self._sock.connect(self.socket_path)
        self._connected = True
        self._buf = b""

    def close(self) -> None:
        """Close the socket connection."""
        if self._sock:
            self._sock.close()
            self._sock = None
        self._connected = False

    def __enter__(self):
        self.connect()
        return self

    def __exit__(self, *exc):
        self.close()

    def send(self, msg: dict) -> None:
        """Send a JSONL message."""
        if not self._sock:
            raise RuntimeError("not connected")
        self._sock.sendall(json.dumps(msg).encode() + b"\n")

    def send_lines(self, *msgs: dict) -> None:
        """Send multiple JSONL messages."""
        data = b"\n".join(json.dumps(m).encode() for m in msgs) + b"\n"
        if not self._sock:
            raise RuntimeError("not connected")
        self._sock.sendall(data)

    def recv_frame(self, timeout: float = 5.0) -> Optional[dict]:
        """Receive a single JSONL frame. Returns None on timeout or EOF."""
        if not self._sock:
            raise RuntimeError("not connected")
        deadline = time.time() + timeout
        while time.time() < deadline:
            if b"\n" in self._buf:
                line, self._buf = self._buf.split(b"\n", 1)
                try:
                    return json.loads(line)
                except json.JSONDecodeError:
                    continue
            remaining = deadline - time.time()
            if remaining <= 0:
                return None
            self._sock.settimeout(max(0.05, remaining))
            try:
                chunk = self._sock.recv(65536)
                if not chunk:
                    return None
                self._buf += chunk
            except socket.timeout:
                continue
            except OSError:
                return None
        return None

    def recv_until(
        self,
        done_types: set[str],
        timeout: float = 30.0,
    ) -> list[dict]:
        """Collect frames until a frame type is in done_types or timeout.

        Returns all frames received, including the done frame.
        """
        frames: list[dict] = []
        deadline = time.time() + timeout
        while time.time() < deadline:
            frame = self.recv_frame(timeout=deadline - time.time())
            if frame is None:
                break
            frames.append(frame)
            if frame.get("type") in done_types:
                break
        return frames

    def send_and_recv(
        self,
        msg: dict,
        done_types: set[str],
        timeout: float = 30.0,
    ) -> list[dict]:
        """Send a message and collect frames until done_types or timeout."""
        self.send(msg)
        return self.recv_until(done_types, timeout)

    def hello(self, name: str = "test", leaf_id: str | None = None) -> dict | None:
        """Send hello handshake and return hello_ack frame."""
        msg: dict = {
            "type": "hello",
            "protocol": 1,
            "name": name,
        }
        if leaf_id is not None:
            msg["leaf_id"] = leaf_id
        self.send(msg)
        return self.recv_frame(timeout=5.0)

    def handshake(self, name: str = "test", leaf_id: str | None = None) -> dict:
        """Send hello and verify hello_ack. Returns the ack frame or raises."""
        ack = self.hello(name=name, leaf_id=leaf_id)
        if ack is None:
            raise RuntimeError("No hello_ack received")
        if ack.get("type") != "hello_ack":
            raise RuntimeError(f"Expected hello_ack, got {ack.get('type')}: {ack}")
        return ack

    def set_blocking(self, blocking: bool) -> None:
        if self._sock:
            self._sock.setblocking(blocking)

    def drain(self) -> None:
        """Discard any buffered data in the receive buffer."""
        self._buf = b""

    @staticmethod
    def recv_parallel(
        clients: list[tuple[SocketClient, set[str]]],
        timeout: float = 90.0,
    ) -> list[list[dict]]:
        """Receive from multiple clients in parallel until done_types met or timeout.

        Args:
            clients: list of (client, done_types) tuples. done_types of None
                     means "collect until timeout only" (no early exit).
            timeout: max seconds to wait.

        Returns:
            list of frame lists, one per client, in same order as input.
        """
        socks = [c._sock for c, _ in clients]
        done_types_list = [dt for _, dt in clients]
        all_msgs: list[list[dict]] = [[] for _ in clients]
        deadline = time.time() + timeout

        while time.time() < deadline:
            readable, _, _ = select.select(socks, [], [], 0.1)
            for s in readable:
                idx = socks.index(s)
                try:
                    data = s.recv(65536)
                    if not data:
                        socks[idx] = None
                        continue
                    for line in data.decode(errors="replace").splitlines():
                        if line.strip():
                            try:
                                all_msgs[idx].append(json.loads(line))
                            except json.JSONDecodeError:
                                pass
                except BlockingIOError:
                    pass

            all_done = True
            for idx, dt in enumerate(done_types_list):
                if dt is None:
                    continue
                if not any(m.get("type") in dt for m in all_msgs[idx]):
                    all_done = False
                    break
            if all_done and any(dt is not None for dt in done_types_list):
                return all_msgs

        return all_msgs