arcana-base-server 0.6.0

Library to help create your own arcana activation server
Documentation
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;

/// Decodes a hex string to 32 bytes' session id.
///
/// # Errors
///
/// Will return `ServerError::InvalidSessionId` if the string is not 32-bytes (64-chars) long
/// or if the string cannot be parsed into u8s.
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)
}

/// Runs a system command and passes messages to the `Sender`.
///
/// This need the generic type to implement `HeadedResponse` to parse
/// stdout and stderr messages.
///
/// # Errors
///
/// Will return `std::io::Error` if the command execution is failing.
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)
}