cuprate_p2p_core/client/
weak.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
use std::task::{ready, Context, Poll};

use futures::channel::oneshot;
use tokio::sync::{mpsc, OwnedSemaphorePermit};
use tokio_util::sync::PollSemaphore;
use tower::Service;

use cuprate_helper::asynch::InfallibleOneshotReceiver;

use crate::{
    client::{connection, PeerInformation},
    NetworkZone, PeerError, PeerRequest, PeerResponse, SharedError,
};

/// A weak handle to a [`Client`](super::Client).
///
/// When this is dropped the peer will not be disconnected.
pub struct WeakClient<N: NetworkZone> {
    /// Information on the connected peer.
    pub info: PeerInformation<N::Addr>,

    /// The channel to the [`Connection`](connection::Connection) task.
    pub(super) connection_tx: mpsc::WeakSender<connection::ConnectionTaskRequest>,

    /// The semaphore that limits the requests sent to the peer.
    pub(super) semaphore: PollSemaphore,
    /// A permit for the semaphore, will be [`Some`] after `poll_ready` returns ready.
    pub(super) permit: Option<OwnedSemaphorePermit>,

    /// The error slot shared between the [`Client`] and [`Connection`](connection::Connection).
    pub(super) error: SharedError<PeerError>,
}

impl<N: NetworkZone> WeakClient<N> {
    /// Internal function to set an error on the [`SharedError`].
    fn set_err(&self, err: PeerError) -> tower::BoxError {
        let err_str = err.to_string();
        match self.error.try_insert_err(err) {
            Ok(()) => err_str,
            Err(e) => e.to_string(),
        }
        .into()
    }
}

impl<Z: NetworkZone> Service<PeerRequest> for WeakClient<Z> {
    type Response = PeerResponse;
    type Error = tower::BoxError;
    type Future = InfallibleOneshotReceiver<Result<Self::Response, Self::Error>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        if let Some(err) = self.error.try_get_err() {
            return Poll::Ready(Err(err.to_string().into()));
        }

        if self.connection_tx.strong_count() == 0 {
            let err = self.set_err(PeerError::ClientChannelClosed);
            return Poll::Ready(Err(err));
        }

        if self.permit.is_some() {
            return Poll::Ready(Ok(()));
        }

        let permit = ready!(self.semaphore.poll_acquire(cx))
            .expect("Client semaphore should not be closed!");

        self.permit = Some(permit);

        Poll::Ready(Ok(()))
    }

    #[expect(clippy::significant_drop_tightening)]
    fn call(&mut self, request: PeerRequest) -> Self::Future {
        let permit = self
            .permit
            .take()
            .expect("poll_ready did not return ready before call to call");

        let (tx, rx) = oneshot::channel();
        let req = connection::ConnectionTaskRequest {
            response_channel: tx,
            request,
            permit: Some(permit),
        };

        match self.connection_tx.upgrade() {
            None => {
                self.set_err(PeerError::ClientChannelClosed);

                let resp = Err(PeerError::ClientChannelClosed.into());
                drop(req.response_channel.send(resp));
            }
            Some(sender) => {
                if let Err(e) = sender.try_send(req) {
                    // The connection task could have closed between a call to `poll_ready` and the call to
                    // `call`, which means if we don't handle the error here the receiver would panic.
                    use mpsc::error::TrySendError;

                    match e {
                        TrySendError::Closed(req) | TrySendError::Full(req) => {
                            self.set_err(PeerError::ClientChannelClosed);

                            let resp = Err(PeerError::ClientChannelClosed.into());
                            drop(req.response_channel.send(resp));
                        }
                    }
                }
            }
        }

        rx.into()
    }
}