1#[cfg(all(test, not(miri)))]
38mod tests;
39
40use ab_aligned_buffer::alignment::{Align1, Alignment};
41use ab_aligned_buffer::{OwnedAlignedBuffer, SharedAlignedBuffer};
42use async_trait::async_trait;
43use futures::channel::{mpsc, oneshot};
44use futures::prelude::*;
45use futures::stream::FuturesUnordered;
46use libp2p::StreamProtocol;
47use libp2p::core::transport::PortUse;
48use libp2p::core::{Endpoint, Multiaddr};
49use libp2p::identity::PeerId;
50use libp2p::request_response::{
51 Behaviour as RequestResponse, Codec as RequestResponseCodec, Config as RequestResponseConfig,
52 Event as RequestResponseEvent, InboundRequestId, Message as RequestResponseMessage,
53 OutboundRequestId, ProtocolSupport, ResponseChannel,
54};
55pub use libp2p::request_response::{InboundFailure, OutboundFailure};
56use libp2p::swarm::behaviour::{ConnectionClosed, DialFailure, FromSwarm, ListenFailure};
57use libp2p::swarm::handler::multi::MultiHandler;
58use libp2p::swarm::{
59 ConnectionDenied, ConnectionId, NetworkBehaviour, THandlerInEvent, THandlerOutEvent, ToSwarm,
60};
61use std::borrow::Cow;
62use std::collections::HashMap;
63use std::collections::hash_map::Entry;
64use std::pin::Pin;
65use std::task::{Context, Poll};
66use std::time::{Duration, Instant};
67use std::{fmt, io, iter};
68use tracing::{debug, error, warn};
69
70const LOG_TARGET: &str = "request-response-protocols";
71
72#[async_trait]
74pub trait RequestHandler: Send {
75 async fn run(&mut self);
77
78 fn protocol_config(&self) -> ProtocolConfig;
80
81 fn protocol_name(&self) -> &'static str;
83
84 fn clone_box(&self) -> Box<dyn RequestHandler>;
86}
87
88impl Clone for Box<dyn RequestHandler> {
89 fn clone(&self) -> Self {
90 self.clone_box()
91 }
92}
93
94#[derive(Debug, Clone)]
96pub struct ProtocolConfig {
97 pub name: &'static str,
99
100 pub max_request_size: u64,
105
106 pub max_response_size: u64,
111
112 pub request_timeout: Duration,
116
117 pub inbound_queue: Option<mpsc::Sender<IncomingRequest>>,
138}
139
140impl ProtocolConfig {
141 pub fn new(protocol_name: &'static str) -> ProtocolConfig {
143 ProtocolConfig {
144 name: protocol_name,
145 max_request_size: 1024 * 1024,
146 max_response_size: 16 * 1024 * 1024,
147 request_timeout: Duration::from_secs(20),
148 inbound_queue: None,
149 }
150 }
151}
152
153#[derive(Debug)]
155pub struct IncomingRequest {
156 pub peer: PeerId,
158
159 pub payload: Vec<u8>,
162
163 pub pending_response: oneshot::Sender<OutgoingResponse>,
172}
173
174#[derive(Debug, Default, Clone)]
179pub struct ResponsePayload {
180 buffers: Vec<SharedAlignedBuffer<Align1>>,
181}
182
183impl<A> From<SharedAlignedBuffer<A>> for ResponsePayload
184where
185 A: Alignment,
186{
187 #[inline]
188 fn from(buffer: SharedAlignedBuffer<A>) -> Self {
189 let mut payload = Self::default();
190 payload.push(buffer);
191 payload
192 }
193}
194
195impl ResponsePayload {
196 #[inline]
198 pub fn push<A>(&mut self, buffer: SharedAlignedBuffer<A>)
199 where
200 A: Alignment,
201 {
202 if !buffer.is_empty() {
203 self.buffers.push(buffer.into_start_align());
204 }
205 }
206
207 #[inline]
209 pub fn len(&self) -> usize {
210 self.buffers
211 .iter()
212 .map(|buffer| buffer.len() as usize)
213 .sum()
214 }
215
216 #[inline]
218 pub fn is_empty(&self) -> bool {
219 self.buffers.is_empty()
220 }
221
222 #[inline]
224 pub fn buffers(&self) -> &[SharedAlignedBuffer<Align1>] {
225 &self.buffers
226 }
227
228 pub fn into_buffer(mut self) -> SharedAlignedBuffer<Align1> {
234 if self.buffers.len() <= 1 {
235 return self.buffers.pop().unwrap_or_default();
236 }
237
238 let capacity = u32::try_from(self.len()).unwrap_or(u32::MAX);
239 let mut buffer = OwnedAlignedBuffer::<Align1>::with_capacity(capacity);
240 for part in &self.buffers {
241 buffer
242 .append(part)
243 .unwrap_or_else(|error| panic!("Failed to concatenate payload: {error}"));
244 }
245 buffer.into_shared()
246 }
247}
248
249#[derive(Debug)]
251pub struct OutgoingResponse {
252 pub result: Result<ResponsePayload, ()>,
256
257 pub sent_feedback: Option<oneshot::Sender<()>>,
266}
267
268#[derive(Debug)]
270pub enum Event {
273 InboundRequest {
277 peer: PeerId,
279 protocol: Cow<'static, str>,
281 result: Result<(), ResponseFailure>,
286 },
287
288 RequestFinished {
293 peer: Option<PeerId>,
295 protocol: Cow<'static, str>,
297 duration: Duration,
299 result: Result<(), String>,
301 },
302}
303
304#[derive(Debug, Clone, PartialEq, Eq, Hash)]
311struct ProtocolRequestId {
312 protocol: Cow<'static, str>,
313 request_id: OutboundRequestId,
314}
315
316impl From<(Cow<'static, str>, OutboundRequestId)> for ProtocolRequestId {
317 #[inline]
318 fn from((protocol, request_id): (Cow<'static, str>, OutboundRequestId)) -> Self {
319 Self {
320 protocol,
321 request_id,
322 }
323 }
324}
325
326#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
328pub enum IfDisconnected {
329 TryConnect,
331 ImmediateError,
333}
334
335impl IfDisconnected {
337 pub fn should_connect(self) -> bool {
339 match self {
340 Self::TryConnect => true,
341 Self::ImmediateError => false,
342 }
343 }
344}
345
346#[expect(
349 clippy::type_complexity,
350 reason = "To preserve compatibility with copied implementation"
351)]
352pub struct RequestResponseFactoryBehaviour {
353 protocols: HashMap<
357 Cow<'static, str>,
358 (
359 RequestResponse<GenericCodec>,
360 Option<mpsc::Sender<IncomingRequest>>,
361 ),
362 >,
363
364 pending_requests: HashMap<
366 ProtocolRequestId,
367 (
368 Instant,
369 oneshot::Sender<Result<SharedAlignedBuffer<Align1>, RequestFailure>>,
370 ),
371 >,
372
373 pending_responses: stream::FuturesUnordered<
376 Pin<Box<dyn Future<Output = Option<RequestProcessingOutcome>> + Send>>,
377 >,
378
379 message_request: Option<MessageRequest>,
382
383 request_handlers: Vec<Pin<Box<dyn Future<Output = ()> + Send>>>,
385}
386
387impl fmt::Debug for RequestResponseFactoryBehaviour {
388 #[inline]
389 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
390 f.debug_struct("RequestResponseFactoryBehaviour")
391 .finish_non_exhaustive()
392 }
393}
394
395struct MessageRequest {
397 peer: PeerId,
398 request_id: InboundRequestId,
399 request: Vec<u8>,
400 channel: ResponseChannel<Result<ResponsePayload, ()>>,
401 protocol: String,
402 response_builder: Option<mpsc::Sender<IncomingRequest>>,
403}
404
405struct RequestProcessingOutcome {
407 request_id: InboundRequestId,
408 protocol: Cow<'static, str>,
409 inner_channel: ResponseChannel<Result<ResponsePayload, ()>>,
410 response: OutgoingResponse,
411}
412
413impl RequestResponseFactoryBehaviour {
414 pub fn new<List>(list: List, max_concurrent_streams: usize) -> Result<Self, RegisterError>
417 where
418 List: IntoIterator<Item = Box<dyn RequestHandler>>,
419 {
420 let mut protocols = HashMap::new();
421 let mut request_handlers = Vec::new();
422 for mut handler in list {
423 let config = handler.protocol_config();
424
425 let protocol_support = if config.inbound_queue.is_some() {
426 ProtocolSupport::Full
427 } else {
428 ProtocolSupport::Outbound
429 };
430
431 let rq_rp = RequestResponse::with_codec(
432 GenericCodec {
433 max_request_size: config.max_request_size,
434 max_response_size: config.max_response_size,
435 },
436 iter::once(StreamProtocol::new(config.name)).zip(iter::repeat(protocol_support)),
437 RequestResponseConfig::default()
438 .with_request_timeout(config.request_timeout)
439 .with_max_concurrent_streams(max_concurrent_streams),
440 );
441
442 match protocols.entry(Cow::Borrowed(config.name)) {
443 Entry::Vacant(e) => e.insert((rq_rp, config.inbound_queue)),
444 Entry::Occupied(e) => {
445 return Err(RegisterError::DuplicateProtocol(e.key().clone()));
446 }
447 };
448
449 let request_handler_run: Pin<Box<dyn Future<Output = ()> + Send>> =
450 Box::pin(async move { handler.run().await }.fuse());
451
452 request_handlers.push(request_handler_run);
453 }
454
455 Ok(Self {
456 protocols,
457 pending_requests: HashMap::new(),
458 pending_responses: FuturesUnordered::new(),
459 message_request: None,
460 request_handlers,
461 })
462 }
463
464 pub fn send_request(
471 &mut self,
472 target: &PeerId,
473 protocol_name: &str,
474 request: Vec<u8>,
475 pending_response: oneshot::Sender<Result<SharedAlignedBuffer<Align1>, RequestFailure>>,
476 connect: IfDisconnected,
477 addresses: Vec<Multiaddr>,
478 ) {
479 if let Some((protocol, _)) = self.protocols.get_mut(protocol_name) {
480 if protocol.is_connected(target) || connect.should_connect() {
481 let request_id = protocol.send_request_with_addresses(target, request, addresses);
482 let prev_req_id = self.pending_requests.insert(
483 (protocol_name.to_string().into(), request_id).into(),
484 (Instant::now(), pending_response),
485 );
486 debug_assert!(prev_req_id.is_none(), "Expect request id to be unique.");
487 } else if pending_response
488 .send(Err(RequestFailure::NotConnected))
489 .is_err()
490 {
491 debug!(
492 target: LOG_TARGET,
493 "Not connected to peer {:?}. At the same time local \
494 node is no longer interested in the result.",
495 target,
496 );
497 }
498 } else if pending_response
499 .send(Err(RequestFailure::UnknownProtocol))
500 .is_err()
501 {
502 debug!(
503 target: LOG_TARGET,
504 "Unknown protocol {:?}. At the same time local \
505 node is no longer interested in the result.",
506 protocol_name,
507 );
508 }
509 }
510}
511
512impl NetworkBehaviour for RequestResponseFactoryBehaviour {
513 type ConnectionHandler = MultiHandler<
514 String,
515 <RequestResponse<GenericCodec> as NetworkBehaviour>::ConnectionHandler,
516 >;
517 type ToSwarm = Event;
518
519 fn handle_established_inbound_connection(
520 &mut self,
521 connection_id: ConnectionId,
522 peer: PeerId,
523 local_addr: &Multiaddr,
524 remote_addr: &Multiaddr,
525 ) -> Result<Self::ConnectionHandler, ConnectionDenied> {
526 let iter = self.protocols.iter_mut().map(|(p, (r, _))| {
527 (
528 p.to_string(),
529 r.handle_established_inbound_connection(
530 connection_id,
531 peer,
532 local_addr,
533 remote_addr,
534 )
535 .expect(
536 "Behaviours return handlers in these methods with the exception of \
537 'connection management' behaviours like connection-limits or allow-black list. \
538 So, inner request-response behaviour always returns Ok(handler).",
539 ),
540 )
541 });
542
543 let handler = MultiHandler::try_from_iter(iter).expect(
544 "Protocols are in a HashMap and there can be at most one handler per protocol name, \
545 which is the only possible error; qed",
546 );
547
548 Ok(handler)
549 }
550
551 fn handle_established_outbound_connection(
552 &mut self,
553 connection_id: ConnectionId,
554 peer: PeerId,
555 addr: &Multiaddr,
556 role_override: Endpoint,
557 port_use: PortUse,
558 ) -> Result<Self::ConnectionHandler, ConnectionDenied> {
559 let iter = self.protocols.iter_mut().map(|(p, (r, _))| {
560 (
561 p.to_string(),
562 r.handle_established_outbound_connection(
563 connection_id,
564 peer,
565 addr,
566 role_override,
567 port_use,
568 )
569 .expect(
570 "Behaviours return handlers in these methods with the exception of \
571 'connection management' behaviours like connection-limits or allow-black \
572 list. So, inner request-response behaviour always returns Ok(handler).",
573 ),
574 )
575 });
576
577 let handler = MultiHandler::try_from_iter(iter).expect(
578 "Protocols are in a HashMap and there can be at most one handler per protocol name, \
579 which is the only possible error; qed",
580 );
581
582 Ok(handler)
583 }
584
585 fn on_swarm_event(&mut self, event: FromSwarm<'_>) {
587 match event {
588 FromSwarm::ConnectionEstablished(inner) => {
589 for (protocol, _) in self.protocols.values_mut() {
590 protocol.on_swarm_event(FromSwarm::ConnectionEstablished(inner));
591 }
592 }
593 FromSwarm::ConnectionClosed(inner) => {
594 for (protocol, _) in self.protocols.values_mut() {
595 protocol.on_swarm_event(FromSwarm::ConnectionClosed(ConnectionClosed {
596 peer_id: inner.peer_id,
597 connection_id: inner.connection_id,
598 endpoint: inner.endpoint,
599 cause: inner.cause,
600 remaining_established: inner.remaining_established,
601 }));
602 }
603 }
604 FromSwarm::AddressChange(inner) => {
605 for (protocol, _) in self.protocols.values_mut() {
606 protocol.on_swarm_event(FromSwarm::AddressChange(inner));
607 }
608 }
609 FromSwarm::DialFailure(inner) => {
610 for (protocol, _) in self.protocols.values_mut() {
611 protocol.on_swarm_event(FromSwarm::DialFailure(DialFailure {
612 peer_id: inner.peer_id,
613 error: inner.error,
614 connection_id: inner.connection_id,
615 }));
616 }
617 }
618 FromSwarm::ListenFailure(inner) => {
619 for (protocol, _) in self.protocols.values_mut() {
620 protocol.on_swarm_event(FromSwarm::ListenFailure(ListenFailure {
621 local_addr: inner.local_addr,
622 send_back_addr: inner.send_back_addr,
623 error: inner.error,
624 connection_id: inner.connection_id,
625 peer_id: inner.peer_id,
626 }));
627 }
628 }
629 FromSwarm::NewListener(inner) => {
630 for (protocol, _) in self.protocols.values_mut() {
631 protocol.on_swarm_event(FromSwarm::NewListener(inner));
632 }
633 }
634 FromSwarm::NewListenAddr(inner) => {
635 for (protocol, _) in self.protocols.values_mut() {
636 protocol.on_swarm_event(FromSwarm::NewListenAddr(inner));
637 }
638 }
639 FromSwarm::ExpiredListenAddr(inner) => {
640 for (protocol, _) in self.protocols.values_mut() {
641 protocol.on_swarm_event(FromSwarm::ExpiredListenAddr(inner));
642 }
643 }
644 FromSwarm::ListenerError(inner) => {
645 for (protocol, _) in self.protocols.values_mut() {
646 protocol.on_swarm_event(FromSwarm::ListenerError(inner));
647 }
648 }
649 FromSwarm::ListenerClosed(inner) => {
650 for (protocol, _) in self.protocols.values_mut() {
651 protocol.on_swarm_event(FromSwarm::ListenerClosed(inner));
652 }
653 }
654 FromSwarm::NewExternalAddrCandidate(inner) => {
655 for (protocol, _) in self.protocols.values_mut() {
656 protocol.on_swarm_event(FromSwarm::NewExternalAddrCandidate(inner));
657 }
658 }
659 FromSwarm::ExternalAddrConfirmed(inner) => {
660 for (protocol, _) in self.protocols.values_mut() {
661 protocol.on_swarm_event(FromSwarm::ExternalAddrConfirmed(inner));
662 }
663 }
664 FromSwarm::ExternalAddrExpired(inner) => {
665 for (protocol, _) in self.protocols.values_mut() {
666 protocol.on_swarm_event(FromSwarm::ExternalAddrExpired(inner));
667 }
668 }
669 FromSwarm::NewExternalAddrOfPeer(inner) => {
670 for (protocol, _) in self.protocols.values_mut() {
671 protocol.on_swarm_event(FromSwarm::NewExternalAddrOfPeer(inner));
672 }
673 }
674 event => {
675 warn!(
676 ?event,
677 "New event must be forwarded to request response protocols"
678 );
679 }
680 }
681 }
682
683 fn on_connection_handler_event(
684 &mut self,
685 peer_id: PeerId,
686 connection: ConnectionId,
687 event: THandlerOutEvent<Self>,
688 ) {
689 let p_name = event.0;
690 if let Some((proto, _)) = self.protocols.get_mut(&*p_name) {
691 return proto.on_connection_handler_event(peer_id, connection, event.1);
692 }
693
694 warn!(
695 target: LOG_TARGET,
696 "inject_node_event: no request-response instance registered for protocol {:?}", p_name
697 );
698 }
699
700 fn poll(
701 &mut self,
702 cx: &mut Context<'_>,
703 ) -> Poll<ToSwarm<Self::ToSwarm, THandlerInEvent<Self>>> {
704 'poll_all: loop {
705 if let Some(message_request) = self.message_request.take() {
706 let MessageRequest {
707 peer,
708 request_id,
709 request,
710 channel,
711 protocol,
712 response_builder,
713 } = message_request;
714
715 let (tx, rx) = oneshot::channel();
716
717 if let Some(mut response_builder) = response_builder {
720 let _: Result<(), _> = response_builder.try_send(IncomingRequest {
724 peer,
725 payload: request,
726 pending_response: tx,
727 });
728 } else {
729 debug_assert!(false, "Received message on outbound-only protocol.");
730 }
731
732 self.pending_responses.push(Box::pin(async move {
733 if let Ok(response) = rx.await {
737 Some(RequestProcessingOutcome {
738 request_id,
739 protocol: Cow::from(protocol),
740 inner_channel: channel,
741 response,
742 })
743 } else {
744 None
745 }
746 }));
747
748 continue 'poll_all;
751 }
752 while let Poll::Ready(Some(outcome)) = self.pending_responses.poll_next_unpin(cx) {
754 let Some(RequestProcessingOutcome {
755 request_id,
756 protocol: protocol_name,
757 inner_channel,
758 response:
759 OutgoingResponse {
760 result,
761 sent_feedback: _,
762 },
763 }) = outcome
764 else {
765 continue;
768 };
769
770 if let Ok(payload) = result
771 && let Some((protocol, _)) = self.protocols.get_mut(&*protocol_name)
772 && protocol.send_response(inner_channel, Ok(payload)).is_err()
773 {
774 debug!(
777 target: LOG_TARGET,
778 %request_id,
779 "Failed to send response for request on protocol {} due to a \
780 timeout or due to the connection to the peer being closed. \
781 Dropping response",
782 protocol_name,
783 );
784 }
785 }
786
787 for rq_rs_runner in &mut self.request_handlers {
788 let _: Poll<()> = rq_rs_runner.poll_unpin(cx);
790 }
791
792 for (protocol, (behaviour, response_builder)) in &mut self.protocols {
794 while let Poll::Ready(event) = behaviour.poll(cx) {
795 let event = match event {
796 ToSwarm::GenerateEvent(event) => event,
798
799 ToSwarm::Dial { opts } => {
802 if opts.get_peer_id().is_none() {
803 error!(
804 "The request-response isn't supposed to start dialing \
805 addresses"
806 );
807 }
808 return Poll::Ready(ToSwarm::Dial { opts });
809 }
810 ToSwarm::NotifyHandler {
811 peer_id,
812 handler,
813 event,
814 } => {
815 return Poll::Ready(ToSwarm::NotifyHandler {
816 peer_id,
817 handler,
818 event: ((*protocol).to_string(), event),
819 });
820 }
821 ToSwarm::CloseConnection {
822 peer_id,
823 connection,
824 } => {
825 return Poll::Ready(ToSwarm::CloseConnection {
826 peer_id,
827 connection,
828 });
829 }
830 ToSwarm::NewExternalAddrCandidate(observed) => {
831 return Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed));
832 }
833 ToSwarm::ExternalAddrConfirmed(addr) => {
834 return Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr));
835 }
836 ToSwarm::ExternalAddrExpired(addr) => {
837 return Poll::Ready(ToSwarm::ExternalAddrExpired(addr));
838 }
839 ToSwarm::ListenOn { opts } => {
840 return Poll::Ready(ToSwarm::ListenOn { opts });
841 }
842 ToSwarm::RemoveListener { id } => {
843 return Poll::Ready(ToSwarm::RemoveListener { id });
844 }
845 event => {
846 warn!(
847 ?event,
848 "New event from request response protocol must be send up"
849 );
850
851 continue;
852 }
853 };
854
855 #[expect(
856 clippy::rest_pattern_accessible_field,
857 reason = "Do not care about other fields"
858 )]
859 match event {
860 RequestResponseEvent::Message {
862 peer,
863 message:
864 RequestResponseMessage::Request {
865 request_id,
866 request,
867 channel,
868 },
869 ..
870 } => {
871 self.message_request = Some(MessageRequest {
872 peer,
873 request_id,
874 request,
875 channel,
876 protocol: protocol.to_string(),
877 response_builder: response_builder.clone(),
878 });
879
880 continue 'poll_all;
883 }
884
885 RequestResponseEvent::Message {
887 peer,
888 message:
889 RequestResponseMessage::Response {
890 request_id,
891 response,
892 },
893 ..
894 } => {
895 let (started, delivered) = if let Some((started, pending_response)) =
896 self.pending_requests
897 .remove(&(protocol.clone(), request_id).into())
898 {
899 let delivered = pending_response
900 .send(
901 response
902 .map(ResponsePayload::into_buffer)
903 .map_err(|()| RequestFailure::Refused),
904 )
905 .map_err(|_error_result| RequestFailure::Obsolete.to_string());
906 (started, delivered)
907 } else {
908 warn!(
909 target: LOG_TARGET,
910 "Received `RequestResponseEvent::Message` with unexpected request id {:?}",
911 request_id,
912 );
913 debug_assert!(false);
914 continue;
915 };
916
917 let out = Event::RequestFinished {
918 peer: Some(peer),
919 protocol: protocol.clone(),
920 duration: started.elapsed(),
921 result: delivered,
922 };
923
924 return Poll::Ready(ToSwarm::GenerateEvent(out));
925 }
926
927 RequestResponseEvent::OutboundFailure {
929 peer,
930 request_id,
931 error,
932 ..
933 } => {
934 let error_string = error.to_string();
935 let started = if let Some((started, pending_response)) = self
936 .pending_requests
937 .remove(&(protocol.clone(), request_id).into())
938 {
939 if pending_response
940 .send(Err(RequestFailure::Network(error)))
941 .is_err()
942 {
943 debug!(
944 target: LOG_TARGET,
945 %request_id,
946 "Request failed. At the same time local node is no longer interested in \
947 the result",
948 );
949 }
950 started
951 } else {
952 warn!(
953 target: LOG_TARGET,
954 %request_id,
955 "Received `RequestResponseEvent::Message` with unexpected request",
956 );
957 debug_assert!(false);
958 continue;
959 };
960
961 let out = Event::RequestFinished {
962 peer: Some(peer),
963 protocol: protocol.clone(),
964 duration: started.elapsed(),
965 result: Err(error_string),
966 };
967
968 return Poll::Ready(ToSwarm::GenerateEvent(out));
969 }
970
971 RequestResponseEvent::InboundFailure { peer, error, .. } => {
974 debug!(?error, %peer, "Inbound request failed.");
975
976 let out = Event::InboundRequest {
977 peer,
978 protocol: protocol.clone(),
979 result: Err(ResponseFailure::Network(error)),
980 };
981 return Poll::Ready(ToSwarm::GenerateEvent(out));
982 }
983
984 RequestResponseEvent::ResponseSent { peer, .. } => {
986 let out = Event::InboundRequest {
987 peer,
988 protocol: protocol.clone(),
989 result: Ok(()),
990 };
991
992 return Poll::Ready(ToSwarm::GenerateEvent(out));
993 }
994 };
995 }
996 }
997
998 break Poll::Pending;
999 }
1000 }
1001}
1002
1003#[derive(Debug, thiserror::Error)]
1005pub enum RegisterError {
1006 #[error("{0}")]
1008 DuplicateProtocol(Cow<'static, str>),
1009}
1010
1011#[derive(Debug, thiserror::Error)]
1013pub enum RequestFailure {
1014 #[error("We are not currently connected to the requested peer")]
1016 NotConnected,
1017 #[error("Given protocol hasn't been registered")]
1019 UnknownProtocol,
1020 #[error(
1023 "Remote has closed the substream before answering, thereby signaling that it considers the \
1024 request as valid, but refused to answer it"
1025 )]
1026 Refused,
1027 #[error("The remote replied, but the local node is no longer interested in the response")]
1029 Obsolete,
1030 #[error("Problem on the network: {0}")]
1032 Network(OutboundFailure),
1033}
1034
1035#[derive(Debug, thiserror::Error)]
1037pub enum ResponseFailure {
1038 #[error("Problem on the network: {0}")]
1040 Network(InboundFailure),
1041}
1042
1043#[derive(Debug, Clone)]
1046#[doc(hidden)] pub struct GenericCodec {
1048 max_request_size: u64,
1049 max_response_size: u64,
1050}
1051
1052impl RequestResponseCodec for GenericCodec {
1053 type Protocol = StreamProtocol;
1054 type Request = Vec<u8>;
1055 type Response = Result<ResponsePayload, ()>;
1056
1057 async fn read_request<T>(&mut self, _: &Self::Protocol, io: &mut T) -> io::Result<Self::Request>
1058 where
1059 T: AsyncRead + Unpin + Send,
1060 {
1061 let length = unsigned_varint::aio::read_usize(&mut *io)
1063 .await
1064 .map_err(|err| io::Error::new(io::ErrorKind::InvalidInput, err))?;
1065 if length > usize::try_from(self.max_request_size).unwrap_or(usize::MAX) {
1066 return Err(io::Error::new(
1067 io::ErrorKind::InvalidInput,
1068 format!(
1069 "Request size exceeds limit: {} > {}",
1070 length, self.max_request_size
1071 ),
1072 ));
1073 }
1074
1075 let mut buffer = vec![0; length];
1077 io.read_exact(&mut buffer).await?;
1078 Ok(buffer)
1079 }
1080
1081 async fn read_response<T>(
1082 &mut self,
1083 _: &Self::Protocol,
1084 io: &mut T,
1085 ) -> io::Result<Self::Response>
1086 where
1087 T: AsyncRead + Unpin + Send,
1088 {
1089 let length = match unsigned_varint::aio::read_usize(&mut *io).await {
1096 Ok(l) => l,
1097 Err(unsigned_varint::io::ReadError::Io(err))
1098 if matches!(err.kind(), io::ErrorKind::UnexpectedEof) =>
1099 {
1100 return Ok(Err(()));
1101 }
1102 Err(err) => return Err(io::Error::new(io::ErrorKind::InvalidInput, err)),
1103 };
1104
1105 if length > usize::try_from(self.max_response_size).unwrap_or(usize::MAX) {
1106 return Err(io::Error::new(
1107 io::ErrorKind::InvalidInput,
1108 format!(
1109 "Response size exceeds limit: {} > {}",
1110 length, self.max_response_size
1111 ),
1112 ));
1113 }
1114
1115 #[cfg_attr(
1117 target_pointer_width = "64",
1118 expect(
1119 clippy::absurd_extreme_comparisons,
1120 reason = "`MAX_CAPACITY` is `u32::MAX` where `usize` is 64-bit"
1121 )
1122 )]
1123 let length = u32::try_from(length)
1124 .ok()
1125 .filter(|&length| length <= OwnedAlignedBuffer::<Align1>::MAX_CAPACITY)
1126 .ok_or_else(|| {
1127 io::Error::new(
1128 io::ErrorKind::InvalidInput,
1129 format!("Response size {length} is too large for a buffer"),
1130 )
1131 })?;
1132 let mut buffer = OwnedAlignedBuffer::<Align1>::zeroed(length);
1133 io.read_exact(buffer.as_mut_slice()).await?;
1134 Ok(Ok(ResponsePayload::from(buffer.into_shared())))
1135 }
1136
1137 async fn write_request<T>(
1138 &mut self,
1139 _: &Self::Protocol,
1140 io: &mut T,
1141 req: Self::Request,
1142 ) -> io::Result<()>
1143 where
1144 T: AsyncWrite + Unpin + Send,
1145 {
1146 {
1148 let mut buffer = unsigned_varint::encode::usize_buffer();
1149 io.write_all(unsigned_varint::encode::usize(req.len(), &mut buffer))
1150 .await?;
1151 }
1152
1153 io.write_all(&req).await?;
1155
1156 io.close().await?;
1157 Ok(())
1158 }
1159
1160 async fn write_response<T>(
1161 &mut self,
1162 _: &Self::Protocol,
1163 io: &mut T,
1164 res: Self::Response,
1165 ) -> io::Result<()>
1166 where
1167 T: AsyncWrite + Unpin + Send,
1168 {
1169 if let Ok(res) = res {
1171 {
1173 let mut buffer = unsigned_varint::encode::usize_buffer();
1174 io.write_all(unsigned_varint::encode::usize(res.len(), &mut buffer))
1175 .await?;
1176 }
1177
1178 for buffer in res.buffers() {
1180 io.write_all(buffer).await?;
1181 }
1182 }
1183
1184 io.close().await?;
1185 Ok(())
1186 }
1187}