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

68 lines
1.9 KiB
Rust
Raw Normal View History

2024-05-29 18:17:34 +01:00
use bft_crdt_derive::add_crdt_fields;
use bft_json_crdt::{
json_crdt::{BaseCrdt, CrdtNode, IntoCrdtNode},
keypair::make_keypair,
list_crdt::ListCrdt,
op::ROOT_ID,
};
use serde::{Deserialize, Serialize};
use tokio::time::{self};
use websockets::WebSocket;
/// Starts a websocket and periodically sends a BFT-CRDT message to the websocket server
2024-05-29 18:17:34 +01:00
pub(crate) async fn start() -> Result<(), websockets::WebSocketError> {
2024-05-29 22:04:05 +01:00
println!("connecting to websocket at ws://localhost:8080/");
let mut ws = WebSocket::connect("ws://localhost:8080/").await?;
2024-05-29 22:04:05 +01:00
// generate a placeholder transaction
2024-05-29 18:17:34 +01:00
let json = generate_transaction().unwrap();
2024-05-29 22:04:05 +01:00
// set up a new BFT-CRDT
2024-05-29 18:17:34 +01:00
let keys = make_keypair();
let mut bft_crdt = BaseCrdt::<ListExample>::new(&keys);
// next job is to keep adding to this guy
let _a = bft_crdt.doc.list.insert(ROOT_ID, 'a').sign(&keys);
2024-05-29 22:04:05 +01:00
let mut interval = every_two_seconds();
loop {
interval.tick().await;
2024-05-29 18:17:34 +01:00
println!("Sending: {}", json);
ws.send_text(json.clone()).await?;
2024-05-29 22:04:05 +01:00
// TODO: bft_crdt.apply() changes in here when we receive socket input from other nodes
2024-05-29 18:17:34 +01:00
let msg = ws.receive().await?;
println!("Received: {:?}", msg);
}
}
2024-05-29 18:17:34 +01:00
2024-05-29 22:04:05 +01:00
fn every_two_seconds() -> time::Interval {
time::interval(time::Duration::from_secs(2))
}
2024-05-29 18:17:34 +01:00
#[add_crdt_fields]
#[derive(Clone, CrdtNode)]
struct ListExample {
list: ListCrdt<char>, // switch to Transaction as soon as char is working
}
/// A fake Transaction struct we can use as a simulated payload
#[derive(Serialize, Deserialize)]
struct Transaction {
from: String,
to: String,
amount: u64,
}
fn generate_transaction() -> serde_json::Result<String> {
let transaction = Transaction {
from: "Alice".to_string(),
to: "Bob".to_string(),
amount: 100,
};
let json = serde_json::to_string(&transaction).unwrap();
Ok(json)
}