Skip to main content

volans_stream/client/
handler.rs

1use std::{
2    convert::Infallible,
3    io,
4    task::{Context, Poll},
5};
6
7use futures::{
8    StreamExt,
9    channel::{mpsc, oneshot},
10};
11use volans_swarm::{
12    ConnectionHandler, ConnectionHandlerEvent, OutboundStreamHandler, OutboundUpgradeSend,
13    StreamProtocol, StreamUpgradeError, Substream, SubstreamProtocol,
14};
15
16use crate::{Upgrade, client::StreamError};
17
18#[derive(Debug)]
19pub(crate) struct NewStream {
20    pub(crate) protocol: StreamProtocol,
21    pub(crate) sender: oneshot::Sender<Result<Substream, StreamError>>,
22}
23
24pub struct Handler {
25    receiver: mpsc::Receiver<NewStream>,
26    /// 接收的新的出站流请求
27    pending_outbound: Option<(
28        StreamProtocol,
29        oneshot::Sender<Result<Substream, StreamError>>,
30    )>,
31}
32
33impl Handler {
34    pub(crate) fn new(receiver: mpsc::Receiver<NewStream>) -> Self {
35        Self {
36            receiver,
37            pending_outbound: None,
38        }
39    }
40}
41
42impl ConnectionHandler for Handler {
43    type Action = Infallible;
44    type Event = Infallible;
45
46    fn handle_action(&mut self, action: Self::Action) {
47        unreachable!("Handler does not support actions, got: {:?}", action);
48    }
49
50    fn poll(&mut self, _cx: &mut Context<'_>) -> Poll<ConnectionHandlerEvent<Self::Event>> {
51        Poll::Pending
52    }
53}
54
55impl OutboundStreamHandler for Handler {
56    type OutboundUpgrade = Upgrade;
57    type OutboundUserData = ();
58
59    fn on_fully_negotiated(
60        &mut self,
61        _user_data: Self::OutboundUserData,
62        (stream, protocol): <Self::OutboundUpgrade as OutboundUpgradeSend>::Output,
63    ) {
64        let Some((expected_protocol, sender)) = self.pending_outbound.take() else {
65            tracing::warn!(
66                "Failed to establish outbound stream for protocol {:?}",
67                protocol
68            );
69            return;
70        };
71        debug_assert!(protocol == expected_protocol);
72        let _ = sender.send(Ok(stream));
73    }
74
75    fn on_upgrade_error(
76        &mut self,
77        _user_data: Self::OutboundUserData,
78        error: StreamUpgradeError<<Self::OutboundUpgrade as OutboundUpgradeSend>::Error>,
79    ) {
80        let Some((protocol, sender)) = self.pending_outbound.take() else {
81            tracing::warn!(
82                "Failed to establish outbound stream for protocol {:?}",
83                error
84            );
85            return;
86        };
87
88        let error = match error {
89            StreamUpgradeError::Timeout => {
90                StreamError::Io(io::Error::from(io::ErrorKind::TimedOut))
91            }
92            StreamUpgradeError::Apply(v) => unreachable!("Unexpected apply error: {:?}", v),
93            StreamUpgradeError::NegotiationFailed => StreamError::Unsupported(protocol),
94            StreamUpgradeError::Io(io) => StreamError::Io(io),
95        };
96
97        // 尝试发送错误到发送者
98        let _ = sender.send(Err(error));
99    }
100
101    fn poll_outbound_request(
102        &mut self,
103        cx: &mut Context<'_>,
104    ) -> Poll<SubstreamProtocol<Self::OutboundUpgrade, Self::OutboundUserData>> {
105        if self.pending_outbound.is_some() {
106            return Poll::Pending;
107        }
108        match self.receiver.poll_next_unpin(cx) {
109            Poll::Ready(Some(NewStream {
110                protocol, sender, ..
111            })) => {
112                self.pending_outbound = Some((protocol.clone(), sender));
113                return Poll::Ready(SubstreamProtocol::new(
114                    Upgrade {
115                        supported_protocols: vec![protocol],
116                    },
117                    (),
118                ));
119            }
120            Poll::Ready(None) => {}
121            Poll::Pending => {}
122        }
123        Poll::Pending
124    }
125}