us changes

feature/configv2
prplV 2025-03-28 05:13:43 -04:00
parent 163887d42c
commit 026a502044
6 changed files with 69 additions and 57 deletions

View File

@ -2,6 +2,12 @@ use clap::{Parser, Subcommand};
#[derive(Debug, Parser, serde::Serialize, serde::Deserialize)] #[derive(Debug, Parser, serde::Serialize, serde::Deserialize)]
pub struct Cli { pub struct Cli {
#[arg(
short,
default_value="noxis-rs.sock",
help="explicit specify of NOXIS Socket file"
)]
pub socket : String,
#[command( #[command(
subcommand, subcommand,
help = "to manage Noxis work", help = "to manage Noxis work",

View File

@ -1,14 +1,15 @@
use thiserror::Error; use thiserror::Error;
use super::cli_net::NOXIS_RS_CREDS;
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum NoxisCliError { pub enum NoxisCliError {
#[error("Can't send any data to {:?}. Noxis-rs daemon is disabled or can't be accessed", NOXIS_RS_CREDS)] #[error("Can't find socket `{0}`. Noxis-rs daemon is disabled or can't be accessed using Unix-Socket")]
NoxisDaemonMissing, NoxisDaemonMissing(String),
#[error("Noxis CLI can't write any data to the Noxis-rs port. Check daemon and it's web-functionality")] #[error("Noxis CLI can't write any data to the Noxis-rs port. Check daemon and it's runtime!")]
PortIsNotWritable, PortIsNotWritable,
#[error("Can't send Cli-prompt to the Noxis-rs. Check it's state")] #[error("Can't send Cli-prompt to the Noxis-rs. Check it's state")]
CliPromptCanNotBeSent, CliPromptCanNotBeSent,
#[error("Can't parse CLI struct and send as byte stream")] #[error("Can't parse CLI struct and send as byte stream")]
ToStringCliParsingParsing, ToStringCliParsingParsing,
#[error("Can't read Noxis response")]
CliResponseReadError
} }

View File

@ -1,32 +1,30 @@
use tokio::net::TcpStream; use tokio::net::UnixStream;
use tokio::io::AsyncWriteExt; use tokio::io::{AsyncWriteExt, AsyncReadExt};
use tokio::time::{Duration, sleep}; use tokio::time::{Duration, sleep};
use anyhow::Result; use anyhow::Result;
use super::Cli; use super::Cli;
use super::cli_error::NoxisCliError; use super::cli_error::NoxisCliError;
pub const NOXIS_RS_CREDS: &str = "127.0.0.1:7753"; async fn create_us_stream(cli: &Cli) -> Result<UnixStream> {
Ok(UnixStream::connect(&cli.socket).await.map_err(|_| NoxisCliError::NoxisDaemonMissing((&cli.socket).to_string()))?)
pub async fn create_tcp_stream() -> Result<TcpStream> {
Ok(TcpStream::connect(NOXIS_RS_CREDS).await.map_err(|_| NoxisCliError::NoxisDaemonMissing)?)
} }
pub async fn try_send(stream: Result<TcpStream>, params: Cli) -> Result<()> { pub async fn try_send(cli: Cli) -> Result<()> {
use serde_json::to_string; // let stream = create_us_stream(&cli).await;
let mut stream = stream.map_err(|_| NoxisCliError::NoxisDaemonMissing)?; let mut stream = create_us_stream(&cli).await?;
loop {
if stream.writable().await.is_err() {
sleep(Duration::from_millis(100)).await;
continue;
}
// let msg: Cli = from_str(&format!("{:?}", params))?;
let msg= to_string(&params).map_err(|_| NoxisCliError::ToStringCliParsingParsing)?;
// let msg = r"HTTP/1.1 POST\r\nContent-Length: 14\r\nContent-Type: text/plain\r\n\r\nHello, World!@";
stream.write_all(msg.as_bytes()).await.map_err(|_| NoxisCliError::CliPromptCanNotBeSent)?; let msg = serde_json::to_vec(&cli)
// ... .map_err(|_| NoxisCliError::ToStringCliParsingParsing)?;
break;
} stream.write_all(&msg).await
.map_err(|_| NoxisCliError::CliPromptCanNotBeSent)?;
stream.shutdown().await?;
let mut response = Vec::new();
stream.read_to_end(&mut response).await
.map_err(|_| NoxisCliError::CliResponseReadError)?;
println!("Received response: {}", String::from_utf8_lossy(&response));
Ok(()) Ok(())
} }

View File

@ -4,12 +4,12 @@ mod cli_error;
use clap::Parser; use clap::Parser;
use cli::Cli; use cli::Cli;
use cli_net::{create_tcp_stream, try_send}; use cli_net::try_send;
use anyhow::Result; use anyhow::Result;
#[tokio::main] #[tokio::main]
async fn main() -> Result<()>{ async fn main() -> Result<()>{
let cli = Cli::parse(); let cli = Cli::parse();
try_send(create_tcp_stream().await, cli).await?; try_send(cli).await?;
Ok(()) Ok(())
} }

View File

@ -1,7 +1,6 @@
mod options; mod options;
mod utils; mod utils;
use anyhow::Error;
use clap::Parser; use clap::Parser;
use log::{error, info}; use log::{error, info};
use options::config::*; use options::config::*;

View File

@ -1,13 +1,11 @@
use log::{error, info, warn}; use log::{error, info};
use tokio::net::{TcpListener, TcpStream, UnixStream}; use tokio::net::{ UnixStream, UnixListener };
use anyhow::{Result as DynResult, Error}; use anyhow::Result as DynResult;
use tokio::time::{sleep, Duration}; use tokio::time::{sleep, Duration};
use std::{borrow::BorrowMut, fs, net::{IpAddr, Ipv4Addr}}; use std::fs;
// use std::io::BufReader; // use std::io::BufReader;
use tokio::io::{BufReader, AsyncWriteExt, AsyncBufReadExt}; use tokio::io::{ AsyncWriteExt, AsyncReadExt};
use tokio::{io::AsyncReadExt, net::UnixListener};
use noxis_cli::Cli; use noxis_cli::Cli;
use serde_json::from_str;
/// # Fn `init_cli_pipeline` /// # Fn `init_cli_pipeline`
/// ## for catching all input requests from CLI /// ## for catching all input requests from CLI
@ -25,12 +23,19 @@ use serde_json::from_str;
pub async fn init_cli_pipeline() -> DynResult<()> { pub async fn init_cli_pipeline() -> DynResult<()> {
match init_listener().await { match init_listener().await {
Ok(list) => { Ok(list) => {
info!("Successfully opened UnixListener for CLI"); // TODO: remove `unwrap`s
info!("Listening on {}", &list.local_addr()?.as_pathname().unwrap().display());
loop { loop {
if let Ok((socket, _)) = list.accept().await {
if let Ok((socket, a)) = list.accept().await {
info!("CLI connection from {}", a.as_pathname().unwrap().display());
process_connection(socket).await; process_connection(socket).await;
} else {
error!("Cannot poll connection to CLI");
} }
sleep(Duration::from_millis(500)).await; dbg!(1);
sleep(Duration::from_millis(300)).await;
} }
// Ok(()) // Ok(())
}, },
@ -65,7 +70,7 @@ async fn init_listener() -> anyhow::Result<UnixListener> {
// None // None
// } // }
// } // }
let socket_path = "noxis-rs"; let socket_path = "noxis-rs.sock";
let _ = fs::remove_file(socket_path); let _ = fs::remove_file(socket_path);
Ok(UnixListener::bind(socket_path)?) Ok(UnixListener::bind(socket_path)?)
} }
@ -84,25 +89,28 @@ async fn init_listener() -> anyhow::Result<UnixListener> {
/// *depends on* : `tokio::net::TcpStream` /// *depends on* : `tokio::net::TcpStream`
/// ///
async fn process_connection(mut stream: UnixStream) { async fn process_connection(mut stream: UnixStream) {
let buf_reader = BufReader::new(stream.borrow_mut()); info!("Processing new connection");
let mut rqst = buf_reader.lines();
while let Ok(Some(line)) = rqst.next_line().await {
if line.is_empty() {
break
}
match from_str::<Cli>(&line) {
Ok(req) => {
// TODO: func wrapper
dbg!(req);
},
Err(_) => {
break
},
}
println!("{}", line);
}
let mut buf = Vec::new();
match stream.read_to_end(&mut buf).await {
Ok(_) => {
match serde_json::from_slice::<Cli>(&buf) {
Ok(cli) => {
info!("Received CLI request: {:?}", cli);
// Обработка запроса
let response = "OK"; let response = "OK";
stream.write_all(response.as_bytes()).await.unwrap(); if let Err(e) = stream.write_all(response.as_bytes()).await {
error!("Failed to send response: {}", e);
}
}
Err(e) => {
error!("Failed to parse CLI request: {}", e);
}
}
}
Err(e) => {
error!("Failed to read from socket: {}", e);
}
}
let _ = stream.shutdown().await;
} }