1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
use crate::ext::anyhow::{bail, Context, Result};
use std::{
    net::SocketAddr,
    process::{Output, Stdio},
    time::Duration,
};
use tokio::{
    net::TcpStream,
    process::{Child, Command},
    sync::broadcast,
    time::sleep,
};

pub trait OutputExt {
    fn stderr(&self) -> String;
    fn has_stderr(&self) -> bool;
    fn stdout(&self) -> String;
    fn has_stdout(&self) -> bool;
}

impl OutputExt for Output {
    fn stderr(&self) -> String {
        String::from_utf8_lossy(&self.stderr).to_string()
    }

    fn has_stderr(&self) -> bool {
        println!("stderr: {}\n'{}'", self.stderr.len(), self.stderr());
        self.stderr.len() > 1
    }

    fn stdout(&self) -> String {
        String::from_utf8_lossy(&self.stdout).to_string()
    }

    fn has_stdout(&self) -> bool {
        self.stdout.len() > 1
    }
}
pub enum CommandResult<T> {
    Success(T),
    Failure(T),
    Interrupted,
}

pub async fn wait_interruptible(name: &str, mut process: Child, mut interrupt_rx: broadcast::Receiver<()>) -> Result<CommandResult<()>> {
    tokio::select! {
        res = process.wait() => match res {
            Ok(exit) => {
                if exit.success() {
                    log::trace!("{name} process finished with success");
                    Ok(CommandResult::Success(()))
                } else {
                    log::trace!("{name} process finished with code {:?}", exit.code());
                    Ok(CommandResult::Failure(()))
                }
            }
            Err(e) => bail!("Command failed due to: {e}"),
        },
        _ = interrupt_rx.recv() => {
            process.kill().await.context("Could not kill process")?;
            log::trace!("{name} process interrupted");
            Ok(CommandResult::Interrupted)
        }
    }
}

pub async fn wait_piped_interruptible(name: &str, mut cmd: Command, mut interrupt_rx: broadcast::Receiver<()>) -> Result<CommandResult<Output>> {
    // see: https://docs.rs/tokio/latest/tokio/process/index.html

    cmd.kill_on_drop(true);
    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());
    let process = cmd.spawn()?;
    tokio::select! {
        res = process.wait_with_output() => match res {
            Ok(output) => {
                if output.status.success() {
                    log::trace!("{name} process finished with success");
                    Ok(CommandResult::Success(output))
                } else {
                    log::trace!("{name} process finished with code {:?}", output.status.code());
                    Ok(CommandResult::Failure(output))
                }
            }
            Err(e) => bail!("Command failed due to: {e}"),
        },
        _ = interrupt_rx.recv() => {
            log::trace!("{name} process interrupted");
            Ok(CommandResult::Interrupted)
        }
    }
}
pub async fn wait_for_socket(name: &str, addr: SocketAddr) -> bool {
    let duration = Duration::from_millis(500);

    for _ in 0..20 {
        if TcpStream::connect(&addr).await.is_ok() {
            log::debug!("{name} server port {addr} open");
            return true;
        }
        sleep(duration).await;
    }
    log::warn!("{name} timed out waiting for port {addr}");
    false
}