Skip to main content

volans_stream/client/
behavior.rs

1use std::{
2    convert::Infallible,
3    io,
4    sync::Arc,
5    task::{Context, Poll},
6};
7
8use futures::{
9    SinkExt, StreamExt,
10    channel::{mpsc, oneshot},
11};
12use parking_lot::Mutex;
13use volans_core::{Multiaddr, PeerId};
14use volans_swarm::{
15    BehaviorEvent, ConnectionDenied, ConnectionId, DialOpts, NetworkBehavior,
16    NetworkOutgoingBehavior, PeerCondition, StreamProtocol, Substream, THandlerAction,
17    THandlerEvent,
18    error::{ConnectionError, DialError},
19};
20
21use crate::client::{StreamError, handler, shared::Shared};
22
23pub struct Behavior {
24    shared: Arc<Mutex<Shared>>,
25    dial_receiver: mpsc::Receiver<PeerId>,
26}
27
28impl Behavior {
29    pub fn new() -> Self {
30        let (dial_sender, dial_receiver) = mpsc::channel(0);
31        let shared = Arc::new(Mutex::new(Shared::new(dial_sender)));
32        Self {
33            shared,
34            dial_receiver,
35        }
36    }
37
38    pub fn controller(&self) -> Controller {
39        Controller::new(self.shared.clone())
40    }
41}
42
43impl NetworkBehavior for Behavior {
44    type ConnectionHandler = handler::Handler;
45    type Event = Infallible;
46
47    fn on_connection_handler_event(
48        &mut self,
49        _id: ConnectionId,
50        _peer_id: PeerId,
51        _event: THandlerEvent<Self>,
52    ) {
53        unreachable!()
54    }
55
56    fn poll(
57        &mut self,
58        _cx: &mut Context<'_>,
59    ) -> Poll<BehaviorEvent<Self::Event, THandlerAction<Self>>> {
60        Poll::Pending
61    }
62}
63
64impl NetworkOutgoingBehavior for Behavior {
65    fn handle_established_connection(
66        &mut self,
67        id: ConnectionId,
68        peer_id: PeerId,
69        _addr: &Multiaddr,
70    ) -> Result<Self::ConnectionHandler, ConnectionDenied> {
71        Ok(handler::Handler::new(
72            Shared::lock(&self.shared).receiver(peer_id, id),
73        ))
74    }
75
76    fn on_connection_established(&mut self, id: ConnectionId, peer_id: PeerId, _addr: &Multiaddr) {
77        Shared::lock(&self.shared).on_connection_established(peer_id, id);
78    }
79
80    fn on_connection_closed(
81        &mut self,
82        id: ConnectionId,
83        peer_id: PeerId,
84        _addr: &Multiaddr,
85        _reason: Option<&ConnectionError>,
86    ) {
87        Shared::lock(&self.shared).on_connection_closed(peer_id, id);
88    }
89
90    fn on_dial_failure(
91        &mut self,
92        _id: ConnectionId,
93        peer_id: Option<PeerId>,
94        _addr: Option<&Multiaddr>,
95        error: &DialError,
96    ) {
97        if let Some(peer_id) = peer_id {
98            Shared::lock(&self.shared).on_dial_failure(peer_id, error);
99        }
100    }
101
102    fn poll_dial(&mut self, cx: &mut Context<'_>) -> Poll<DialOpts> {
103        if let Poll::Ready(Some(peer)) = self.dial_receiver.poll_next_unpin(cx) {
104            return Poll::Ready(
105                DialOpts::new(None, Some(peer))
106                    .with_condition(PeerCondition::DisconnectedAndNotDialing),
107            );
108        }
109        Poll::Pending
110    }
111}
112
113#[derive(Clone)]
114pub struct Controller {
115    shared: Arc<Mutex<Shared>>,
116}
117
118impl Controller {
119    fn new(shared: Arc<Mutex<Shared>>) -> Self {
120        Self { shared }
121    }
122
123    pub async fn open(
124        &mut self,
125        peer_id: PeerId,
126        protocol: StreamProtocol,
127    ) -> Result<Substream, StreamError> {
128        let mut new_stream_sender = Shared::lock(&self.shared).sender(peer_id);
129        let (sender, receiver) = oneshot::channel();
130        new_stream_sender
131            .send(handler::NewStream { protocol, sender })
132            .await
133            .map_err(|e| StreamError::Io(io::Error::new(io::ErrorKind::ConnectionReset, e)))?;
134
135        let result = receiver
136            .await
137            .map_err(|e| StreamError::Io(io::Error::new(io::ErrorKind::ConnectionReset, e)))?;
138
139        result
140    }
141}