//! Cliente de handshake. Conecta a un Unix socket y mantiene la sesión. use std::collections::VecDeque; use std::path::Path; use std::time::Duration; use brahman_card::{Card, WitInterface, CARD_SCHEMA_VERSION}; use thiserror::Error; use tokio::net::UnixStream; use crate::codec::{read_frame, write_frame}; use crate::messages::{Farewell, Frame, HandshakeError, Hello, HelloAck, MatchEvent, Ping, SessionId}; /// Errores del cliente. #[derive(Debug, Error)] pub enum ClientError { #[error("E/S: {0}")] Io(#[from] std::io::Error), /// El servidor respondió con un error explícito. #[error("servidor: {0}")] Server(#[source] HandshakeError), /// El servidor envió un frame que no esperábamos en este punto del protocolo. #[error("frame inesperado: {got}")] UnexpectedFrame { got: &'static str }, /// La Card que el cliente intentó enviar no pasa su propia validación. #[error("card inválida pre-envío: {0}")] InvalidCard(String), } /// Cliente conectado y autenticado. Tras `connect` ya completó el handshake /// y tiene su `SessionId`. Los `MatchEvent` recibidos durante operaciones /// request/response se buferean en `pending_events` y se obtienen vía /// [`Client::take_event`] o [`Client::await_event`]. #[derive(Debug)] pub struct Client { stream: UnixStream, session: SessionId, server_info: HelloAck, pending_events: VecDeque, } impl Client { /// Conecta como módulo agnóstico (sin WIT). Equivalente a /// `connect_with(path, card, None)`. pub async fn connect(path: impl AsRef, card: Card) -> Result { Self::connect_with(path, card, None).await } /// Conecta al socket enviando Hello con la Card dada y opcionalmente /// una `WitInterface` ya extraída. Si `wit` es `Some`, el server /// registra el módulo como "consciente". pub async fn connect_with( path: impl AsRef, card: Card, wit: Option, ) -> Result { card.validate() .map_err(|e| ClientError::InvalidCard(e.to_string()))?; let mut stream = UnixStream::connect(path).await?; let hello = Hello { schema_version: CARD_SCHEMA_VERSION, protocol_version: brahman_card::PROTOCOL_VERSION.to_string(), card: card.into(), // Card → WireCard: descarta extensions wit, }; write_frame(&mut stream, &Frame::Hello(hello)).await?; let frame = read_frame(&mut stream).await?; let ack = match frame { Frame::HelloAck(a) => a, Frame::Error(e) => return Err(ClientError::Server(e)), Frame::Hello(_) => return Err(ClientError::UnexpectedFrame { got: "Hello" }), Frame::Ping(_) => return Err(ClientError::UnexpectedFrame { got: "Ping" }), Frame::Pong(_) => return Err(ClientError::UnexpectedFrame { got: "Pong" }), Frame::Farewell(_) => return Err(ClientError::UnexpectedFrame { got: "Farewell" }), Frame::MatchEvent(_) => { return Err(ClientError::UnexpectedFrame { got: "MatchEvent (pre-handshake)", }); } }; Ok(Self { stream, session: ack.session, server_info: ack, pending_events: VecDeque::new(), }) } /// `SessionId` asignado por el servidor. pub fn session(&self) -> SessionId { self.session } /// Información del servidor recibida en el handshake. pub fn server_info(&self) -> &HelloAck { &self.server_info } /// Envía un Ping y devuelve el timestamp del servidor. Los frames /// `MatchEvent` que lleguen mezclados se buferean en `pending_events`. pub async fn ping(&mut self) -> Result { write_frame( &mut self.stream, &Frame::Ping(Ping { session: self.session, }), ) .await?; loop { match read_frame(&mut self.stream).await? { Frame::Pong(p) => return Ok(p.timestamp_ms), Frame::MatchEvent(ev) => self.pending_events.push_back(ev), Frame::Error(e) => return Err(ClientError::Server(e)), _ => return Err(ClientError::UnexpectedFrame { got: "non-pong" }), } } } /// Saca un evento pendiente del buffer, sin bloquear ni leer del wire. pub fn take_event(&mut self) -> Option { self.pending_events.pop_front() } /// Espera un `MatchEvent` con timeout. Drena primero el buffer; si /// está vacío, lee del wire hasta el timeout. Otros frames recibidos /// (Pong huérfano, Error) cortan la espera con error. pub async fn await_event( &mut self, timeout: Duration, ) -> Result, ClientError> { if let Some(ev) = self.pending_events.pop_front() { return Ok(Some(ev)); } match tokio::time::timeout(timeout, read_frame(&mut self.stream)).await { Err(_) => Ok(None), Ok(Err(e)) => Err(ClientError::Io(e)), Ok(Ok(Frame::MatchEvent(ev))) => Ok(Some(ev)), Ok(Ok(Frame::Error(e))) => Err(ClientError::Server(e)), Ok(Ok(_)) => Err(ClientError::UnexpectedFrame { got: "non-event en await_event", }), } } /// Cierre cooperativo. Consume el cliente. pub async fn farewell(mut self) -> Result<(), ClientError> { write_frame( &mut self.stream, &Frame::Farewell(Farewell { session: self.session, }), ) .await?; Ok(()) } }