bee_network/service/
command.rs

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