Complete basalt example

This commit is contained in:
Alex 2020-12-02 21:21:42 +01:00
parent 14d34e76f4
commit 4061fc9fe8

View file

@ -2,15 +2,18 @@ use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use log::info;
use log::{info, warn};
use structopt::StructOpt;
use serde::{Deserialize, Serialize};
use sodiumoxide::crypto::auth;
use sodiumoxide::crypto::sign::ed25519;
use netapp::NetApp;
use netapp::peering::basalt::*;
use netapp::message::*;
use netapp::proto::*;
#[derive(StructOpt, Debug)]
#[structopt(name = "netapp")]
@ -88,20 +91,56 @@ async fn main() {
};
let peering = Basalt::new(netapp.clone(), bootstrap_peers, basalt_params);
netapp.add_msg_handler::<ExampleMessage, _, _>(
|_from: ed25519::PublicKey, msg: ExampleMessage| {
info!("Got example message: {:?}, sending example response", msg);
async {
ExampleResponse{example_field: false}
}
}
);
tokio::join!(
sampling_loop(peering.clone()),
sampling_loop(netapp.clone(), peering.clone()),
netapp.listen(),
peering.run(),
);
}
async fn sampling_loop(basalt: Arc<Basalt>) {
async fn sampling_loop(netapp: Arc<NetApp>, basalt: Arc<Basalt>) {
loop {
tokio::time::delay_for(Duration::from_secs(10)).await;
let peers = basalt.sample(10);
for p in peers {
info!("Sampled: {}", hex::encode(p));
let netapp2 = netapp.clone();
tokio::spawn(async move {
match netapp2.request(&p, ExampleMessage{
example_field: 42,
}, PRIO_NORMAL).await {
Ok(resp) => info!("Got example response: {:?}", resp),
Err(e) => warn!("Error with example request: {}", e),
}
});
}
}
}
#[derive(Serialize, Deserialize, Debug)]
struct ExampleMessage {
example_field: usize,
}
#[derive(Serialize, Deserialize, Debug)]
struct ExampleResponse {
example_field: bool,
}
impl Message for ExampleMessage {
const KIND: MessageKind = 0x99000001;
type Response = ExampleResponse;
}