diplonat/src/consul_actor.rs

54 lines
1.5 KiB
Rust
Raw Normal View History

2020-05-22 09:34:12 +00:00
use crate::consul::Consul;
use tokio::sync::watch;
2020-05-22 10:25:44 +00:00
use tokio::time::delay_for;
use crate::messages;
use anyhow::Result;
use std::cmp;
use std::time::Duration;
use log::*;
2020-05-22 09:34:12 +00:00
pub struct ConsulActor {
2020-05-22 10:25:44 +00:00
pub rx_open_ports: watch::Receiver<messages::OpenPorts>,
consul: Consul,
node: String,
retries: u32,
tx_open_ports: watch::Sender<messages::OpenPorts>
}
fn retry_to_time(retries: u32, max_time: Duration) -> Duration {
// 1.2^x seems to be a good value to exponentially increase time at a good pace
// eg. 1.2^32 = 341 seconds ~= 5 minutes - ie. after 32 retries we wait 5 minutes
return Duration::from_secs(cmp::max(max_time.as_secs(), 1.2f64.powf(retries as f64) as u64))
2020-05-22 09:34:12 +00:00
}
impl ConsulActor {
2020-05-22 10:29:55 +00:00
pub fn new(url: &str, node: &str) -> Self {
2020-05-22 10:25:44 +00:00
let (tx, rx) = watch::channel(messages::OpenPorts{ports: Vec::new() });
2020-05-22 09:34:12 +00:00
return Self {
2020-05-22 10:25:44 +00:00
consul: Consul::new(url),
rx_open_ports: rx,
tx_open_ports: tx,
node: node.to_string(),
retries: 0,
2020-05-22 09:34:12 +00:00
};
}
2020-05-22 10:25:44 +00:00
2020-05-22 10:29:55 +00:00
pub async fn listen(&mut self) -> Result<()> {
2020-05-22 10:25:44 +00:00
loop {
let catalog = match self.consul.watch_node(&self.node).await {
Ok(c) => c,
Err(e) => {
self.retries = cmp::min(u32::MAX - 1, self.retries) + 1;
let will_retry_in = retry_to_time(self.retries, Duration::from_secs(600));
error!("Failed to query consul. Will retry in {}s. {}", will_retry_in.as_secs(), e);
delay_for(will_retry_in).await;
continue;
}
};
2020-05-22 10:29:55 +00:00
info!("{:#?}", catalog);
2020-05-22 10:25:44 +00:00
}
}
2020-05-22 09:34:12 +00:00
}