Files
bft-crdt-experiment/side-node/src/websocket.rs

70 lines
2.1 KiB
Rust
Raw Normal View History

2024-06-06 19:32:29 +01:00
use async_trait::async_trait;
use bft_json_crdt::json_crdt::SignedOp;
2024-06-06 19:32:29 +01:00
use ezsockets::ClientConfig;
use tokio::sync::mpsc;
2024-06-06 19:32:29 +01:00
pub(crate) struct WebSocketClient {
incoming_sender: mpsc::Sender<SignedOp>,
2024-06-11 18:13:51 +01:00
network_receiver: mpsc::Receiver<SignedOp>,
handle: ezsockets::Client<WebSocketClient>,
}
impl WebSocketClient {
/// Start the websocket client
2024-06-11 18:13:51 +01:00
pub(crate) async fn new(
2024-06-10 16:43:45 +01:00
incoming_sender: mpsc::Sender<SignedOp>,
2024-06-11 18:13:51 +01:00
network_receiver: mpsc::Receiver<SignedOp>,
) -> ezsockets::Client<WebSocketClient> {
tracing_subscriber::fmt::init();
let config = ClientConfig::new("ws://localhost:8080/websocket");
2024-06-11 18:13:51 +01:00
let (handle, future) = ezsockets::connect(
|client| WebSocketClient {
incoming_sender,
network_receiver,
handle: client,
},
config,
)
.await;
tokio::spawn(async move {
future.await.unwrap();
});
handle
}
2024-06-11 18:13:51 +01:00
pub(crate) async fn start(&mut self) {
loop {
match self.network_receiver.try_recv() {
Ok(signed_op) => {
let to_send = serde_json::to_string(&signed_op).unwrap();
self.handle.text(to_send).unwrap();
}
Err(_) => {} // ignore empty channel errors in this PoC
}
}
}
}
2024-06-06 19:32:29 +01:00
#[async_trait]
impl ezsockets::ClientExt for WebSocketClient {
2024-06-11 18:13:51 +01:00
type Call = String;
2024-06-06 19:32:29 +01:00
async fn on_text(&mut self, text: String) -> Result<(), ezsockets::Error> {
let incoming: bft_json_crdt::json_crdt::SignedOp = serde_json::from_str(&text).unwrap();
tracing::info!("received signed op: {incoming:?}");
self.incoming_sender.send(incoming).await.unwrap();
2024-06-06 19:32:29 +01:00
Ok(())
}
async fn on_binary(&mut self, bytes: Vec<u8>) -> Result<(), ezsockets::Error> {
tracing::info!("received bytes: {bytes:?}");
Ok(())
}
async fn on_call(&mut self, call: Self::Call) -> Result<(), ezsockets::Error> {
2024-06-11 18:13:51 +01:00
println!("received call: {call}");
self.start().await;
2024-06-06 19:32:29 +01:00
Ok(())
}
}