Add console command

This commit is contained in:
fluo10 2025-06-05 09:23:24 +09:00
parent 2910cfae4a
commit 10fc2d9946
6 changed files with 58 additions and 18 deletions

View file

@ -0,0 +1,28 @@
use std::time::Duration;
use clap::Args;
use futures::StreamExt;
use libp2p::{noise, ping, swarm::{NetworkBehaviour, SwarmEvent}, tcp, yamux, Swarm};
use tokio::time::sleep;
use tracing_subscriber::EnvFilter;
use crate::{error::Error, global::GLOBAL};
use super::ConfigArgs;
#[derive(Args, Debug)]
pub struct ConsoleArgs {
#[command(flatten)]
config: ConfigArgs,
}
impl ConsoleArgs {
pub async fn start_console(self) -> Result<(), Error>{
let _ = crate::global::GLOBAL.get_or_init_node_config(self.config.try_into_node_config().await?).await;
tokio::spawn( async {
GLOBAL.launch_swarm().await
});
sleep(Duration::from_secs(1)).await;
Ok(())
}
}

View file

@ -1,11 +1,13 @@
use std::path::PathBuf; use std::path::PathBuf;
mod config; mod config;
mod console;
mod init; mod init;
mod node; mod node;
mod server; mod server;
pub use config::ConfigArgs; pub use config::ConfigArgs;
pub use console::ConsoleArgs;
pub use init::InitArgs; pub use init::InitArgs;
pub use node::{ NodeArgs, NodeCommand, JoinNodeArgs }; pub use node::{ NodeArgs, NodeCommand, JoinNodeArgs };
pub use server::ServerArgs; pub use server::ServerArgs;

View file

@ -3,7 +3,7 @@ use futures::StreamExt;
use libp2p::{noise, ping, swarm::{NetworkBehaviour, SwarmEvent}, tcp, yamux, Swarm}; use libp2p::{noise, ping, swarm::{NetworkBehaviour, SwarmEvent}, tcp, yamux, Swarm};
use tracing_subscriber::EnvFilter; use tracing_subscriber::EnvFilter;
use crate::error::Error; use crate::{error::Error, global::GLOBAL};
use super::ConfigArgs; use super::ConfigArgs;
@ -14,16 +14,7 @@ pub struct ServerArgs {
} }
impl ServerArgs { impl ServerArgs {
pub async fn start_server(self) -> Result<(), Error>{ pub async fn start_server(self) -> Result<(), Error>{
let mut swarm = self.config.try_into_node_config().await?.try_into_swarm().await?; let _ = crate::global::GLOBAL.get_or_init_node_config(self.config.try_into_node_config().await?).await;
loop{ GLOBAL.launch_swarm().await
match swarm.select_next_some().await {
SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {address:?}"),
SwarmEvent::Behaviour(event) => {
println!("{event:?}");
event.run().await;
},
_ => {}
}
}
} }
} }

View file

@ -23,7 +23,7 @@ fn base64_to_keypair(base64: &str) -> Result<Keypair, Error> {
Ok(Keypair::from_protobuf_encoding(&vec)?) Ok(Keypair::from_protobuf_encoding(&vec)?)
} }
#[derive(Debug, Deserialize, Serialize)] #[derive(Clone, Debug, Deserialize, Serialize)]
pub struct NodeConfig { pub struct NodeConfig {
#[serde(with = "keypair_parser")] #[serde(with = "keypair_parser")]
pub secret: Keypair, pub secret: Keypair,

View file

@ -1,7 +1,8 @@
use std::{collections::HashMap, net::{IpAddr, Ipv4Addr}, path::PathBuf, sync::LazyLock}; use std::{collections::HashMap, net::{IpAddr, Ipv4Addr}, path::PathBuf, sync::LazyLock};
use crate::config::{NodeConfig, RawNodeConfig}; use crate::{config::{NodeConfig, RawNodeConfig}, error::Error};
use libp2p::{Multiaddr, PeerId}; use futures::StreamExt;
use libp2p::{swarm::SwarmEvent, Multiaddr, PeerId};
use sea_orm::DatabaseConnection; use sea_orm::DatabaseConnection;
use tokio::sync::{OnceCell, RwLock}; use tokio::sync::{OnceCell, RwLock};
@ -59,7 +60,7 @@ pub static GLOBAL: Global = Global{
pub struct Global { pub struct Global {
pub node_config: OnceCell<NodeConfig>, pub node_config: OnceCell<NodeConfig>,
pub database: OnceCell<DatabaseConnection>, pub database: OnceCell<DatabaseConnection>,
pub peers: OnceCell<RwLock<HashMap<PeerId, Multiaddr>>> pub peers: OnceCell<RwLock<HashMap<PeerId, Multiaddr>>>,
} }
#[cfg(test)] #[cfg(test)]
@ -69,7 +70,7 @@ impl Global {
pub fn get_node_config(&self) -> Option<&NodeConfig> { pub fn get_node_config(&self) -> Option<&NodeConfig> {
self.node_config.get() self.node_config.get()
} }
pub async fn get_or_try_init_node_config(&self, config: NodeConfig) -> &NodeConfig { pub async fn get_or_init_node_config(&self, config: NodeConfig) -> &NodeConfig {
self.node_config.get_or_init(|| async {config}).await self.node_config.get_or_init(|| async {config}).await
} }
pub async fn get_or_init_peers(&self) -> &RwLock<HashMap<PeerId, Multiaddr>> { pub async fn get_or_init_peers(&self) -> &RwLock<HashMap<PeerId, Multiaddr>> {
@ -83,6 +84,22 @@ impl Global {
pub async fn write_peers(&self) -> tokio::sync::RwLockWriteGuard<'_, HashMap<PeerId, Multiaddr>>{ pub async fn write_peers(&self) -> tokio::sync::RwLockWriteGuard<'_, HashMap<PeerId, Multiaddr>>{
self.get_or_init_peers().await.write().await self.get_or_init_peers().await.write().await
} }
pub async fn launch_swarm(&self) -> Result<(), Error> {
let mut swarm = self.get_node_config().unwrap().clone().try_into_swarm().await?;
loop{
let swarm_event = swarm.select_next_some().await;
tokio::spawn(async move{
match swarm_event {
SwarmEvent::NewListenAddr { address, .. } => println!("Listening on {address:?}"),
SwarmEvent::Behaviour(event) => {
println!("{event:?}");
event.run().await;
},
_ => {}
}
});
}
}
} }
pub static DEFAULT_RAW_NODE_CONFIG: LazyLock<RawNodeConfig> = LazyLock::new(|| { pub static DEFAULT_RAW_NODE_CONFIG: LazyLock<RawNodeConfig> = LazyLock::new(|| {

View file

@ -1,5 +1,5 @@
use clap::{Parser, Subcommand}; use clap::{Parser, Subcommand};
use lazy_supplements::{cli::{InitArgs, NodeArgs, NodeCommand, ServerArgs}, *}; use lazy_supplements::{cli::{ConsoleArgs, InitArgs, NodeArgs, NodeCommand, ServerArgs}, *};
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
struct Cli { struct Cli {
@ -9,6 +9,7 @@ struct Cli {
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
enum Command { enum Command {
Console(ConsoleArgs),
Node(NodeArgs), Node(NodeArgs),
Init(InitArgs), Init(InitArgs),
Server(ServerArgs), Server(ServerArgs),
@ -24,5 +25,6 @@ async fn main() {
}, },
Command::Init(x) => x.init_config().await, Command::Init(x) => x.init_config().await,
Command::Server(x) => x.start_server().await.unwrap(), Command::Server(x) => x.start_server().await.unwrap(),
Command::Console(x) => x.start_console().await.unwrap(),
} }
} }