use std::collections::HashMap;
use futures::channel::oneshot::Sender;
use hotshot_types::request_response::{Request, Response};
use libp2p::request_response::{Message, OutboundRequestId};
use crate::network::NetworkEvent;
#[derive(Default, Debug)]
pub(crate) struct RequestResponseState {
request_map: HashMap<OutboundRequestId, Sender<Option<Response>>>,
}
impl RequestResponseState {
pub fn handle_request_response(
&mut self,
event: libp2p::request_response::Event<Request, Response>,
) -> Option<NetworkEvent> {
match event {
libp2p::request_response::Event::Message { peer: _, message } => match message {
Message::Request {
request_id: _,
request,
channel,
} => Some(NetworkEvent::ResponseRequested(request, channel)),
Message::Response {
request_id,
response,
} => {
let chan = self.request_map.remove(&request_id)?;
if chan.send(Some(response)).is_err() {
tracing::warn!("Failed to send response to client, channel closed.");
}
None
}
},
libp2p::request_response::Event::OutboundFailure {
peer: _,
request_id,
error,
} => {
tracing::warn!("Error Sending Request {:?}", error);
let chan = self.request_map.remove(&request_id)?;
if chan.send(None).is_err() {
tracing::warn!("Failed to send response to client, channel closed.");
}
None
}
libp2p::request_response::Event::InboundFailure { .. }
| libp2p::request_response::Event::ResponseSent { .. } => None,
}
}
pub fn add_request(&mut self, id: OutboundRequestId, chan: Sender<Option<Response>>) {
self.request_map.insert(id, chan);
}
}