Skip to main content

zebra_network/peer/
client.rs

1//! Handles outbound requests from our node to the network.
2
3use std::{
4    future::Future,
5    pin::Pin,
6    sync::Arc,
7    task::{Context, Poll},
8};
9
10use futures::{
11    channel::{mpsc, oneshot},
12    future, ready,
13    stream::{Stream, StreamExt},
14    FutureExt,
15};
16use tokio::task::JoinHandle;
17use tower::Service;
18
19use zebra_chain::diagnostic::task::CheckForPanics;
20
21use crate::{
22    peer::{
23        error::{AlreadyErrored, ErrorSlot, PeerError, SharedPeerError},
24        ConnectionInfo,
25    },
26    protocol::internal::{Request, Response},
27    BoxError,
28};
29
30#[cfg(any(test, feature = "proptest-impl"))]
31pub mod tests;
32
33/// The "client" duplex half of a peer connection.
34pub struct Client {
35    /// The metadata for the connected peer `service`.
36    pub connection_info: Arc<ConnectionInfo>,
37
38    /// Used to shut down the corresponding heartbeat.
39    /// This is always Some except when we take it on drop.
40    pub(crate) shutdown_tx: Option<oneshot::Sender<CancelHeartbeatTask>>,
41
42    /// Used to send [`Request`]s to the remote peer.
43    pub(crate) server_tx: mpsc::Sender<ClientRequest>,
44
45    /// Sends block adverts without waiting for an outstanding request's response.
46    pub(crate) block_advert_tx: tokio::sync::mpsc::Sender<crate::peer_set::BlockAdvert>,
47
48    /// A slot for an error shared between the Connection and the Client that uses it.
49    ///
50    /// `None` unless the connection or client have errored.
51    pub(crate) error_slot: ErrorSlot,
52
53    /// A handle to the task responsible for connecting to the peer.
54    pub(crate) connection_task: JoinHandle<()>,
55
56    /// A handle to the task responsible for sending periodic heartbeats.
57    pub(crate) heartbeat_task: JoinHandle<Result<(), BoxError>>,
58}
59
60/// A signal sent by the [`Client`] half of a peer connection,
61/// to cancel a [`Client`]'s heartbeat task.
62///
63/// When it receives this signal, the heartbeat task exits.
64#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
65pub struct CancelHeartbeatTask;
66
67/// A message from the `peer::Client` to the `peer::Server`.
68#[derive(Debug)]
69pub(crate) struct ClientRequest {
70    /// The actual network request for the peer.
71    pub request: Request,
72
73    /// The response `Message` channel, included because `peer::Client::call`
74    /// returns a future that may be moved around before it resolves.
75    pub tx: oneshot::Sender<Result<Response, SharedPeerError>>,
76
77    /// The tracing context for the request, so that work the connection task does
78    /// processing messages in the context of this request will have correct context.
79    pub span: tracing::Span,
80}
81
82/// A receiver for the `peer::Server`, which wraps a `mpsc::Receiver`,
83/// converting `ClientRequest`s into `InProgressClientRequest`s.
84#[derive(Debug)]
85pub(super) struct ClientRequestReceiver {
86    /// The inner receiver
87    inner: mpsc::Receiver<ClientRequest>,
88}
89
90/// A message from the `peer::Client` to the `peer::Server`,
91/// after it has been received by the `peer::Server`.
92#[derive(Debug)]
93#[must_use = "tx.send() must be called before drop"]
94pub(super) struct InProgressClientRequest {
95    /// The actual request.
96    pub request: Request,
97
98    /// The return message channel, included because `peer::Client::call` returns a
99    /// future that may be moved around before it resolves.
100    ///
101    /// INVARIANT: `tx.send()` must be called before dropping `tx`.
102    ///
103    /// JUSTIFICATION: the `peer::Client` translates `Request`s into
104    /// `ClientRequest`s, which it sends to a background task. If the send is
105    /// `Ok(())`, it will assume that it is safe to unconditionally poll the
106    /// `Receiver` tied to the `Sender` used to create the `ClientRequest`.
107    ///
108    /// We enforce this invariant via the type system, by converting
109    /// `ClientRequest`s to `InProgressClientRequest`s when they are received by
110    /// the background task. These conversions are implemented by
111    /// `ClientRequestReceiver`.
112    pub tx: MustUseClientResponseSender,
113
114    /// The tracing context for the request, so that work the connection task does
115    /// processing messages in the context of this request will have correct context.
116    pub span: tracing::Span,
117}
118
119/// A `oneshot::Sender` for client responses, that must be used by calling `send()`.
120///
121/// Panics on drop if `tx` has not been used or canceled.
122/// Panics if `tx.send()` is used more than once.
123#[derive(Debug)]
124#[must_use = "tx.send() must be called before drop"]
125pub(super) struct MustUseClientResponseSender {
126    /// The sender for the oneshot client response channel.
127    ///
128    /// `None` if `tx.send()` has been used.
129    pub tx: Option<oneshot::Sender<Result<Response, SharedPeerError>>>,
130}
131
132impl std::fmt::Debug for Client {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        // skip the channels, they don't tell us anything useful
135        f.debug_struct("Client")
136            .field("connection_info", &self.connection_info)
137            .field("error_slot", &self.error_slot)
138            .field("connection_task", &self.connection_task)
139            .field("heartbeat_task", &self.heartbeat_task)
140            .finish()
141    }
142}
143
144impl From<ClientRequest> for InProgressClientRequest {
145    fn from(client_request: ClientRequest) -> Self {
146        let ClientRequest { request, tx, span } = client_request;
147
148        let tx = MustUseClientResponseSender::new(tx);
149
150        InProgressClientRequest { request, tx, span }
151    }
152}
153
154impl ClientRequestReceiver {
155    /// Forwards to `inner.close()`.
156    pub fn close(&mut self) {
157        self.inner.close()
158    }
159
160    /// Closes `inner`, then gets the next pending [`Request`].
161    ///
162    /// Closing the channel ensures that:
163    /// - the request stream terminates, and
164    /// - task notifications are not required.
165    pub fn close_and_flush_next(&mut self) -> Option<InProgressClientRequest> {
166        self.inner.close();
167
168        // # Correctness
169        //
170        // The request stream terminates, because the sender is closed,
171        // and the channel has a limited capacity.
172        // Task notifications are not required, because the sender is closed.
173        //
174        // Despite what its documentation says, we've seen futures::channel::mpsc::Receiver::try_recv()
175        // return an error after the channel is closed.
176        self.inner.try_recv().ok().map(Into::into)
177    }
178}
179
180impl Stream for ClientRequestReceiver {
181    type Item = InProgressClientRequest;
182
183    /// Converts the successful result of `inner.poll_next()` to an
184    /// `InProgressClientRequest`.
185    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
186        match self.inner.poll_next_unpin(cx) {
187            Poll::Ready(client_request) => Poll::Ready(client_request.map(Into::into)),
188            // CORRECTNESS
189            //
190            // The current task must be scheduled for wakeup every time we
191            // return `Poll::Pending`.
192            //
193            // inner.poll_next_unpin` schedules this task for wakeup when
194            // there are new items available in the inner stream.
195            Poll::Pending => Poll::Pending,
196        }
197    }
198
199    /// Returns `inner.size_hint()`
200    fn size_hint(&self) -> (usize, Option<usize>) {
201        self.inner.size_hint()
202    }
203}
204
205impl From<mpsc::Receiver<ClientRequest>> for ClientRequestReceiver {
206    fn from(rx: mpsc::Receiver<ClientRequest>) -> Self {
207        ClientRequestReceiver { inner: rx }
208    }
209}
210
211impl MustUseClientResponseSender {
212    /// Returns a newly created client response sender for `tx`.
213    pub fn new(tx: oneshot::Sender<Result<Response, SharedPeerError>>) -> Self {
214        Self { tx: Some(tx) }
215    }
216
217    /// Forwards `response` to `tx.send()` and marks this sender as used.
218    ///
219    /// Panics if `tx.send()` is used more than once.
220    pub fn send(
221        mut self,
222        response: Result<Response, SharedPeerError>,
223    ) -> Result<(), Result<Response, SharedPeerError>> {
224        // Forward the response to the internal requester.
225        self.tx
226            .take()
227            .unwrap_or_else(|| {
228                panic!(
229                    "multiple uses of response sender: response must be sent exactly once: {self:?}"
230                )
231            })
232            .send(response)
233    }
234
235    /// Returns `tx.cancellation()`.
236    ///
237    /// Panics if `tx.send()` has previously been used.
238    pub fn cancellation(&mut self) -> oneshot::Cancellation<'_, Result<Response, SharedPeerError>> {
239        self.tx
240            .as_mut()
241            .map(|tx| tx.cancellation())
242            .unwrap_or_else( || {
243                panic!("called cancellation() after using oneshot sender: oneshot must be used exactly once")
244            })
245    }
246
247    /// Returns `tx.is_canceled()`.
248    ///
249    /// Panics if `tx.send()` has previously been used.
250    pub fn is_canceled(&self) -> bool {
251        self.tx
252            .as_ref()
253            .map(|tx| tx.is_canceled())
254            .unwrap_or_else(
255                || panic!("called is_canceled() after using oneshot sender: oneshot must be used exactly once: {self:?}"))
256    }
257}
258
259impl Drop for MustUseClientResponseSender {
260    #[instrument(skip(self))]
261    fn drop(&mut self) {
262        // we don't panic if we are shutting down anyway
263        if !zebra_chain::shutdown::is_shutting_down() {
264            // is_canceled() will not panic, because we check is_none() first
265            assert!(
266                self.tx.is_none() || self.is_canceled(),
267                "unused client response sender: oneshot must be used or canceled: {self:?}"
268            );
269        }
270    }
271}
272
273impl Client {
274    /// Check if this connection's heartbeat task has exited.
275    ///
276    /// Returns an error if the heartbeat task exited. Otherwise, schedules the client task for
277    /// wakeup when the heartbeat task finishes, or the channel closes, and returns `Pending`.
278    ///
279    /// # Panics
280    ///
281    /// If the heartbeat task panicked.
282    #[allow(clippy::unwrap_in_result)]
283    fn poll_heartbeat(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), SharedPeerError>> {
284        let is_canceled = self
285            .shutdown_tx
286            .as_mut()
287            .expect("only taken on drop")
288            .poll_canceled(cx)
289            .is_ready();
290
291        let result = match self.heartbeat_task.poll_unpin(cx) {
292            Poll::Pending => {
293                // The heartbeat task returns `Pending` while it continues to run.
294                // But if it has dropped its receiver, it is shutting down, and we should also shut down.
295                if is_canceled {
296                    self.set_task_exited_error(
297                        "heartbeat",
298                        PeerError::HeartbeatTaskExited("Task was cancelled".to_string()),
299                    )
300                } else {
301                    // Heartbeat task is still running.
302                    return Poll::Pending;
303                }
304            }
305            Poll::Ready(Ok(Ok(_))) => {
306                // Heartbeat task stopped unexpectedly, without panic or error.
307                self.set_task_exited_error(
308                    "heartbeat",
309                    PeerError::HeartbeatTaskExited(
310                        "Heartbeat task stopped unexpectedly".to_string(),
311                    ),
312                )
313            }
314            Poll::Ready(Ok(Err(error))) => {
315                // Heartbeat task stopped unexpectedly, with error.
316                self.set_task_exited_error(
317                    "heartbeat",
318                    PeerError::HeartbeatTaskExited(error.to_string()),
319                )
320            }
321            Poll::Ready(Err(error)) => {
322                // Heartbeat task panicked.
323                let error = error.panic_if_task_has_panicked();
324
325                // Heartbeat task was cancelled.
326                if error.is_cancelled() {
327                    self.set_task_exited_error(
328                        "heartbeat",
329                        PeerError::HeartbeatTaskExited("Task was cancelled".to_string()),
330                    )
331                }
332                // Heartbeat task stopped with another kind of task error.
333                else {
334                    self.set_task_exited_error(
335                        "heartbeat",
336                        PeerError::HeartbeatTaskExited(error.to_string()),
337                    )
338                }
339            }
340        };
341
342        Poll::Ready(result)
343    }
344
345    /// Check if the connection's request/response task has exited.
346    ///
347    /// Returns an error if the connection task exited. Otherwise, schedules the client task for
348    /// wakeup when the connection task finishes, and returns `Pending`.
349    ///
350    /// # Panics
351    ///
352    /// If the connection task panicked.
353    fn poll_connection(&mut self, context: &mut Context<'_>) -> Poll<Result<(), SharedPeerError>> {
354        // Return `Pending` if the connection task is still running.
355        let result = match ready!(self.connection_task.poll_unpin(context)) {
356            Ok(()) => {
357                // Connection task stopped unexpectedly, without panicking.
358                self.set_task_exited_error("connection", PeerError::ConnectionTaskExited)
359            }
360            Err(error) => {
361                // Connection task panicked or was cancelled.
362                let _ = error.panic_if_task_has_panicked();
363
364                // Any unexpected termination of the connection task is reported as ConnectionTaskExited.
365                self.set_task_exited_error("connection", PeerError::ConnectionTaskExited)
366            }
367        };
368
369        Poll::Ready(result)
370    }
371
372    /// Properly update the error slot after a background task has unexpectedly stopped.
373    fn set_task_exited_error(
374        &mut self,
375        task_name: &str,
376        error: PeerError,
377    ) -> Result<(), SharedPeerError> {
378        // Make sure there is an error in the slot
379        let task_error = SharedPeerError::from(error);
380        let original_error = self.error_slot.try_update_error(task_error.clone());
381        debug!(
382            ?original_error,
383            latest_error = ?task_error,
384            "client {} task exited", task_name
385        );
386
387        if let Err(AlreadyErrored { original_error }) = original_error {
388            Err(original_error)
389        } else {
390            Err(task_error)
391        }
392    }
393
394    /// Poll for space in the shared request sender channel.
395    ///
396    /// Returns an error if the sender channel is closed. If there is no space in the channel,
397    /// returns `Pending`, and schedules the task for wakeup when there is space available.
398    fn poll_request(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), SharedPeerError>> {
399        let server_result = ready!(self.server_tx.poll_ready(cx));
400        if server_result.is_err() {
401            Poll::Ready(Err(self
402                .error_slot
403                .try_get_error()
404                .unwrap_or_else(|| PeerError::ConnectionTaskExited.into())))
405        } else if let Some(error) = self.error_slot.try_get_error() {
406            Poll::Ready(Err(error))
407        } else {
408            Poll::Ready(Ok(()))
409        }
410    }
411
412    /// Poll for space in the shared request sender channel, and for errors in the connection tasks.
413    ///
414    /// Returns an error if the sender channel is closed, or the heartbeat or connection tasks have
415    /// terminated. If there is no space in the channel, returns `Pending`, and schedules the task
416    /// for wakeup when there is space available, or one of the tasks terminates.
417    fn poll_client(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), SharedPeerError>> {
418        // # Correctness
419        //
420        // The current task must be scheduled for wakeup every time we return
421        // `Poll::Pending`.
422        //
423        // `poll_heartbeat()` and `poll_connection()` schedule the client task for wakeup
424        // if either task exits, or if the heartbeat task drops the cancel handle.
425        //
426        //`ready!` returns `Poll::Pending` when `server_tx` is unready, and
427        // schedules this task for wakeup.
428        //
429        // It's ok to exit early and skip wakeups when there is an error, because the connection
430        // and its tasks are shut down immediately on error.
431
432        let _heartbeat_pending: Poll<()> = self.poll_heartbeat(cx)?;
433        let _connection_pending: Poll<()> = self.poll_connection(cx)?;
434
435        // We're only pending if the sender channel is full.
436        self.poll_request(cx)
437    }
438
439    /// Shut down the resources held by the client half of this peer connection.
440    ///
441    /// Stops further requests to the remote peer, and stops the heartbeat task.
442    fn shutdown(&mut self) {
443        // Prevent any senders from sending more messages to this peer.
444        self.server_tx.close_channel();
445
446        // Ask the heartbeat task to stop.
447        if let Some(shutdown_tx) = self.shutdown_tx.take() {
448            let _ = shutdown_tx.send(CancelHeartbeatTask);
449        }
450
451        // Force the connection and heartbeat tasks to stop.
452        self.connection_task.abort();
453        self.heartbeat_task.abort();
454    }
455}
456
457impl Service<Request> for Client {
458    type Response = Response;
459    type Error = SharedPeerError;
460    type Future =
461        Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send + 'static>>;
462
463    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
464        // # Correctness
465        //
466        // The current task must be scheduled for wakeup every time we return
467        // `Poll::Pending`.
468        //
469        // `poll_client()` schedules the client task for wakeup if the sender channel has space,
470        // either connection task exits, or if the heartbeat task drops the cancel handle.
471
472        // Check all the tasks and channels.
473        //
474        //`ready!` returns `Poll::Pending` when `server_tx` is unready, and
475        // schedules this task for wakeup.
476        let result = ready!(self.poll_client(cx));
477
478        // Shut down the client and connection if there is an error.
479        if let Err(error) = result {
480            self.shutdown();
481
482            Poll::Ready(Err(error))
483        } else {
484            Poll::Ready(Ok(()))
485        }
486    }
487
488    fn call(&mut self, request: Request) -> Self::Future {
489        let (tx, rx) = oneshot::channel();
490        // get the current Span to propagate it to the peer connection task.
491        // this allows the peer connection to enter the correct tracing context
492        // when it's handling messages in the context of processing this
493        // request.
494        let span = tracing::Span::current();
495
496        match self.server_tx.try_send(ClientRequest { request, tx, span }) {
497            Err(e) => {
498                if e.is_disconnected() {
499                    let peer_error = self
500                        .error_slot
501                        .try_get_error()
502                        .unwrap_or_else(|| PeerError::ConnectionTaskExited.into());
503
504                    let ClientRequest { tx, .. } = e.into_inner();
505                    let _ = tx.send(Err(peer_error.clone()));
506
507                    future::ready(Err(peer_error)).boxed()
508                } else {
509                    // sending fails when there's not enough
510                    // channel space, but we called poll_ready
511                    panic!("called call without poll_ready");
512                }
513            }
514            Ok(()) => {
515                // The receiver end of the oneshot is itself a future.
516                rx.map(|oneshot_recv_result| {
517                    // The ClientRequest oneshot sender should not be dropped before sending a
518                    // response. But sometimes that happens during process or connection shutdown.
519                    // So we just return a generic error here.
520                    match oneshot_recv_result {
521                        Ok(result) => result,
522                        Err(oneshot::Canceled) => Err(PeerError::ConnectionDropped.into()),
523                    }
524                })
525                .boxed()
526            }
527        }
528    }
529}
530
531impl Drop for Client {
532    fn drop(&mut self) {
533        // Make sure there is an error in the slot
534        let drop_error: SharedPeerError = PeerError::ClientDropped.into();
535        let original_error = self.error_slot.try_update_error(drop_error.clone());
536        debug!(
537            ?original_error,
538            latest_error = ?drop_error,
539            "client struct dropped"
540        );
541
542        self.shutdown();
543    }
544}