federation_net/event.rs
1//! Network events delivered to the application.
2
3use iroh::EndpointId;
4use tokio::sync::mpsc;
5
6/// Direction of an established peer connection.
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
8pub enum ConnectionDirection {
9 /// The remote peer connected to us.
10 Incoming,
11 /// We connected to the remote peer.
12 Outgoing,
13}
14
15/// Events emitted by a [`crate::NetworkEngine`].
16///
17/// `M` is the application-defined domain message type.
18#[derive(Debug)]
19pub enum NetworkEvent<M> {
20 /// A peer completed the handshake and is now connected.
21 PeerConnected {
22 /// Identifier of the connected peer.
23 peer_id: EndpointId,
24 /// Whether the peer connected to us or we connected to it.
25 direction: ConnectionDirection,
26 },
27
28 /// A peer disconnected.
29 PeerDisconnected {
30 /// Identifier of the disconnected peer.
31 peer_id: EndpointId,
32 /// Human-readable reason, if one is known.
33 reason: Option<String>,
34 },
35
36 /// A domain message was received from a peer.
37 MessageReceived {
38 /// Identifier of the sending peer.
39 peer_id: EndpointId,
40 /// The decoded domain message.
41 message: M,
42 },
43
44 /// A protocol-level error occurred.
45 ///
46 /// Errors of a single connection never bring down the engine; they are
47 /// reported here instead.
48 ProtocolError {
49 /// The peer involved, if known.
50 peer_id: Option<EndpointId>,
51 /// Human-readable error description.
52 error: String,
53 },
54}
55
56/// Receiving side of the engine's event channel.
57///
58/// There is exactly one receiver per engine; it is returned from
59/// [`crate::NetworkEngine::start`]. The underlying channel is bounded, so the
60/// application should consume events promptly to avoid back-pressuring the
61/// engine.
62#[derive(Debug)]
63pub struct NetworkEventReceiver<M> {
64 rx: mpsc::Receiver<NetworkEvent<M>>,
65}
66
67impl<M> NetworkEventReceiver<M> {
68 pub(crate) fn new(rx: mpsc::Receiver<NetworkEvent<M>>) -> Self {
69 Self { rx }
70 }
71
72 /// Receives the next event.
73 ///
74 /// Returns `None` after the engine has shut down and all pending events
75 /// have been consumed.
76 pub async fn recv(&mut self) -> Option<NetworkEvent<M>> {
77 self.rx.recv().await
78 }
79}