use error::RoutingError;
#[cfg(feature = "use-mock-crust")]
use fake_clock::FakeClock as Instant;
use maidsafe_utilities::serialisation;
use message_filter::MessageFilter;
use messages::RoutingMessage;
use sha3;
use std::collections::BTreeMap;
use std::fmt;
use std::time::Duration;
#[cfg(not(feature = "use-mock-crust"))]
use std::time::Instant;
use tiny_keccak::sha3_256;
pub const ACK_TIMEOUT_SECS: u64 = 20;
const EXPIRY_DURATION_SECS: u64 = 4 * 60;
#[derive(Clone, Debug)]
pub struct UnacknowledgedMessage {
pub routing_msg: RoutingMessage,
pub route: u8,
pub timer_token: u64,
pub expires_at: Option<Instant>,
}
pub struct AckManager {
pending: BTreeMap<Ack, UnacknowledgedMessage>,
received: MessageFilter<Ack>,
}
#[derive(Clone, Copy, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
pub struct Ack {
m_hash: sha3::Digest256,
}
impl AckManager {
pub fn new() -> Self {
let expiry_duration = Duration::from_secs(EXPIRY_DURATION_SECS);
AckManager {
pending: BTreeMap::new(),
received: MessageFilter::with_expiry_duration(expiry_duration),
}
}
pub fn receive(&mut self, ack: Ack) {
let _ack = self.pending.remove(&ack);
let _ = self.received.insert(&ack);
}
pub fn did_receive(&mut self, ack: Ack) -> bool {
self.received.contains(&ack)
}
pub fn add_to_pending(
&mut self,
ack: Ack,
unacked_msg: UnacknowledgedMessage,
) -> Option<UnacknowledgedMessage> {
self.pending.insert(ack, unacked_msg)
}
pub fn find_timed_out(&mut self, token: u64) -> Option<(UnacknowledgedMessage, Ack)> {
let timed_out_ack = if let Some((sip_hash, _)) =
self.pending.iter().find(|&(_, unacked_msg)| {
unacked_msg.timer_token == token
})
{
*sip_hash
} else {
return None;
};
let mut unacked_msg = unwrap!(self.pending.remove(&timed_out_ack));
unacked_msg.route += 1;
Some((unacked_msg, timed_out_ack))
}
pub fn remove(&mut self, ack: &Ack) -> Option<UnacknowledgedMessage> {
self.pending.remove(ack)
}
}
impl Ack {
pub fn compute(routing_msg: &RoutingMessage) -> Result<Ack, RoutingError> {
let hash_msg = serialisation::serialise(routing_msg)?;
Ok(Ack { m_hash: sha3_256(&hash_msg) })
}
}
impl fmt::Debug for Ack {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
write!(
formatter,
"Ack({:02x}{:02x}..)",
self.m_hash[0],
self.m_hash[1]
)
}
}