use std::io::{BufRead, BufReader, Error as IoError};
use std::process::{Command, Stdio};
use log::debug;
use tokio::sync::mpsc;
use tonic::Status;
use crate::activation::{HeadedResponse, ResponseHeader};
use crate::errors::ServerError;
pub fn decode_session_id(message: &str) -> Result<[u8; 32], ServerError> {
(0..message.len())
.step_by(2)
.map(|i| u8::from_str_radix(&message[i..i + 2], 16))
.collect::<Result<Vec<u8>, _>>()
.map_err(|_| ServerError::InvalidSessionId)?
.try_into()
.map_err(|_| ServerError::InvalidSessionId)
}
pub async fn run_command<T: Send + HeadedResponse>(
tx: mpsc::Sender<Result<T, Status>>,
mut command: Command,
) -> std::io::Result<Vec<T>> {
debug!(
"Running command `{} {} {}`",
command
.get_envs()
.map(|(name, value)| format!(
"{}={}",
name.display(),
value.unwrap_or_default().display()
))
.collect::<Vec<_>>()
.join(" "),
command.get_program().display(),
command
.get_args()
.map(|a| format!("{}", a.display()))
.collect::<Vec<_>>()
.join(" ")
);
let mut responses = Vec::new();
let send = async |message| {
tx.send(Ok(T::from_header(message)))
.await
.map_err(|err| IoError::other(format!("{err}")))
};
let mut exec = match command
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
{
Ok(e) => e,
Err(e) => {
send(ResponseHeader::error(format!(
"Error while executing command: {e:?}"
)))
.await?;
return Err(e);
}
};
let mut stdout = BufReader::new(
exec.stdout
.take()
.ok_or(IoError::other("Cannot take stdout from execution"))?,
)
.lines();
let mut stderr = BufReader::new(
exec.stderr
.take()
.ok_or(IoError::other("Cannot take stderr from execution"))?,
)
.lines();
loop {
for stderr_line in stderr.by_ref() {
send(ResponseHeader::log(stderr_line?)).await?;
}
for stdout_line in stdout.by_ref() {
let header = ResponseHeader::log(stdout_line?);
send(header.clone()).await?;
responses.push(T::from_header(header));
}
match exec.try_wait() {
Ok(Some(status)) => {
if !status.success() {
send(ResponseHeader::error(format!(
"Command exited with code {status}"
)))
.await?;
return match status.code() {
Some(code) => {
Err(IoError::other(format!("Exited with non-zero code: {code}")))
}
None => Err(IoError::other("Exited without code")),
};
}
break;
}
Err(e) => {
send(ResponseHeader::error(format!(
"Error while executing command: {e:?}"
)))
.await?;
return Err(e);
}
_ => (),
}
}
Ok(responses)
}