bee_gossip/service/
command.rs

1// Copyright 2020-2021 IOTA Stiftung
2// SPDX-License-Identifier: Apache-2.0
3
4use libp2p_core::{Multiaddr, PeerId};
5use tokio::sync::mpsc;
6
7use super::error::Error;
8use crate::peer::info::PeerRelation;
9
10pub type CommandReceiver = mpsc::UnboundedReceiver<Command>;
11pub type CommandSender = mpsc::UnboundedSender<Command>;
12
13pub fn command_channel() -> (CommandSender, CommandReceiver) {
14    mpsc::unbounded_channel()
15}
16
17/// Describes the commands accepted by the networking layer.
18#[derive(Debug, Eq, PartialEq)]
19#[non_exhaustive]
20pub enum Command {
21    /// Adds a peer.
22    AddPeer {
23        /// The peer's id.
24        peer_id: PeerId,
25        /// The peer's address.
26        multiaddr: Multiaddr,
27        /// The peer's optional alias.
28        alias: Option<String>,
29        /// The relation with that peer.
30        relation: PeerRelation,
31    },
32    /// Removes a peer.
33    RemovePeer {
34        /// The peer's id.
35        peer_id: PeerId,
36    },
37    /// Dials a peer.
38    DialPeer {
39        /// The peer's id.
40        peer_id: PeerId,
41    },
42    /// Dials an address.
43    DialAddress {
44        /// The peer's address.
45        address: Multiaddr,
46    },
47    /// Disconnects a peer.
48    DisconnectPeer {
49        /// The peer's id.
50        peer_id: PeerId,
51    },
52    /// Bans a peer.
53    BanPeer {
54        /// The peer's id.
55        peer_id: PeerId,
56    },
57    /// Unbans a peer.
58    UnbanPeer {
59        /// The peer's id.
60        peer_id: PeerId,
61    },
62    /// Bans an address.
63    BanAddress {
64        /// The peer's address.
65        address: Multiaddr,
66    },
67    /// Unbans an address.
68    UnbanAddress {
69        /// The peer's address.
70        address: Multiaddr,
71    },
72    /// Upgrades the relation with a peer.
73    ChangeRelation {
74        /// The peer's id.
75        peer_id: PeerId,
76        /// The peer's new relation.
77        to: PeerRelation,
78    },
79}
80
81/// Allows the user to send [`Command`]s to the network layer.
82#[derive(Clone, Debug)]
83pub struct NetworkCommandSender(CommandSender);
84
85impl NetworkCommandSender {
86    pub(crate) fn new(inner: CommandSender) -> Self {
87        Self(inner)
88    }
89
90    /// Sends a command to the network.
91    ///
92    /// NOTE: Although synchronous, this method never actually blocks.
93    pub fn send(&self, command: Command) -> Result<(), Error> {
94        self.0.send(command).map_err(|_| Error::SendingCommandFailed)
95    }
96}