libp2p_pubsub_core/protocol/
router_trait.rs

1use std::rc::Rc;
2
3use libp2p::PeerId;
4
5use libp2p_pubsub_common::service::Service;
6
7use crate::framing::Message as FrameMessage;
8use crate::subscription::Subscription;
9use crate::topic::TopicHash;
10
11/// A pubsub protocol router input event.
12#[derive(Debug, Clone)]
13pub enum ProtocolRouterInEvent {
14    /// A connection event.
15    ConnectionEvent(ProtocolRouterConnectionEvent),
16    /// A subscription event.
17    SubscriptionEvent(ProtocolRouterSubscriptionEvent),
18    /// A was message received from a peer.
19    MessageReceived {
20        /// The message propagator.
21        src: PeerId,
22        /// The message.
23        message: Rc<FrameMessage>,
24    },
25    /// A message ready to publish.
26    ///
27    /// This event is generated by the `publish` method of the pubsub behaviour.
28    MessagePublished(Rc<FrameMessage>),
29}
30
31/// A pubsub protocol router connection event.
32#[derive(Debug, Clone)]
33pub enum ProtocolRouterConnectionEvent {
34    /// A new peer connected.
35    PeerConnected(PeerId),
36    /// A peer disconnected.
37    PeerDisconnected(PeerId),
38}
39
40/// A pubsub protocol router topic subscription event.
41#[derive(Debug, Clone)]
42pub enum ProtocolRouterSubscriptionEvent {
43    /// A subscription event.
44    Subscribed(Subscription),
45    /// An unsubscription event.
46    Unsubscribed(TopicHash),
47    /// A peer subscribed to a topic.
48    PeerSubscribed { peer: PeerId, topic: TopicHash },
49    /// A peer unsubscribed from a topic.
50    PeerUnsubscribed { peer: PeerId, topic: TopicHash },
51}
52
53/// A pubsub protocol router output event.
54#[derive(Debug, Clone)]
55pub enum ProtocolRouterOutEvent {
56    /// Forward the message to the given peers.
57    ForwardMessage {
58        /// The destination peers.
59        dest: Vec<PeerId>,
60        /// The message.
61        message: Rc<FrameMessage>,
62    },
63}
64
65// NOTE: Use `trait_set` crate as `trait_alias` is not yet stable.
66//       https://github.com/rust-lang/rust/issues/41517
67trait_set::trait_set! {
68    /// The protocol message router service trait.
69    ///
70    /// This trait is used by the [`Behaviour`] to route received (and published) messages
71    /// to the appropriate peers.
72    ///
73    /// It handles the [`ProtocolRouterInEvent`] and generates [`ProtocolRouterOutEvent`] events.
74    pub trait ProtocolRouter = Service<InEvent = ProtocolRouterInEvent, OutEvent = ProtocolRouterOutEvent>;
75}