use std::time::Duration;
use tracing::{debug, info};
use super::bucket::Bucket;
use super::node::DhtNode;
use super::socket::DhtSocket;
use super::tracker::TransactionTracker;
const MAX_RETRY: u32 = 2;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ReplaceNodeResult {
NodeAlive,
NodeReplaced,
NoQuestionableNode,
Failed(String),
}
pub async fn replace_node(
bucket: &mut Bucket,
new_node: &DhtNode,
socket: &DhtSocket,
_tracker: &TransactionTracker,
timeout: Duration,
) -> ReplaceNodeResult {
let (q_id, q_addr) = match bucket.get_lru_questionable_node() {
Some(node) => (node.id, node.addr),
None => return ReplaceNodeResult::NoQuestionableNode,
};
debug!(
"ReplaceNode: pinging questionable node {} (attempt 1/{})",
hex::encode(q_id),
MAX_RETRY,
);
for attempt in 1..=MAX_RETRY {
let self_id = new_node.id;
let msg = super::message::DhtMessageBuilder::ping(0, &self_id);
let encoded = match msg.encode() {
Ok(e) => e,
Err(e) => return ReplaceNodeResult::Failed(format!("encode error: {}", e)),
};
if let Err(e) = socket.send_to(q_addr, &encoded).await {
debug!(
"ReplaceNode: failed to send ping to {}: {}",
hex::encode(q_id),
e
);
return ReplaceNodeResult::Failed(format!("send error: {}", e));
}
let mut buf = [0u8; 4096];
match socket.recv_with_timeout(&mut buf, timeout).await {
Ok((len, _from)) if len > 0 => {
if let Ok(response) = super::message::DhtMessage::decode(&buf[..len])
&& response.is_response()
{
info!(
"ReplaceNode: ping reply received from {} — node is alive",
hex::encode(q_id)
);
bucket.mark_good(&q_id);
return ReplaceNodeResult::NodeAlive;
}
}
_ => {
}
}
if attempt < MAX_RETRY {
debug!(
"ReplaceNode: ping timeout from {}, retrying (attempt {}/{})",
hex::encode(q_id),
attempt + 1,
MAX_RETRY,
);
}
}
info!(
"ReplaceNode: ping failed {} times, replacing {} with {}",
MAX_RETRY,
hex::encode(q_id),
new_node.id_hex(),
);
bucket.mark_bad(&q_id);
bucket.add_node(new_node.clone());
ReplaceNodeResult::NodeReplaced
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_replace_node_result_variants() {
assert_eq!(ReplaceNodeResult::NodeAlive, ReplaceNodeResult::NodeAlive);
assert_eq!(
ReplaceNodeResult::NodeReplaced,
ReplaceNodeResult::NodeReplaced
);
assert_eq!(
ReplaceNodeResult::NoQuestionableNode,
ReplaceNodeResult::NoQuestionableNode
);
}
}