2020-12-02 12:30:47 +00:00
|
|
|
use serde::Serialize;
|
|
|
|
|
2021-10-13 15:12:13 +00:00
|
|
|
use log::info;
|
|
|
|
|
2020-12-07 12:35:24 +00:00
|
|
|
use tokio::sync::watch;
|
|
|
|
|
2020-12-12 20:14:15 +00:00
|
|
|
pub type NodeID = sodiumoxide::crypto::sign::ed25519::PublicKey;
|
|
|
|
|
2020-12-02 19:12:24 +00:00
|
|
|
/// Utility function: encodes any serializable value in MessagePack binary format
|
|
|
|
/// using the RMP library.
|
|
|
|
///
|
|
|
|
/// Field names and variant names are included in the serialization.
|
|
|
|
/// This is used internally by the netapp communication protocol.
|
2020-12-02 12:30:47 +00:00
|
|
|
pub fn rmp_to_vec_all_named<T>(val: &T) -> Result<Vec<u8>, rmp_serde::encode::Error>
|
|
|
|
where
|
|
|
|
T: Serialize + ?Sized,
|
|
|
|
{
|
|
|
|
let mut wr = Vec::with_capacity(128);
|
|
|
|
let mut se = rmp_serde::Serializer::new(&mut wr)
|
|
|
|
.with_struct_map()
|
|
|
|
.with_string_variants();
|
|
|
|
val.serialize(&mut se)?;
|
|
|
|
Ok(wr)
|
|
|
|
}
|
2020-12-07 12:35:24 +00:00
|
|
|
|
|
|
|
/// This async function returns only when a true signal was received
|
|
|
|
/// from a watcher that tells us when to exit.
|
|
|
|
/// Usefull in a select statement to interrupt another
|
|
|
|
/// future:
|
|
|
|
/// ```
|
|
|
|
/// select!(
|
|
|
|
/// _ = a_long_task() => Success,
|
|
|
|
/// _ = await_exit(must_exit) => Interrupted,
|
|
|
|
/// )
|
|
|
|
/// ```
|
|
|
|
pub async fn await_exit(mut must_exit: watch::Receiver<bool>) {
|
2021-10-12 11:07:34 +00:00
|
|
|
while !*must_exit.borrow_and_update() {
|
|
|
|
if must_exit.changed().await.is_err() {
|
|
|
|
break;
|
2020-12-07 12:35:24 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-10-13 15:12:13 +00:00
|
|
|
|
|
|
|
pub fn watch_ctrl_c() -> watch::Receiver<bool> {
|
|
|
|
let (send_cancel, watch_cancel) = watch::channel(false);
|
|
|
|
tokio::spawn(async move {
|
|
|
|
tokio::signal::ctrl_c()
|
|
|
|
.await
|
|
|
|
.expect("failed to install CTRL+C signal handler");
|
|
|
|
info!("Received CTRL+C, shutting down.");
|
|
|
|
send_cancel.send(true).unwrap();
|
|
|
|
});
|
|
|
|
watch_cancel
|
|
|
|
}
|