exedev 0.1.0

Official Rust SDK for exe.dev: create VMs, run commands on them, and run every exe.dev command
Documentation
// Code generated by "go run ./cmd/gensdkrs" in the exe.dev repository. DO NOT EDIT.

//! Background processes that [`Vm::spawn`] starts.

use std::future::IntoFuture;
use std::time::Duration;

use tokio::time::Instant;

use crate::client::{BoxFuture, SshOptions};
use crate::error::{Error, InterruptKind, Result};
use crate::scripts::*;
use crate::vm::{CommandResult, Vm};
use crate::wire::{self, MAX_OUTPUT, MISSING, ProcessState, sh};

/// A process that [`Vm::spawn`] started on a VM.
///
/// It does not depend on this program: it runs until it exits or is
/// killed. Find it again later with [`Vm::process`]. Its attributes are a
/// snapshot; [`poll`](Process::poll) and [`wait`](Process::wait) update
/// them. Dropping a `Process` leaves the process running.
#[derive(Clone)]
pub struct Process {
    vm: Vm,
    name: String,
    state: ProcessState,
}

impl std::fmt::Debug for Process {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Process")
            .field("vm", &self.vm.name())
            .field("name", &self.name)
            .field("pid", &self.state.pid)
            .field("exit_code", &self.state.exit_code)
            .field("lost", &self.state.lost)
            .finish()
    }
}

/// A process's output so far; see [`Process::logs`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Logs {
    /// Its standard output.
    pub stdout: Vec<u8>,
    /// Its standard error.
    pub stderr: Vec<u8>,
}

impl Logs {
    /// Standard output as text; invalid UTF-8 becomes U+FFFD.
    pub fn stdout_lossy(&self) -> String {
        String::from_utf8_lossy(&self.stdout).into_owned()
    }

    /// Standard error as text; invalid UTF-8 becomes U+FFFD.
    pub fn stderr_lossy(&self) -> String {
        String::from_utf8_lossy(&self.stderr).into_owned()
    }
}

impl Process {
    pub(crate) fn new(vm: Vm, name: String, state: ProcessState) -> Process {
        Process { vm, name, state }
    }

    /// The VM it runs on.
    pub fn vm(&self) -> &Vm {
        &self.vm
    }

    /// Its name, which [`Vm::process`] finds it by.
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Its process ID on the VM, which is also its process group's; 0 if
    /// that is unknown, as it can be for a lost process.
    pub fn pid(&self) -> u32 {
        self.state.pid
    }

    /// Its exit status, or None if it was running when last seen. A process
    /// killed by a signal has 128 plus the signal's number.
    pub fn exit_code(&self) -> Option<i32> {
        self.state.exit_code
    }

    fn lost(&self) -> Error {
        Error::ProcessLost {
            process: self.name.clone(),
            vm: self.vm.name().to_string(),
        }
    }

    /// Its exit status, or None if it is still running.
    /// [`Error::ProcessLost`] if it ended without one.
    pub async fn poll(&mut self) -> Result<Option<i32>> {
        let result = self
            .vm
            .script(&sh(STATE_SCRIPT, &[&self.name]), MAX_OUTPUT, &[MISSING])
            .await?;
        if result.exit_code == MISSING {
            return Err(self.vm.no_such_process(&self.name));
        }
        self.state = wire::process_state(&result.stdout_lossy())?;
        if self.state.lost {
            return Err(self.lost());
        }
        Ok(self.state.exit_code)
    }

    /// Waits for it to exit, and returns how it ended, with its output.
    ///
    /// A lost connection does not matter: it reconnects until it knows.
    /// [`Error::ProcessLost`] if it ended without an exit status.
    pub fn wait(&mut self) -> Wait<'_> {
        Wait {
            process: self,
            timeout: None,
            check: false,
            capture: true,
            max_output: MAX_OUTPUT,
        }
    }

    /// Its output so far.
    pub fn logs(&self) -> LogsRequest<'_> {
        LogsRequest {
            process: self,
            tail: None,
        }
    }

    /// Sends a signal, such as `"HUP"` or `"9"`, to the process and
    /// everything it started, if it is running.
    pub async fn send_signal(&self, signal: &str) -> Result<()> {
        let command = sh(KILL_SCRIPT, &[&self.name, &wire::signal_name(signal)?]);
        let result = self.vm.script(&command, MAX_OUTPUT, &[MISSING]).await?;
        if result.exit_code == MISSING {
            return Err(self.vm.no_such_process(&self.name));
        }
        Ok(())
    }

    /// Sends SIGTERM to the process and everything it started.
    pub async fn terminate(&self) -> Result<()> {
        self.send_signal("TERM").await
    }

    /// Sends SIGKILL to the process and everything it started.
    pub async fn kill(&self) -> Result<()> {
        self.send_signal("KILL").await
    }
}

/// [`Process::wait`].
#[must_use = "a request does nothing until it is awaited"]
pub struct Wait<'a> {
    process: &'a mut Process,
    timeout: Option<Duration>,
    check: bool,
    capture: bool,
    max_output: usize,
}

impl Wait<'_> {
    /// How long to wait: [`Error::ProcessTimeout`] if it is still running
    /// then (which it still is).
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// As for [`Run::check`](crate::vm::Run::check).
    pub fn check(mut self, check: bool) -> Self {
        self.check = check;
        self
    }

    /// As for [`Run::capture`](crate::vm::Run::capture): without it, the
    /// result has no output.
    pub fn capture(mut self, capture: bool) -> Self {
        self.capture = capture;
        self
    }

    /// As for [`Run::max_output`](crate::vm::Run::max_output).
    pub fn max_output(mut self, bytes: usize) -> Self {
        self.max_output = bytes;
        self
    }
}

impl<'a> IntoFuture for Wait<'a> {
    type Output = Result<CommandResult>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let p = self.process;
            let deadline = self.timeout.map(|t| Instant::now() + t);
            let nonce = wire::random_hex(8);
            let command = sh(WAIT_SCRIPT, &[&p.name, &nonce, if self.capture { "1" } else { "" }]);
            let mut backoff = Duration::from_millis(100);
            let result = loop {
                let remaining = deadline.map(|d| d.saturating_duration_since(Instant::now()));
                if remaining.is_some_and(|r| r.is_zero()) {
                    return Err(Error::ProcessTimeout {
                        process: p.name.clone(),
                        vm: p.vm.name().to_string(),
                    });
                }
                let options = SshOptions {
                    max_output: self.max_output,
                    timeout: remaining,
                    ..SshOptions::default()
                };
                match p.vm.t.ssh(p.vm.name(), &command, options).await {
                    Ok(result) => break result,
                    Err(Error::Interrupted(i)) if i.kind == InterruptKind::Timeout => continue,
                    Err(Error::Interrupted(i)) if i.kind == InterruptKind::Disconnected => {}
                    Err(Error::Network { .. }) => {}
                    Err(err) => return Err(err),
                }
                tokio::time::sleep(backoff).await;
                backoff = (backoff * 2).min(Duration::from_secs(2));
            };
            if result.exit_code == 0 && result.stdout == format!("{nonce} missing").as_bytes() {
                return Err(p.vm.no_such_process(&p.name));
            }
            if result.exit_code == 0 && result.stdout == format!("{nonce} lost").as_bytes() {
                p.state.lost = true;
                return Err(p.lost());
            }
            p.state.exit_code = Some(result.exit_code);
            if self.check { result.check() } else { Ok(result) }
        })
    }
}

/// [`Process::logs`].
#[must_use = "a request does nothing until it is awaited"]
pub struct LogsRequest<'a> {
    process: &'a Process,
    tail: Option<usize>,
}

impl LogsRequest<'_> {
    /// At most this many lines from the end of each stream.
    pub fn tail(mut self, lines: usize) -> Self {
        self.tail = Some(lines);
        self
    }
}

impl<'a> IntoFuture for LogsRequest<'a> {
    type Output = Result<Logs>;
    type IntoFuture = BoxFuture<'a, Self::Output>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(async move {
            let p = self.process;
            let tail = self.tail.map(|n| n.to_string()).unwrap_or_default();
            let result =
                p.vm.script(&sh(LOGS_SCRIPT, &[&p.name, &tail]), usize::MAX, &[MISSING])
                    .await?;
            if result.exit_code == MISSING {
                return Err(p.vm.no_such_process(&p.name));
            }
            Ok(Logs {
                stdout: result.stdout,
                stderr: result.stderr,
            })
        })
    }
}