Skip to main content

mtorrent_dht/
cmds.rs

1use derive_more::Debug;
2use futures_util::Stream;
3use std::net::SocketAddr;
4use std::pin::Pin;
5use std::task::{Context, Poll};
6use tokio::sync::mpsc;
7
8/// Command from the user to the DHT system.
9#[derive(Debug)]
10pub enum Command {
11    /// Attempt to connect to a new node and insert it into the routing table.
12    AddNode {
13        addr: SocketAddr,
14    },
15    /// Commence search for peers for the given torrent.
16    FindPeers {
17        /// Info hash of the torrent.
18        info_hash: [u8; 20],
19        /// Channel for sending back addresses of the discovered peers.
20        #[debug(skip)]
21        callback: mpsc::Sender<SocketAddr>,
22        /// Peer wire protocol port of the local peer.
23        local_peer_port: u16,
24    },
25    /// Shut down the DHT system.
26    Shutdown,
27}
28
29/// Command receiver used internally by the DHT code.
30pub struct CommandSource(mpsc::Receiver<Command>);
31
32impl Stream for CommandSource {
33    type Item = Command;
34
35    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
36        self.0.poll_recv(cx)
37    }
38}
39
40/// Sender of commands to the DHT system.
41pub type CommandSink = mpsc::Sender<Command>;
42
43/// Set up a channel for the user commands to the DHT system.
44pub fn setup_commands() -> (CommandSink, CommandSource) {
45    let (sender, receiver) = mpsc::channel(1);
46    (sender, CommandSource(receiver))
47}