use std::{
pin::Pin,
sync::Arc,
task::{Context, Poll},
};
use futures::{future::BoxFuture, FutureExt, Stream, StreamExt};
use nimiq_network_interface::{network::Network, request::RequestError};
use nimiq_primitives::key_nibbles::KeyNibbles;
use parking_lot::RwLock;
use super::{RequestChunk, ResponseChunk};
use crate::sync::{peer_list::PeerList, sync_queue::SyncQueue};
pub struct ChunkRequestComponent<N: Network> {
sync_queue:
SyncQueue<N, RequestChunk, (ResponseChunk, RequestChunk, N::PeerId), RequestError, ()>,
peers: Arc<RwLock<PeerList<N>>>,
}
impl<N: Network> ChunkRequestComponent<N> {
const NUM_PENDING_CHUNKS: usize = 1;
pub fn new(network: Arc<N>, peers: Arc<RwLock<PeerList<N>>>) -> Self {
let sync_queue = SyncQueue::with_verification(
network,
vec![],
Arc::clone(&peers),
Self::NUM_PENDING_CHUNKS,
|request_chunk: RequestChunk, network, peer_id| {
async move {
Self::request_missing_chunks_from_peer(network, peer_id, request_chunk.clone())
.await
.map(|res| (res, request_chunk, peer_id))
}
.boxed()
},
|request, (response, _, peer_id), _| {
if let ResponseChunk::Chunk(chunk) = response
&& chunk.chunk.items.len() > request.limit as usize
{
debug!(
"Peer[{}] Chunk size exceeded the request limit. Req: {:?} Chunk size: {}",
peer_id,
request,
chunk.chunk.items.len()
);
return false;
}
true
},
(),
);
ChunkRequestComponent { sync_queue, peers }
}
pub fn remove_peer(&mut self, peer_id: &N::PeerId) {
self.peers.write().remove_peer(peer_id);
}
pub fn has_pending_requests(&self) -> bool {
!self.sync_queue.is_empty()
}
pub fn request_chunk(&mut self, request: RequestChunk) {
self.sync_queue.add_ids(vec![(request, None)]);
}
async fn request_missing_chunks_from_peer(
network: Arc<N>,
peer_id: N::PeerId,
request: RequestChunk,
) -> Result<ResponseChunk, RequestError> {
network.request::<RequestChunk>(request, peer_id).await
}
pub fn wait_for_peers(&self) -> Option<BoxFuture<'static, ()>> {
self.peers.read().wait_for_peers()
}
}
impl<N: Network> Stream for ChunkRequestComponent<N> {
type Item = (ResponseChunk, KeyNibbles, N::PeerId);
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
while let Poll::Ready(Some(result)) = self.sync_queue.poll_next_unpin(cx) {
match result {
Ok((response, request, peer_id)) => {
return Poll::Ready(Some((response, request.start_key, peer_id)));
}
Err(req) => {
debug!(
"Failed to retrieve missing chunks for target hash {:?}",
req
);
}
}
}
Poll::Pending
}
}