volans_swarm/
behavior.rs

1mod either;
2
3use std::task::{Context, Poll};
4
5use volans_core::{PeerId, Url};
6
7use crate::{
8    ConnectionDenied, ConnectionHandler, ConnectionId, DialOpts, ListenerId, THandlerAction,
9    THandlerEvent,
10    error::{ConnectionError, DialError, ListenError},
11};
12
13pub trait NetworkBehavior: Send + 'static {
14    type Event: Send + 'static;
15    type ConnectionHandler: ConnectionHandler;
16
17    fn on_connection_handler_event(
18        &mut self,
19        id: ConnectionId,
20        peer_id: PeerId,
21        event: THandlerEvent<Self>,
22    );
23
24    fn poll(
25        &mut self,
26        cx: &mut Context<'_>,
27    ) -> Poll<BehaviorEvent<Self::Event, THandlerAction<Self>>>;
28}
29
30pub trait NetworkIncomingBehavior: NetworkBehavior {
31    /// 处理新的入站连接
32    fn handle_pending_connection(
33        &mut self,
34        _id: ConnectionId,
35        _local_addr: &Url,
36        _remote_addr: &Url,
37    ) -> Result<(), ConnectionDenied> {
38        Ok(())
39    }
40
41    /// 处理已建立的连接
42    fn handle_established_connection(
43        &mut self,
44        _id: ConnectionId,
45        peer_id: PeerId,
46        _local_addr: &Url,
47        _remote_addr: &Url,
48    ) -> Result<Self::ConnectionHandler, ConnectionDenied>;
49
50    /// 连接处理器事件处理
51    fn on_connection_established(
52        &mut self,
53        _id: ConnectionId,
54        _peer_id: PeerId,
55        _local_addr: &Url,
56        _remote_addr: &Url,
57    ) {
58    }
59
60    fn on_connection_closed(
61        &mut self,
62        _id: ConnectionId,
63        _peer_id: PeerId,
64        _local_addr: &Url,
65        _remote_addr: &Url,
66        _reason: Option<&ConnectionError>,
67    ) {
68    }
69
70    /// 监听失败事件处理
71    fn on_listen_failure(
72        &mut self,
73        _id: ConnectionId,
74        _peer_id: Option<PeerId>,
75        _local_addr: &Url,
76        _remote_addr: &Url,
77        _error: &ListenError,
78    ) {
79    }
80
81    /// 监听器事件处理
82    fn on_listener_event(&mut self, _event: ListenerEvent<'_>) {}
83}
84
85pub trait NetworkOutgoingBehavior: NetworkBehavior {
86    fn handle_pending_connection(
87        &mut self,
88        _id: ConnectionId,
89        _maybe_peer: Option<PeerId>,
90        _addr: &Option<Url>,
91    ) -> Result<Option<Url>, ConnectionDenied> {
92        Ok(None)
93    }
94
95    fn handle_established_connection(
96        &mut self,
97        id: ConnectionId,
98        peer_id: PeerId,
99        addr: &Url,
100    ) -> Result<Self::ConnectionHandler, ConnectionDenied>;
101
102    /// 连接处理器事件处理
103    fn on_connection_established(&mut self, _id: ConnectionId, _peer_id: PeerId, _addr: &Url) {}
104
105    fn on_connection_closed(
106        &mut self,
107        _id: ConnectionId,
108        _peer_id: PeerId,
109        _addr: &Url,
110        _reason: Option<&ConnectionError>,
111    ) {
112    }
113
114    /// 失败事件处理
115    fn on_dial_failure(
116        &mut self,
117        _id: ConnectionId,
118        _peer_id: Option<PeerId>,
119        _addr: Option<&Url>,
120        _error: &DialError,
121    ) {
122    }
123
124    fn poll_dial(&mut self, _cx: &mut Context<'_>) -> Poll<DialOpts> {
125        Poll::Pending
126    }
127}
128
129#[derive(Debug, Clone, Copy)]
130#[non_exhaustive]
131pub enum ListenerEvent<'a> {
132    /// 新的监听器事件
133    NewListener(NewListener),
134    /// 新的监听地址事件
135    NewListenAddr(NewListenAddr<'a>),
136    /// 过期的监听地址事件
137    ExpiredListenAddr(ExpiredListenAddr<'a>),
138    /// 监听器错误事件
139    ListenerError(ListenerError<'a>),
140    /// 监听器关闭事件
141    ListenerClosed(ListenerClosed<'a>),
142}
143
144#[derive(Debug, Clone, Copy)]
145pub struct NewListener {
146    pub listener_id: ListenerId,
147}
148
149#[derive(Debug, Clone, Copy)]
150pub struct NewListenAddr<'a> {
151    pub listener_id: ListenerId,
152    pub addr: &'a Url,
153}
154
155#[derive(Debug, Clone, Copy)]
156pub struct ListenerError<'a> {
157    pub listener_id: ListenerId,
158    pub error: &'a (dyn std::error::Error + 'static),
159}
160
161#[derive(Debug, Clone, Copy)]
162pub struct ListenerClosed<'a> {
163    pub listener_id: ListenerId,
164    pub reason: Result<(), &'a std::io::Error>,
165}
166
167#[derive(Debug, Clone, Copy)]
168pub struct ExpiredListenAddr<'a> {
169    pub listener_id: ListenerId,
170    pub addr: &'a Url,
171}
172
173#[derive(Debug)]
174#[non_exhaustive]
175pub enum BehaviorEvent<TEvent, THandlerAction> {
176    /// 行为生成的事件
177    Behavior(TEvent),
178    /// 处理程序命令
179    HandlerAction {
180        peer_id: PeerId,
181        handler: NotifyHandler,
182        action: THandlerAction,
183    },
184    /// 关闭连接事件
185    CloseConnection {
186        peer_id: PeerId,
187        connection: CloseConnection,
188    },
189}
190
191impl<TEvent, THandlerAction> BehaviorEvent<TEvent, THandlerAction> {
192    pub fn map_handler_action<O, F>(self, f: F) -> BehaviorEvent<TEvent, O>
193    where
194        F: FnOnce(THandlerAction) -> O,
195    {
196        match self {
197            BehaviorEvent::Behavior(event) => BehaviorEvent::Behavior(event),
198            BehaviorEvent::HandlerAction {
199                peer_id,
200                handler,
201                action,
202            } => BehaviorEvent::HandlerAction {
203                peer_id,
204                handler,
205                action: f(action),
206            },
207            BehaviorEvent::CloseConnection {
208                peer_id,
209                connection,
210            } => BehaviorEvent::CloseConnection {
211                peer_id,
212                connection,
213            },
214        }
215    }
216
217    pub fn map_event<O, F>(self, f: F) -> BehaviorEvent<O, THandlerAction>
218    where
219        F: FnOnce(TEvent) -> O,
220    {
221        match self {
222            BehaviorEvent::Behavior(event) => BehaviorEvent::Behavior(f(event)),
223            BehaviorEvent::HandlerAction {
224                peer_id,
225                handler,
226                action,
227            } => BehaviorEvent::HandlerAction {
228                peer_id,
229                handler,
230                action,
231            },
232            BehaviorEvent::CloseConnection {
233                peer_id,
234                connection,
235            } => BehaviorEvent::CloseConnection {
236                peer_id,
237                connection,
238            },
239        }
240    }
241}
242
243#[derive(Debug, Clone)]
244pub enum NotifyHandler {
245    One(ConnectionId),
246    Any,
247}
248
249#[derive(Debug, Clone, Default)]
250pub enum CloseConnection {
251    One(ConnectionId),
252    #[default]
253    All,
254}