use log::{error, info}; use tokio::net::{ UnixStream, UnixListener }; use anyhow::Result as DynResult; use tokio::time::{sleep, Duration}; use std::fs; // use std::io::BufReader; use tokio::io::{ AsyncWriteExt, AsyncReadExt}; use noxis_cli::Cli; /// # Fn `init_cli_pipeline` /// ## for catching all input requests from CLI /// /// *input* : - /// /// *output* : `anyhow::Result<()>` to wrap errors /// /// *initiator* : fn `main` /// /// *managing* : `TcpListener` object to handle requests /// /// *depends on* : - /// pub async fn init_cli_pipeline() -> DynResult<()> { match init_listener().await { Ok(list) => { // TODO: remove `unwrap`s info!("Listening on {}", &list.local_addr()?.as_pathname().unwrap().display()); loop { if let Ok((socket, a)) = list.accept().await { info!("CLI connection from {}", a.as_pathname().unwrap().display()); process_connection(socket).await; } else { error!("Cannot poll connection to CLI"); } dbg!(1); sleep(Duration::from_millis(300)).await; } // Ok(()) }, Err(er) => { error!("Failed to open UnixListener for CLI"); Err(er) }, } } /// # Fn `init_listener` /// ## for creating TCP-listener for communicating with CLI /// /// *input* : - /// /// *output* : `Some` if port 7753 was opened | None if not /// /// *initiator* : fn `init_cli_pipeline` /// /// *managing* : `TcpListener` object to handle requests /// /// *depends on* : `tokio::net::TcpListener` /// async fn init_listener() -> anyhow::Result { // match TcpListener::bind("127.0.0.1:7753").await { // Ok(listener) => { // info!("Runner is listening localhost:7753"); // Some(listener) // }, // Err(_) => { // error!("Cannot create TCP listener for CLI"); // None // } // } let socket_path = "noxis-rs.sock"; let _ = fs::remove_file(socket_path); Ok(UnixListener::bind(socket_path)?) } /// # Fn `process_connection` /// ## for processing input CLI requests /// /// *input* : mut stream: `TcpStream` /// /// *output* : - /// /// *initiator* : fn `init_cli_pipeline` /// /// *managing* : mutable object of `TcpStream` /// /// *depends on* : `tokio::net::TcpStream` /// async fn process_connection(mut stream: UnixStream) { info!("Processing new connection"); let mut buf = Vec::new(); match stream.read_to_end(&mut buf).await { Ok(_) => { match serde_json::from_slice::(&buf) { Ok(cli) => { info!("Received CLI request: {:?}", cli); // Обработка запроса let response = "OK"; 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; }