use alloc::collections::BTreeMap;
use alloc::vec::Vec;
use crate::connect::proto::{
EndpointDescription, LONG_POLL_HOLD, NodeDescription, NodeId, WaitAction, WaitForPairing,
WaitInstruction,
};
#[derive(Debug, Clone, Default)]
pub struct WaitingNode {
pub description: Option<NodeDescription>,
pub endpoint: Option<EndpointDescription>,
pub error: Option<crate::connect::proto::WaitErrorMessage>,
}
#[derive(Debug, Default)]
pub(super) struct LongPoll {
state: std::sync::Mutex<State>,
woken: tokio::sync::Notify,
}
#[derive(Debug, Default)]
struct State {
pending: BTreeMap<NodeId, WaitAction>,
seen: BTreeMap<NodeId, (WaitingNode, std::time::Instant)>,
}
impl LongPoll {
pub(super) const MAX_WAITING: usize = 256;
pub(super) const SEEN_TTL: core::time::Duration = core::time::Duration::from_mins(5);
pub(super) const MAX_PER_POLL: usize = 32;
pub(super) fn instruct(&self, client: NodeId, action: WaitAction) {
if let Ok(mut state) = self.state.lock() {
if state.pending.len() < Self::MAX_WAITING || state.pending.contains_key(&client) {
state.pending.insert(client, action);
}
}
self.woken.notify_waiters();
}
pub(super) fn waiting(&self) -> Vec<(NodeId, WaitingNode)> {
self.state.lock().map_or_else(
|_| Vec::new(),
|state| {
state
.seen
.iter()
.map(|(id, (node, _))| (*id, node.clone()))
.collect()
},
)
}
fn take(&self, nodes: &[WaitForPairing]) -> Vec<WaitInstruction> {
let Ok(mut state) = self.state.lock() else {
return Vec::new();
};
let now = std::time::Instant::now();
state
.seen
.retain(|_, (_, at)| now.saturating_duration_since(*at) < Self::SEEN_TTL);
let mut out = Vec::new();
for node in nodes.iter().take(Self::MAX_PER_POLL) {
if !state.seen.contains_key(&node.client_node_id)
&& state.seen.len() >= Self::MAX_WAITING
{
continue;
}
let (seen, at) = state
.seen
.entry(node.client_node_id)
.or_insert_with(|| (WaitingNode::default(), now));
*at = now;
if node.client_node_description.is_some() {
seen.description.clone_from(&node.client_node_description);
}
if node.client_endpoint_description.is_some() {
seen.endpoint.clone_from(&node.client_endpoint_description);
}
seen.error = node.error_message;
if let Some(action) = state.pending.remove(&node.client_node_id) {
out.push(WaitInstruction {
client_node_id: node.client_node_id,
action,
});
}
}
out
}
pub(super) async fn poll(&self, nodes: &[WaitForPairing]) -> Vec<WaitInstruction> {
let ready = self.take(nodes);
if !ready.is_empty() {
return ready;
}
let woken = self.woken.notified();
tokio::pin!(woken);
woken.as_mut().enable();
let ready = self.take(nodes);
if !ready.is_empty() {
return ready;
}
let hold = core::time::Duration::from(LONG_POLL_HOLD);
if tokio::time::timeout(hold, woken).await.is_err() {
return Vec::new();
}
self.take(nodes)
}
}