use futures_util::SinkExt; use serde::Serialize; use tokio_tungstenite::tungstenite::Message; use crate::Socket; pub struct GiteratedConnectionHandshaker(Socket); impl GiteratedConnectionHandshaker { pub fn new(socket: Socket) -> Self { Self(socket) } pub async fn handshake(self) -> Result { // let mut socket = self.0; // // Send handshake initiation // Self::send_raw_message( // &mut socket, // &InitiateHandshake { // version: Version::from_str("0.0.0").unwrap(), // }, // ) // .await?; // while let Some(message) = socket.next().await { // let message = match message { // Ok(message) => message, // Err(err) => { // error!("Error reading message: {:?}", err); // continue; // } // }; // let payload = match message { // Message::Text(text) => text.into_bytes(), // Message::Binary(bytes) => bytes, // Message::Ping(_) => continue, // Message::Pong(_) => continue, // Message::Close(_) => { // socket.close(None).await?; // return Err(SocketClosedError.into()); // } // _ => unreachable!(), // }; // info!("Read payload: {}", std::str::from_utf8(&payload).unwrap()); // // We try deserializing the finalize response first as it is smaller and just as common // if let Ok(finalize) = serde_json::from_slice::(&payload) { // if finalize.success { // info!("Handshake success!"); // return Ok(socket); // } else { // socket.close(None).await?; // return Err(SocketClosedError.into()); // } // } else { // match serde_json::from_slice::(&payload) { // Ok(_response) => { // // let message = if !validate_version(&response.version) { // // error!( // // "Version compatibility failure! Our Version: {}, Their Version: {}", // // version(), // // response.version // // ); // // HandshakeFinalize { success: false } // // } else { // // info!("Connected with a compatible version"); // // HandshakeFinalize { success: true } // // }; // warn!("Version compatibility has been no-op'd"); // let message = HandshakeFinalize { success: true }; // // Send [`HandshakeFinalize`] to indicate if we're compatible or not // Self::send_raw_message(&mut socket, &message).await?; // } // Err(err) => { // error!("Error deserializing message: {:?}", err); // continue; // } // } // } // } Ok(self.0) } async fn send_raw_message( socket: &mut Socket, message: &T, ) -> Result<(), tokio_tungstenite::tungstenite::Error> { socket .send(Message::Binary(bincode::serialize(message).unwrap())) .await?; Ok(()) } } #[derive(Debug, thiserror::Error)] #[error("closed socket")] struct SocketClosedError;