use crate::{strategy::StrategyKey, LOG_TARGET};
use futures::{
channel::oneshot,
future::BoxFuture,
stream::{BoxStream, FusedStream, Stream},
FutureExt, StreamExt,
};
use log::error;
use std::any::Any;
use sc_network::{request_responses::RequestFailure, types::ProtocolName};
use sc_network_types::PeerId;
use std::task::{Context, Poll, Waker};
use tokio_stream::StreamMap;
type ResponseResult =
Result<Result<(Box<dyn Any + Send>, ProtocolName), RequestFailure>, oneshot::Canceled>;
pub(crate) type ResponseFuture = BoxFuture<'static, ResponseResult>;
pub(crate) struct ResponseEvent {
pub peer_id: PeerId,
pub key: StrategyKey,
pub response: ResponseResult,
}
pub(crate) struct PendingResponses {
pending_responses: StreamMap<(PeerId, StrategyKey), BoxStream<'static, ResponseResult>>,
waker: Option<Waker>,
}
impl PendingResponses {
pub fn new() -> Self {
Self { pending_responses: StreamMap::new(), waker: None }
}
pub fn insert(&mut self, peer_id: PeerId, key: StrategyKey, response_future: ResponseFuture) {
if self
.pending_responses
.insert((peer_id, key), Box::pin(response_future.into_stream()))
.is_some()
{
error!(
target: LOG_TARGET,
"Discarded pending response from peer {peer_id}, strategy key: {key:?}.",
);
debug_assert!(false);
}
if let Some(waker) = self.waker.take() {
waker.wake();
}
}
pub fn remove(&mut self, peer_id: PeerId, key: StrategyKey) -> bool {
self.pending_responses.remove(&(peer_id, key)).is_some()
}
pub fn remove_all(&mut self, peer_id: &PeerId) {
let to_remove = self
.pending_responses
.keys()
.filter(|(peer, _key)| peer == peer_id)
.cloned()
.collect::<Vec<_>>();
to_remove.iter().for_each(|k| {
self.pending_responses.remove(k);
});
}
pub fn len(&self) -> usize {
self.pending_responses.len()
}
}
impl Stream for PendingResponses {
type Item = ResponseEvent;
fn poll_next(
mut self: std::pin::Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Self::Item>> {
match self.pending_responses.poll_next_unpin(cx) {
Poll::Ready(Some(((peer_id, key), response))) => {
self.pending_responses.remove(&(peer_id, key));
Poll::Ready(Some(ResponseEvent { peer_id, key, response }))
},
Poll::Ready(None) | Poll::Pending => {
self.waker = Some(cx.waker().clone());
Poll::Pending
},
}
}
}
impl FusedStream for PendingResponses {
fn is_terminated(&self) -> bool {
false
}
}