Skip to main content

ab_networking/protocols/request_response/
request_response_factory.rs

1// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.
2// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
3
4// This program is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// This program is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with this program. If not, see <https://www.gnu.org/licenses/>.
16
17//! Collection of request-response protocols.
18//!
19//! The [`RequestResponse`] struct defined in this module provides support for zero or more
20//! so-called "request-response" protocols.
21//!
22//! A request-response protocol works in the following way:
23//!
24//! - For every emitted request, a new substream is open and the protocol is negotiated. If the
25//!   remote supports the protocol, the size of the request is sent as a LEB128 number, followed
26//!   with the request itself. The remote then sends the size of the response as a LEB128 number,
27//!   followed with the response.
28//!
29//! - Requests have a certain time limit before they time out. This time includes the time it takes
30//!   to send/receive the request and response.
31//!
32//! - If provided, a [requests processing](ProtocolConfig::inbound_queue) channel is used to handle
33//!   incoming requests.
34//!
35//! Original file commit: <https://github.com/paritytech/substrate/commit/c2fc4b3ca0d7a15cc3f9cb1e5f441d99ec8d6e0b>
36
37#[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/// Defines a handler for the request-response protocol factory.
73#[async_trait]
74pub trait RequestHandler: Send {
75    /// Runs the underlying protocol handler.
76    async fn run(&mut self);
77
78    /// Returns a config for the request-response protocol factory.
79    fn protocol_config(&self) -> ProtocolConfig;
80
81    /// Returns a protocol name.
82    fn protocol_name(&self) -> &'static str;
83
84    /// Clone boxed value.
85    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/// Configuration for a single request-response protocol.
95#[derive(Debug, Clone)]
96pub struct ProtocolConfig {
97    /// Name of the protocol on the wire. Should be something like `/foo/bar`.
98    pub name: &'static str,
99
100    /// Maximum allowed size, in bytes, of a request.
101    ///
102    /// Any request larger than this value will be declined as a way to avoid allocating too
103    /// much memory for it.
104    pub max_request_size: u64,
105
106    /// Maximum allowed size, in bytes, of a response.
107    ///
108    /// Any response larger than this value will be declined as a way to avoid allocating too
109    /// much memory for it.
110    pub max_response_size: u64,
111
112    /// Duration after which emitted requests are considered timed out.
113    ///
114    /// If you expect the response to come back quickly, you should set this to a smaller duration.
115    pub request_timeout: Duration,
116
117    /// Channel on which the networking service will send incoming requests.
118    ///
119    /// Every time a peer sends a request to the local node using this protocol, the networking
120    /// service will push an element on this channel. The receiving side of this channel then has
121    /// to pull this element, process the request, and send back the response to send back to the
122    /// peer.
123    ///
124    /// The size of the channel has to be carefully chosen. If the channel is full, the networking
125    /// service will discard the incoming request send back an error to the peer. Consequently,
126    /// the channel being full is an indicator that the node is overloaded.
127    ///
128    /// You can typically set the size of the channel to `T / d`, where `T` is the
129    /// `request_timeout` and `d` is the expected average duration of CPU and I/O it takes to
130    /// build a response.
131    ///
132    /// Can be `None` if the local node does not support answering incoming requests.
133    /// If this is `None`, then the local node will not advertise support for this protocol towards
134    /// other peers. If this is `Some` but the channel is closed, then the local node will
135    /// advertise support for this protocol, but any incoming request will lead to an error being
136    /// sent back.
137    pub inbound_queue: Option<mpsc::Sender<IncomingRequest>>,
138}
139
140impl ProtocolConfig {
141    /// Creates request-response protocol config.
142    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/// A single request received by a peer on a request-response protocol.
154#[derive(Debug)]
155pub struct IncomingRequest {
156    /// Who sent the request.
157    pub peer: PeerId,
158
159    /// Request sent by the remote. Will always be smaller than
160    /// [`ProtocolConfig::max_request_size`].
161    pub payload: Vec<u8>,
162
163    /// Channel to send back the response.
164    ///
165    /// There are two ways to indicate that handling the request failed:
166    ///
167    /// 1. Drop `pending_response` and thus not changing the reputation of the peer.
168    ///
169    /// 2. Sending an `Err(())` via `pending_response`, optionally including reputation changes for
170    ///    the given peer.
171    pub pending_response: oneshot::Sender<OutgoingResponse>,
172}
173
174/// Payload of a response that consists of buffers, which are sent one after another.
175///
176/// This allows sending large buffers as a part of the response without copying them into a single
177/// buffer first.
178#[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    /// Append a buffer to the payload
197    #[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    /// Total length of the payload in bytes
208    #[inline]
209    pub fn len(&self) -> usize {
210        self.buffers
211            .iter()
212            .map(|buffer| buffer.len() as usize)
213            .sum()
214    }
215
216    /// Whether the payload is empty
217    #[inline]
218    pub fn is_empty(&self) -> bool {
219        self.buffers.is_empty()
220    }
221
222    /// Buffers of the payload in order
223    #[inline]
224    pub fn buffers(&self) -> &[SharedAlignedBuffer<Align1>] {
225        &self.buffers
226    }
227
228    /// Convert into a single buffer, which copies the contents of the payload unless it consists
229    /// of a single buffer.
230    ///
231    /// # Panics
232    /// If the payload is larger than [`OwnedAlignedBuffer::MAX_CAPACITY`] or allocation fails
233    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/// Response for an incoming request to be send by a request protocol handler.
250#[derive(Debug)]
251pub struct OutgoingResponse {
252    /// The payload of the response.
253    ///
254    /// `Err(())` if none is available e.g. due an error while handling the request.
255    pub result: Result<ResponsePayload, ()>,
256
257    /// If provided, the `oneshot::Sender` will be notified when the request has been sent to the
258    /// peer.
259    ///
260    /// Note: Operating systems typically maintain a buffer of a few dozen kilobytes of
261    /// outgoing data for each TCP socket, and it is not possible for a user
262    /// application to inspect this buffer. This channel here is not actually notified
263    /// when the response has been fully sent out, but rather when it has fully been
264    /// written to the buffer managed by the operating system.
265    pub sent_feedback: Option<oneshot::Sender<()>>,
266}
267
268/// Event generated by the [`RequestResponseFactoryBehaviour`].
269#[derive(Debug)]
270// We are not reading these events in a meaningful way right now, but the fields in there are still
271// potentially useful
272pub enum Event {
273    /// A remote sent a request and either we have successfully answered it or an error happened.
274    ///
275    /// This event is generated for statistics purposes.
276    InboundRequest {
277        /// Peer which has emitted the request.
278        peer: PeerId,
279        /// Name of the protocol in question.
280        protocol: Cow<'static, str>,
281        /// Whether handling the request was successful or unsuccessful.
282        ///
283        /// When successful contains the time elapsed between when we received the request and when
284        /// we sent back the response. When unsuccessful contains the failure reason.
285        result: Result<(), ResponseFailure>,
286    },
287
288    /// A request initiated using [`RequestResponseFactoryBehaviour::send_request`] has succeeded or
289    /// failed.
290    ///
291    /// This event is generated for statistics purposes.
292    RequestFinished {
293        /// Peer that we sent the request to, if one was chosen.
294        peer: Option<PeerId>,
295        /// Name of the protocol in question.
296        protocol: Cow<'static, str>,
297        /// Duration the request took.
298        duration: Duration,
299        /// Result of the request.
300        result: Result<(), String>,
301    },
302}
303
304/// Combination of a protocol name and a request id.
305///
306/// Uniquely identifies an inbound or outbound request among all handled protocols. Note however
307/// that uniqueness is only guaranteed between two inbound and likewise between two outbound
308/// requests. There is no uniqueness guarantee in a set of both inbound and outbound
309/// [`ProtocolRequestId`]s.
310#[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/// When sending a request, what to do on a disconnected recipient
327#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
328pub enum IfDisconnected {
329    /// Try to connect to the peer
330    TryConnect,
331    /// Just fail if the destination is not yet connected
332    ImmediateError,
333}
334
335/// Convenience functions for `IfDisconnected`.
336impl IfDisconnected {
337    /// Shall we connect to a disconnected peer?
338    pub fn should_connect(self) -> bool {
339        match self {
340            Self::TryConnect => true,
341            Self::ImmediateError => false,
342        }
343    }
344}
345
346/// Implementation of `NetworkBehaviour` that provides support for multiple request-response
347/// protocols.
348#[expect(
349    clippy::type_complexity,
350    reason = "To preserve compatibility with copied implementation"
351)]
352pub struct RequestResponseFactoryBehaviour {
353    /// The multiple sub-protocols, by name.
354    /// Contains the underlying libp2p `RequestResponse` behaviour, plus an optional
355    /// "response builder" used to build responses for incoming requests.
356    protocols: HashMap<
357        Cow<'static, str>,
358        (
359            RequestResponse<GenericCodec>,
360            Option<mpsc::Sender<IncomingRequest>>,
361        ),
362    >,
363
364    /// Pending requests, passed down to a [`RequestResponse`] behaviour, awaiting a reply.
365    pending_requests: HashMap<
366        ProtocolRequestId,
367        (
368            Instant,
369            oneshot::Sender<Result<SharedAlignedBuffer<Align1>, RequestFailure>>,
370        ),
371    >,
372
373    /// Whenever an incoming request arrives, a `Future` is added to this list and will yield the
374    /// start time and the response to send back to the remote.
375    pending_responses: stream::FuturesUnordered<
376        Pin<Box<dyn Future<Output = Option<RequestProcessingOutcome>> + Send>>,
377    >,
378
379    /// Pending message request, holds `MessageRequest` as a Future state to poll it
380    /// until we get a response from `Peerset`
381    message_request: Option<MessageRequest>,
382
383    /// Request handlers future collection.
384    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
395// This is a state of processing incoming request Message.
396struct 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
405/// Generated by the response builder and waiting to be processed.
406struct RequestProcessingOutcome {
407    request_id: InboundRequestId,
408    protocol: Cow<'static, str>,
409    inner_channel: ResponseChannel<Result<ResponsePayload, ()>>,
410    response: OutgoingResponse,
411}
412
413impl RequestResponseFactoryBehaviour {
414    /// Creates a new behaviour. Must be passed a list of supported protocols. Returns an error if
415    /// the same protocol is passed twice.
416    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    /// Initiates sending a request.
465    ///
466    /// If there is no established connection to the target peer, the behavior is determined by the
467    /// choice of `connect`.
468    ///
469    /// An error is returned if the protocol doesn't match one that has been registered.
470    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    /// Informs the behaviour about an event from the [`Swarm`](libp2p::Swarm).
586    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                // Submit the request to the "response builder" passed by the user at
718                // initialization.
719                if let Some(mut response_builder) = response_builder {
720                    // If the response builder is too busy, silently drop `tx`. This
721                    // will be reported by the corresponding `RequestResponse` through
722                    // an `InboundFailure::Omission` event.
723                    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                    // The `tx` created above can be dropped if we are not capable of
734                    // processing this request, which is reflected as a
735                    // `InboundFailure::Omission` event.
736                    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                // This `continue` makes sure that `pending_responses` gets polled
749                // after we have added the new element.
750                continue 'poll_all;
751            }
752            // Poll to see if any response is ready to be sent back.
753            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                    // The response builder was too busy, or handling the request failed. This is
766                    // later on reported as `InboundFailure::Omission`.
767                    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                    // Note: Failure is handled further below when receiving
775                    // `InboundFailure` event from `RequestResponse` behaviour.
776                    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                // Future.Output == (), so we don't need a result here
789                let _: Poll<()> = rq_rs_runner.poll_unpin(cx);
790            }
791
792            // Poll request-responses protocols.
793            for (protocol, (behaviour, response_builder)) in &mut self.protocols {
794                while let Poll::Ready(event) = behaviour.poll(cx) {
795                    let event = match event {
796                        // Main events we are interested in.
797                        ToSwarm::GenerateEvent(event) => event,
798
799                        // Other events generated by the underlying behaviour are transparently
800                        // passed through.
801                        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                        // Received a request from a remote.
861                        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                            // This `continue` makes sure that `message_request` gets polled
881                            // after we have added the new element.
882                            continue 'poll_all;
883                        }
884
885                        // Received a response from a remote to one of our requests.
886                        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                        // One of our requests has failed.
928                        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                        // An inbound request failed, either while reading the request or due to
972                        // failing to send a response.
973                        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                        // A response to an inbound request has been sent.
985                        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/// Error when registering a protocol.
1004#[derive(Debug, thiserror::Error)]
1005pub enum RegisterError {
1006    /// A protocol has been specified multiple times.
1007    #[error("{0}")]
1008    DuplicateProtocol(Cow<'static, str>),
1009}
1010
1011/// Error in a request
1012#[derive(Debug, thiserror::Error)]
1013pub enum RequestFailure {
1014    /// We are not currently connected to the requested peer
1015    #[error("We are not currently connected to the requested peer")]
1016    NotConnected,
1017    /// Given protocol hasn't been registered
1018    #[error("Given protocol hasn't been registered")]
1019    UnknownProtocol,
1020    /// Remote has closed the substream before answering, thereby signaling that it considers the
1021    /// request as valid, but refused to answer it
1022    #[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    /// The remote replied, but the local node is no longer interested in the response
1028    #[error("The remote replied, but the local node is no longer interested in the response")]
1029    Obsolete,
1030    /// Problem on the network
1031    #[error("Problem on the network: {0}")]
1032    Network(OutboundFailure),
1033}
1034
1035/// Error when processing a request sent by a remote.
1036#[derive(Debug, thiserror::Error)]
1037pub enum ResponseFailure {
1038    /// Problem on the network.
1039    #[error("Problem on the network: {0}")]
1040    Network(InboundFailure),
1041}
1042
1043/// Implements the libp2p [`RequestResponseCodec`] trait. Defines how streams of bytes are turned
1044/// into requests and responses and vice-versa.
1045#[derive(Debug, Clone)]
1046#[doc(hidden)] // Needs to be public in order to satisfy the Rust compiler.
1047pub 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        // Read the length.
1062        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        // Read the payload.
1076        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        // Note that this function returns a `Result<Result<...>>`. Returning an `Err` is
1090        // considered as a protocol error and will result in the entire connection being closed.
1091        // Returning `Ok(Err(_))` signifies that a response has successfully been fetched, and
1092        // that this response is an error.
1093
1094        // Read the length.
1095        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        // Read the payload.
1116        #[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        // Write the length.
1147        {
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        // Write the payload.
1154        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 `res` is an `Err`, we jump to closing the substream without writing anything on it.
1170        if let Ok(res) = res {
1171            // Write the length.
1172            {
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            // Write the payload, one buffer at a time
1179            for buffer in res.buffers() {
1180                io.write_all(buffer).await?;
1181            }
1182        }
1183
1184        io.close().await?;
1185        Ok(())
1186    }
1187}