rustimal 0.8.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
//! Running T3 Code's server without its app: no window, started when `t3` needs it.
//!
//! A hidden rustimal process (`rustimal --t3-server`) runs `t3 serve` and watches over
//! it. It is a process of its own so that closing rustimal windows leaves the server, and
//! whatever its agents are doing, running.
//!
//! T3 Code allows one server per data folder, and its desktop app gives up with an error if
//! another one holds the folder. So the watcher stops the server as soon as the app is
//! opened; the app waits about ten seconds for that, and then starts its own.

use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::process::CommandExt;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::time::{Duration, Instant};

use crate::platform::process::{self, CREATE_NO_WINDOW, Job, free_port, state_file};

/// The port the desktop app uses too. T3 Code's web page keeps its sign-in per address, so
/// staying on it avoids pairing again.
const PORT: u16 = 3773;
const POLL: Duration = Duration::from_millis(250);
/// How long a server may take to be usable.
const START_TIMEOUT: Duration = Duration::from_secs(60);
/// After our own start has ended, how much longer to wait for a server someone else is
/// starting (another pane, say: only one of them gets the data folder).
const SOMEONE_ELSE: Duration = Duration::from_secs(10);

/// Where the desktop app keeps the lock it holds for as long as it runs.
fn desktop_lock() -> Option<PathBuf> {
    std::env::var_os("APPDATA").map(|d| PathBuf::from(d).join("t3code-v2").join("lockfile"))
}

/// Does anyone have this file open?
///
/// The app's lock is a file that is deleted when closed. It lets itself be opened by
/// anyone who, like Rust by default, allows the others everything, deleting included. So
/// ask to share it with no one: that fails whenever somebody else has it open.
fn is_held(path: &Path) -> bool {
    match std::fs::OpenOptions::new().read(true).share_mode(0).open(path) {
        Ok(_) => false,
        Err(e) => e.kind() != std::io::ErrorKind::NotFound,
    }
}

fn desktop_running() -> bool {
    desktop_lock().is_some_and(|lock| is_held(&lock))
}

/// Asks the watcher to stop; it removes the file to say it heard.
fn stop_request() -> Option<PathBuf> {
    state_file("t3-server.stop")
}

/// One line about what the watcher did, for when something goes wrong out of sight.
fn note(message: &str) {
    let Some(path) = state_file("t3-server.log") else { return };
    if let Some(folder) = path.parent() {
        let _ = std::fs::create_dir_all(folder);
    }
    let when = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs());
    // Only the latest run is kept, so it never grows.
    let before = std::fs::read_to_string(&path).unwrap_or_default();
    let kept = if message.starts_with("starting") { String::new() } else { before };
    let _ = std::fs::write(path, format!("{kept}{when} {message}\n"));
}

/// Something waiting for the server: the part [`wait_for`] needs of the process that
/// runs it.
trait Starting {
    fn ended(&mut self) -> bool;
}

impl Starting for Child {
    fn ended(&mut self) -> bool {
        self.try_wait().is_ok_and(|status| status.is_some())
    }
}

/// Ask `ready` until it has an answer. `watcher` is the process we started to run a
/// server, if we did.
fn wait_for<T>(
    ready: &mut dyn FnMut() -> Option<T>,
    watcher: Option<&mut dyn Starting>,
    app_open: &dyn Fn() -> bool,
    patience: (Duration, Duration),
    pause: Duration,
) -> Result<T, &'static str> {
    let (timeout, after_ours) = patience;
    let began = Instant::now();
    let mut watcher = watcher;
    let mut give_up_at = began + timeout;
    loop {
        if let Some(answer) = ready() {
            return Ok(answer);
        }
        // It ends by itself if the server fails, or if the app is opened meanwhile.
        if watcher.as_mut().is_some_and(|w| w.ended()) {
            watcher = None;
            if !app_open() {
                give_up_at = give_up_at.min(Instant::now() + after_ours);
            }
        }
        if Instant::now() >= give_up_at {
            return Err(if app_open() {
                "the T3 Code app is open, but its server is not answering"
            } else if watcher.is_some() {
                "T3 Code's server did not become ready in time. Run `t3 serve` to see why"
            } else {
                "T3 Code's server stopped while starting. Run `t3 serve` to see why"
            });
        }
        std::thread::sleep(pause);
    }
}

/// Get a server running, once T3 Code's CLI has said none is: wait for the desktop app's
/// if it is open, and otherwise start one in the background. `ready` asks the CLI again,
/// and answers once it can use the server. Only that counts as ready: a port can take
/// connections before the server has said where it is, and the file where it says so can
/// be left over from an earlier one.
pub(super) fn ensure<T>(mut ready: impl FnMut() -> Option<T>) -> Result<T, String> {
    let mut watcher = if desktop_running() {
        None
    } else {
        let child =
            process::start_watcher("--t3-server").map_err(|e| format!("could not start T3 Code's server: {e}"))?;
        Some(child)
    };
    let result = wait_for(
        &mut ready,
        watcher.as_mut().map(|w| w as &mut dyn Starting),
        &desktop_running,
        (START_TIMEOUT, SOMEONE_ELSE),
        POLL,
    );
    // A server that can't be used must not stay behind: it would keep the app from
    // opening. Ending the watcher ends its server with it.
    if result.is_err()
        && let Some(child) = watcher.as_mut()
    {
        let _ = child.kill();
        let _ = child.wait();
    }
    result.map_err(str::to_string)
}

/// `rustimal --t3-server`: run the server out of sight until it is no longer wanted.
pub fn supervise() -> i32 {
    if desktop_running() {
        return 0;
    }
    let Ok(cli) = super::cli_path() else {
        note("T3 Code's CLI was not found");
        return 1;
    };
    if let Some(stop) = stop_request() {
        let _ = std::fs::remove_file(stop);
    }
    let port = free_port(PORT);
    note(&format!("starting T3 Code's server on port {port}"));
    let mut command = Command::new(cli);
    command
        .args(["serve", "--host", "127.0.0.1", "--port", &port.to_string()])
        // PATH and friends as they are now, so the server finds the agents.
        .envs(crate::platform::winenv::fresh())
        // The server prints a pairing code, which is not for keeping.
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .creation_flags(CREATE_NO_WINDOW);
    if let Some(home) = dirs::home_dir() {
        command.current_dir(home);
    }
    let mut server = match command.spawn() {
        Ok(child) => child,
        Err(e) => {
            note(&format!("could not start it: {e}"));
            return 1;
        }
    };
    let Some(job) = Job::holding(&server) else {
        note("could not keep hold of the server's processes, so it was not left running");
        let _ = server.kill();
        return 1;
    };
    let why = loop {
        std::thread::sleep(POLL);
        if let Ok(Some(status)) = server.try_wait() {
            break format!("the server ended ({status})");
        }
        if desktop_running() {
            break "stopped, to let the T3 Code app take over".to_string();
        }
        if let Some(stop) = stop_request().filter(|s| s.exists()) {
            let _ = std::fs::remove_file(stop);
            break "stopped, as asked".to_string();
        }
    };
    // Ends the server and everything it started.
    drop(job);
    let _ = server.wait();
    note(&why);
    0
}

/// `t3 stop`: end the server rustimal started. The desktop app's own is left alone.
pub(super) fn stop() -> Result<&'static str, String> {
    let request = stop_request().ok_or("could not find rustimal's folder")?;
    if let Some(folder) = request.parent() {
        std::fs::create_dir_all(folder).map_err(|e| e.to_string())?;
    }
    std::fs::write(&request, "").map_err(|e| e.to_string())?;
    let began = Instant::now();
    while began.elapsed() < Duration::from_secs(3) {
        if !request.exists() {
            return Ok("Stopped the T3 Code server that was running in the background");
        }
        std::thread::sleep(POLL);
    }
    let _ = std::fs::remove_file(request);
    Ok("rustimal has no T3 Code server running in the background (the app's own is left alone)")
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Against the real thing, which a stand-in can get wrong: run it with the app open.
    #[test]
    #[ignore]
    fn the_open_t3_app_is_noticed() {
        let lock = desktop_lock().unwrap();
        assert!(lock.exists(), "open the T3 Code app first");
        assert!(desktop_running(), "the app holds {} but was not noticed", lock.display());
    }

    #[test]
    fn a_lock_counts_only_while_it_is_held() {
        let path = std::env::temp_dir().join(format!("rustimal-t3-lock-{}", std::process::id()));
        let _ = std::fs::remove_file(&path);
        assert!(!is_held(&path), "no file");
        std::fs::write(&path, "").unwrap();
        assert!(!is_held(&path), "left over from before");
        // As Chromium holds the app's: for writing, deleted when closed, shared for reading.
        const DELETE_ON_CLOSE: u32 = 0x0400_0000;
        const SHARE_READ: u32 = 1;
        let held = std::fs::OpenOptions::new()
            .write(true)
            .share_mode(SHARE_READ)
            .custom_flags(DELETE_ON_CLOSE)
            .open(&path)
            .unwrap();
        assert!(is_held(&path));
        drop(held);
        assert!(!path.exists() && !is_held(&path), "gone with its holder");
        // Held and shared with nobody counts too.
        let held =
            std::fs::OpenOptions::new().write(true).create(true).truncate(true).share_mode(0).open(&path).unwrap();
        assert!(is_held(&path));
        drop(held);
        std::fs::remove_file(path).unwrap();
    }

    /// A watcher that has ended, or not, from the start.
    struct Fake(bool);

    impl Starting for Fake {
        fn ended(&mut self) -> bool {
            self.0
        }
    }

    fn wait(ready_after: u32, watcher: Option<&mut dyn Starting>, app: bool) -> Result<u32, &'static str> {
        let mut asked = 0;
        let mut ready = || {
            asked += 1;
            (asked > ready_after).then_some(asked)
        };
        let patience = (Duration::from_millis(400), Duration::from_millis(120));
        wait_for(&mut ready, watcher, &|| app, patience, Duration::from_millis(5))
    }

    #[test]
    fn it_keeps_asking_until_the_server_can_be_used() {
        assert_eq!(wait(3, Some(&mut Fake(false)), false), Ok(4), "not ready at first is no failure");
        // Ours lost to someone else's start, which is a little behind.
        assert_eq!(wait(3, Some(&mut Fake(true)), false), Ok(4));
        assert_eq!(wait(3, None, true), Ok(4), "the app's own server");
    }

    #[test]
    fn it_gives_up_and_says_which_way_it_failed() {
        let never = u32::MAX;
        assert!(wait(never, Some(&mut Fake(false)), false).unwrap_err().contains("did not become ready"));
        let began = Instant::now();
        assert!(wait(never, Some(&mut Fake(true)), false).unwrap_err().contains("stopped while starting"));
        assert!(began.elapsed() < Duration::from_millis(350), "sooner once ours has ended");
        assert!(wait(never, None, true).unwrap_err().contains("app is open"));
    }
}