use std::time::Duration;
use tracing::{debug, trace};
use super::super::constants::MESSAGE_TIMEOUT_SECS;
use super::super::node::DhtNode;
use super::DhtTask;
pub struct DhtPingTask {
remote_node: DhtNode,
max_retry: u32,
retry_count: u32,
success: bool,
done: bool,
timeout: Duration,
}
impl DhtPingTask {
pub fn new(remote_node: DhtNode, max_retry: u32) -> Self {
Self {
remote_node,
max_retry,
retry_count: 0,
success: false,
done: false,
timeout: Duration::from_secs(MESSAGE_TIMEOUT_SECS),
}
}
pub fn on_response(&mut self) {
debug!(addr = %self.remote_node.addr(), "Ping successful");
self.success = true;
self.done = true;
}
pub fn on_timeout(&mut self) -> bool {
self.retry_count += 1;
if self.retry_count > self.max_retry {
debug!(
addr = %self.remote_node.addr(),
retries = self.retry_count,
"Ping failed after max retries"
);
self.done = true;
return false; }
trace!(
addr = %self.remote_node.addr(),
retry = self.retry_count,
"Ping timeout, retrying"
);
true }
pub fn remote_node(&self) -> &DhtNode {
&self.remote_node
}
pub fn is_success(&self) -> bool {
self.success
}
pub fn timeout(&self) -> Duration {
self.timeout
}
}
impl DhtTask for DhtPingTask {
fn startup(&mut self) {
trace!(addr = %self.remote_node.addr(), "Starting ping task");
}
fn finished(&self) -> bool {
self.done
}
}