use async_trait::async_trait; use bft_json_crdt::json_crdt::SignedOp; use ezsockets::ClientConfig; use tokio::sync::mpsc; pub(crate) struct WebSocketClient { incoming_sender: mpsc::Sender, handle: ezsockets::Client, } impl WebSocketClient { /// Start the websocket client pub(crate) async fn new( incoming_sender: mpsc::Sender, ) -> ezsockets::Client { tracing_subscriber::fmt::init(); let config = ClientConfig::new("ws://localhost:8080/websocket"); let (handle, future) = ezsockets::connect( |client| WebSocketClient { incoming_sender, handle: client, }, config, ) .await; tokio::spawn(async move { future.await.unwrap(); }); handle } } #[async_trait] impl ezsockets::ClientExt for WebSocketClient { // Right now we're only using the Call type for sending signed ops // change this to an enum if we need to send other types of calls, and // match on it. type Call = String; async fn on_text(&mut self, text: String) -> Result<(), ezsockets::Error> { tracing::info!("received text: {text:?}"); let incoming: bft_json_crdt::json_crdt::SignedOp = serde_json::from_str(&text).unwrap(); self.incoming_sender.send(incoming).await?; Ok(()) } async fn on_binary(&mut self, bytes: Vec) -> Result<(), ezsockets::Error> { tracing::info!("received bytes: {bytes:?}"); Ok(()) } async fn on_call(&mut self, call: Self::Call) -> Result<(), ezsockets::Error> { tracing::info!("sending signed op: {call:?}"); self.handle.text(call)?; Ok(()) } }