caretta-sync/lazy-supplements/src/cli/node.rs

81 lines
2 KiB
Rust
Raw Normal View History

2025-05-30 09:26:47 +09:00
use std::{net::IpAddr, path::PathBuf};
2025-06-06 06:50:28 +09:00
use clap::{Args, Parser, Subcommand};
2025-06-01 15:18:17 +09:00
use futures::StreamExt;
use libp2p::{
multiaddr::Protocol, noise, ping, swarm::SwarmEvent, tcp, yamux, Multiaddr
};
use tracing_subscriber::EnvFilter;
2025-06-02 12:02:04 +09:00
use crate::{cli::ServerArgs, error::Error};
use super::ConfigArgs;
2025-05-30 09:26:47 +09:00
2025-06-06 06:50:28 +09:00
#[derive(Debug, Args)]
2025-05-30 09:26:47 +09:00
pub struct NodeArgs {
#[command(subcommand)]
2025-06-01 16:29:35 +09:00
pub command: NodeCommand
2025-05-30 09:26:47 +09:00
}
2025-06-06 06:50:28 +09:00
#[derive(Debug, Parser)]
pub struct ConsoleNodeArgs {
#[command(flatten)]
pub args: NodeArgs,
}
2025-06-06 08:22:36 +09:00
impl NodeArgs {
2025-06-06 07:49:36 +09:00
pub async fn run(self) -> Result<(), Error> {
2025-06-06 06:50:28 +09:00
println!("{self:?}");
Ok(())
}
}
2025-06-06 07:49:36 +09:00
pub async fn parse_and_run_console_node_command(s:Vec<String>) -> Result<(), Error> {
2025-06-06 08:22:36 +09:00
ConsoleNodeArgs::try_parse_from(s)?.args.run().await
2025-06-06 06:50:28 +09:00
}
2025-05-30 09:26:47 +09:00
#[derive(Args, Debug)]
pub struct JoinNodeArgs {
#[arg(long)]
2025-06-02 12:02:04 +09:00
pub peer_ip: IpAddr,
2025-05-30 09:26:47 +09:00
#[arg(long)]
2025-06-02 12:02:04 +09:00
pub peer_port: u16,
//#[arg(long)]
//pub peer_id: String,
#[command(flatten)]
pub config: ConfigArgs,
2025-05-30 09:26:47 +09:00
}
#[derive(Debug, Subcommand)]
pub enum NodeCommand {
Ping(JoinNodeArgs),
Join(JoinNodeArgs),
}
2025-06-01 15:18:17 +09:00
impl JoinNodeArgs {
pub async fn ping(self) -> Result<(), Error> {
2025-06-02 12:02:04 +09:00
let mut swarm = self.config.try_into_node_config().await?.try_into_swarm().await?;
2025-06-01 15:18:17 +09:00
let mut remote: Multiaddr = Multiaddr::empty();
2025-06-02 12:02:04 +09:00
remote.push(match self.peer_ip {
2025-06-01 15:18:17 +09:00
IpAddr::V4(x) => Protocol::Ip4(x),
IpAddr::V6(x) => Protocol::Ip6(x),
});
2025-06-02 12:02:04 +09:00
remote.push(Protocol::Tcp(self.peer_port));
2025-06-01 15:18:17 +09:00
let addr = remote.to_string();
swarm.dial(remote)?;
println!("Dialed {addr}");
loop{
match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {address:?}"),
2025-06-04 07:13:37 +09:00
SwarmEvent::Behaviour(event) => {
println!("{event:?}");
event.run().await;
},
2025-06-01 15:18:17 +09:00
_ => {}
}
}
}
}