Skip to content

Clone your own voice on your own computer: speak any text in 60+ languages and dub videos into another language in your voice. Fully local. Early version.

27.8 KB
Raw Blame
//! Engine client: spawns the Python engine and speaks contract/engine-protocol.md over stdin/stdout.

#![allow(dead_code)]

pub mod protocol;

use std::collections::VecDeque;
use std::ffi::OsString;
use std::fs::{self, File};
use std::io::{BufRead, BufReader, Write};
use std::path::{Path, PathBuf};
use std::process::{Child, ChildStdin, Command, Stdio};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::mpsc::{self, Receiver};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

use anyhow::{Context, anyhow};
use serde::Deserialize;
use serde_json::Value;

const APP_DIR: &str = "mimvox";
const STDERR_TAIL_LINES: usize = 200;

#[derive(Clone, Debug)]
pub struct EngineConfig {
    pub runtime_toml: PathBuf,
    pub engine_src: PathBuf,
    pub data_dir: PathBuf,
}

fn env_path(name: &str) -> Option<PathBuf> {
    std::env::var_os(name).filter(|v| !v.is_empty()).map(PathBuf::from)
}

/// The fixed per-user folder of the pointer file (it never moves, so the data dir can).
fn pointer_base() -> Option<PathBuf> {
    #[cfg(target_os = "windows")]
    return dirs::data_local_dir();
    #[cfg(target_os = "macos")]
    return dirs::data_dir();
    #[cfg(not(any(target_os = "windows", target_os = "macos")))]
    return dirs::config_dir();
}

fn platform_data_dir() -> Option<PathBuf> {
    #[cfg(target_os = "windows")]
    return dirs::data_local_dir();
    #[cfg(not(target_os = "windows"))]
    return dirs::data_dir();
}

#[derive(Deserialize)]
struct LocationToml {
    data_dir: String,
}

/// `MIMVOX_DATA`, else `data_dir` from the `location.toml` pointer written by setup, else the platform default.
pub fn default_data_dir() -> Option<PathBuf> {
    if let Some(p) = env_path("MIMVOX_DATA") {
        return Some(p);
    }
    let pointed = pointer_base()
        .map(|b| b.join(APP_DIR).join("location.toml"))
        .and_then(|f| fs::read_to_string(f).ok())
        .and_then(|text| toml::from_str::<LocationToml>(&text).ok())
        .map(|l| PathBuf::from(l.data_dir.trim()))
        .filter(|p| p.is_absolute());
    pointed.or_else(|| platform_data_dir().map(|d| d.join(APP_DIR)))
}

fn is_engine_src(dir: &Path) -> bool {
    dir.join("mimvox_engine").join("__init__.py").is_file()
}

fn is_resources_root(dir: &Path) -> bool {
    is_engine_src(&dir.join("engine").join("src"))
}

/// The folder that holds `engine/`, `presets/`, `tools/`, `contract/`; the layouts must match
/// `crates/desktop/Packager.toml`.
pub fn find_resources() -> Option<PathBuf> {
    if let Some(p) = env_path("MIMVOX_RESOURCES") {
        return Some(p);
    }
    let exe_dir = std::env::current_exe()
        .ok()
        .and_then(|p| p.canonicalize().ok().or(Some(p)))
        .and_then(|p| p.parent().map(Path::to_path_buf));

    let mut candidates: Vec<PathBuf> = Vec::new();
    if let Some(dir) = &exe_dir {
        for rel in ["", "../Resources", "../lib/mimvox", "resources"] {
            candidates.push(if rel.is_empty() { dir.clone() } else { dir.join(rel) });
        }
        candidates.extend(dir.ancestors().map(Path::to_path_buf));
    }
    let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
    candidates.extend(manifest.ancestors().map(Path::to_path_buf));
    candidates.into_iter().find(|c| is_resources_root(c))
}

impl EngineConfig {
    pub fn discover() -> anyhow::Result<Self> {
        Self::discover_in(None)
    }

    /// [`EngineConfig::discover`] with `data_dir` in place of the usual data directory lookup when given.
    pub fn discover_in(data_dir: Option<PathBuf>) -> anyhow::Result<Self> {
        let data_dir = match data_dir {
            Some(dir) => dir,
            None => {
                default_data_dir().ok_or_else(|| anyhow!("cannot determine the data directory; set MIMVOX_DATA"))?
            }
        };

        let runtime_toml = match env_path("MIMVOX_RUNTIME") {
            Some(p) => p,
            None => {
                let in_data = data_dir.join("runtime.toml");
                if in_data.is_file() {
                    in_data
                } else {
                    // Portable layouts: runtime.toml next to the executable.
                    let beside_exe = std::env::current_exe()
                        .ok()
                        .and_then(|p| p.parent().map(|d| d.join("runtime.toml")))
                        .filter(|p| p.is_file());
                    beside_exe.unwrap_or(in_data)
                }
            }
        };

        let engine_src = match env_path("MIMVOX_ENGINE_SRC") {
            Some(p) => p,
            None => find_resources().map(|r| r.join("engine").join("src")).ok_or_else(|| {
                anyhow!(
                    "engine sources not found (looked next to the executable, in bundle resources and in \
                     engine/src of a repo checkout); set MIMVOX_RESOURCES or MIMVOX_ENGINE_SRC"
                )
            })?,
        };

        Ok(Self { runtime_toml, engine_src, data_dir })
    }

    pub fn log_path(&self) -> PathBuf {
        self.data_dir.join("logs").join("engine.log")
    }
}

#[derive(Debug, Deserialize)]
struct RuntimeToml {
    python: RuntimePython,
}

#[derive(Debug, Deserialize)]
struct RuntimePython {
    engine: String,
}

/// Reads `[python] engine` from runtime.toml (relative paths resolve against the file's directory).
fn read_engine_python(runtime_toml: &Path) -> anyhow::Result<PathBuf> {
    let text = fs::read_to_string(runtime_toml).with_context(|| {
        format!("cannot read {} (run the setup script first, or set MIMVOX_RUNTIME)", runtime_toml.display())
    })?;
    let parsed: RuntimeToml = toml::from_str(&text).with_context(|| {
        format!("invalid runtime.toml at {}: expected [python] engine = \"...\"", runtime_toml.display())
    })?;
    let python = PathBuf::from(&parsed.python.engine);
    let python =
        if python.is_relative() { runtime_toml.parent().map(|d| d.join(&python)).unwrap_or(python) } else { python };
    if !python.is_file() {
        return Err(anyhow!(
            "engine interpreter from runtime.toml does not exist: {} (re-run the setup script)",
            python.display()
        ));
    }
    Ok(python)
}

#[derive(Debug)]
pub enum EngineMsg {
    Ready(Box<protocol::Hello>),
    Response { id: u64, result: Result<serde_json::Value, protocol::EngineError> },
    Event(protocol::Event),
    Exited { code: Option<i32>, stderr_tail: String },
}

/// Called on the client's reader thread for every message, in order. The `u64` is [`EngineClient::id`], so
/// messages from an engine that was replaced meanwhile can be told apart.
pub type EngineSink = Arc<dyn Fn(u64, EngineMsg) + Send + Sync>;

type StderrTail = Arc<Mutex<VecDeque<String>>>;

fn tail_string(tail: &StderrTail) -> String {
    let t = tail.lock().unwrap_or_else(|e| e.into_inner());
    t.iter().cloned().collect::<Vec<_>>().join("\n")
}

fn push_tail(tail: &StderrTail, line: String) {
    let mut t = tail.lock().unwrap_or_else(|e| e.into_inner());
    if t.len() >= STDERR_TAIL_LINES {
        t.pop_front();
    }
    t.push_back(line);
}

/// The installer and the uninstaller wait while it exists (scripts/build/inno.py, APP_MUTEX).
#[cfg(windows)]
pub const APP_MUTEX: &str = "Local\\Mimvox-running";

/// Holds [`APP_MUTEX`] until the process exits: the app and mimvox-server both keep installed files in use.
#[cfg(windows)]
pub fn hold_app_mutex() {
    use windows_sys::Win32::System::Threading::CreateMutexW;
    let name: Vec<u16> = APP_MUTEX.encode_utf16().chain(std::iter::once(0)).collect();
    // SAFETY: a NUL-terminated name; the handle is never closed, so the mutex lives as long as the process.
    let _ = unsafe { CreateMutexW(std::ptr::null(), 0, name.as_ptr()) };
}

/// Locked while an engine runs on a data dir, so the app and mimvox-server never run two engines on it.
pub const LOCK_FILE: &str = "engine.lock";

fn lock_data_dir(data_dir: &Path) -> anyhow::Result<Option<File>> {
    let Ok(file) = fs::OpenOptions::new().create(true).write(true).truncate(false).open(data_dir.join(LOCK_FILE))
    else {
        return Ok(None);
    };
    match file.try_lock() {
        Ok(()) => Ok(Some(file)),
        Err(fs::TryLockError::WouldBlock) => Err(anyhow!(
            "another Mimvox engine (the app or mimvox-server) is already running on {}",
            data_dir.display()
        )),
        // A filesystem without locks: run unguarded rather than not at all.
        Err(fs::TryLockError::Error(_)) => Ok(None),
    }
}

#[derive(Clone, Copy, Debug, Default)]
pub struct SpawnOptions {
    /// Unix: a process group of its own, so a terminal's Ctrl+C reaches only the client, which then shuts it down.
    pub own_process_group: bool,
}

const SHUTDOWN_GRACE: Duration = Duration::from_millis(2500);
/// How long the exit report waits for the last stderr lines after the process is gone.
const STDERR_FLUSH: Duration = Duration::from_millis(300);

pub struct EngineClient {
    id: u64,
    child: Arc<Mutex<Child>>,
    stdin: Mutex<Option<ChildStdin>>,
    sink: EngineSink,
    /// Signalled by the stdout reader once the process has exited (after stdout closed).
    exited: Mutex<Receiver<()>>,
    next_id: AtomicU64,
    stderr_tail: StderrTail,
    log_path: PathBuf,
    shut_down: AtomicBool,
    _lock: Option<File>,
    #[cfg(windows)]
    _job: Option<std::os::windows::io::OwnedHandle>,
}

impl EngineClient {
    pub fn spawn(cfg: &EngineConfig, sink: EngineSink) -> anyhow::Result<Self> {
        Self::spawn_with(cfg, sink, SpawnOptions::default())
    }

    pub fn spawn_with(cfg: &EngineConfig, sink: EngineSink, opts: SpawnOptions) -> anyhow::Result<Self> {
        static NEXT_CLIENT: AtomicU64 = AtomicU64::new(1);
        let client_id = NEXT_CLIENT.fetch_add(1, Ordering::Relaxed);
        let python = read_engine_python(&cfg.runtime_toml)?;
        if !is_engine_src(&cfg.engine_src) {
            return Err(anyhow!(
                "engine sources not found at {} (expected mimvox_engine/__init__.py inside)",
                cfg.engine_src.display()
            ));
        }
        fs::create_dir_all(&cfg.data_dir)
            .with_context(|| format!("cannot create data dir {}", cfg.data_dir.display()))?;
        let lock = lock_data_dir(&cfg.data_dir)?;

        let mut pythonpath = OsString::from(&cfg.engine_src);
        if let Some(existing) = std::env::var_os("PYTHONPATH").filter(|v| !v.is_empty()) {
            let joined =
                std::env::join_paths(std::env::split_paths(&pythonpath).chain(std::env::split_paths(&existing)))
                    .context("cannot build PYTHONPATH")?;
            pythonpath = joined;
        }

        let mut cmd = Command::new(&python);
        if std::env::var_os("MIMVOX_PRESETS").is_none_or(|v| v.is_empty()) {
            let presets = cfg.engine_src.parent().and_then(Path::parent).map(|r| r.join("presets"));
            if let Some(dir) = presets.filter(|d| d.is_dir()) {
                cmd.env("MIMVOX_PRESETS", dir);
            }
        }
        cmd.arg("-m")
            .arg("mimvox_engine")
            .arg("serve")
            .arg("--runtime")
            .arg(&cfg.runtime_toml)
            .arg("--data-dir")
            .arg(&cfg.data_dir)
            .env("PYTHONPATH", pythonpath)
            // Bytecode caches in the data folder: an installed app's folder may be read-only, and its uninstaller should
            // find only the files it installed.
            .env("PYTHONPYCACHEPREFIX", cfg.data_dir.join("cache").join("pycache"))
            .env("PYTHONUNBUFFERED", "1")
            .env("PYTHONIOENCODING", "utf-8")
            .env("PYTHONUTF8", "1")
            .stdin(Stdio::piped())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        #[cfg(windows)]
        {
            use std::os::windows::process::CommandExt;
            const CREATE_NO_WINDOW: u32 = 0x0800_0000;
            cmd.creation_flags(CREATE_NO_WINDOW);
        }
        #[cfg(unix)]
        if opts.own_process_group {
            use std::os::unix::process::CommandExt;
            cmd.process_group(0);
        }
        #[cfg(not(unix))]
        let _ = opts;
        // std locks with flock on Unix, which belongs to the open file: the engine's inherited copy keeps the data dir
        // locked until the engine itself exits, even when the client is killed first.
        #[cfg(unix)]
        if let Some(fd) = lock.as_ref().map(std::os::fd::AsRawFd::as_raw_fd) {
            use std::os::unix::process::CommandExt;
            // SAFETY: fcntl is async-signal-safe and only changes the flags of the child's copy of the descriptor.
            unsafe {
                cmd.pre_exec(move || {
                    let flags = libc::fcntl(fd, libc::F_GETFD);
                    if flags < 0 || libc::fcntl(fd, libc::F_SETFD, flags & !libc::FD_CLOEXEC) < 0 {
                        return Err(std::io::Error::last_os_error());
                    }
                    Ok(())
                });
            }
        }

        let mut child = cmd.spawn().with_context(|| format!("cannot start the engine with {}", python.display()))?;
        #[cfg(windows)]
        let job = kill_on_close_job(&child);
        let stdin = child.stdin.take().ok_or_else(|| anyhow!("engine stdin unavailable"))?;
        let stdout = child.stdout.take().ok_or_else(|| anyhow!("engine stdout unavailable"))?;
        let stderr = child.stderr.take().ok_or_else(|| anyhow!("engine stderr unavailable"))?;

        let child = Arc::new(Mutex::new(child));
        let stderr_tail: StderrTail = Arc::new(Mutex::new(VecDeque::new()));
        let log_path = cfg.log_path();
        let (stderr_done_tx, stderr_done_rx) = mpsc::channel::<()>();
        let (exited_tx, exited_rx) = mpsc::channel::<()>();

        {
            let tail = stderr_tail.clone();
            let log_path = log_path.clone();
            thread::Builder::new()
                .name("engine-stderr".into())
                .spawn(move || {
                    let mut log = log_path
                        .parent()
                        .and_then(|d| fs::create_dir_all(d).ok())
                        .and_then(|_| File::create(&log_path).ok());
                    for line in BufReader::new(stderr).split(b'\n') {
                        let Ok(line) = line else { break };
                        let line = String::from_utf8_lossy(&line).trim_end_matches(['\r', '\n']).to_string();
                        if let Some(f) = log.as_mut() {
                            let _ = writeln!(f, "{line}");
                        }
                        push_tail(&tail, line);
                    }
                    let _ = stderr_done_tx.send(());
                })
                .context("cannot start the stderr reader")?;
        }

        {
            let sink = sink.clone();
            let child = child.clone();
            let tail = stderr_tail.clone();
            thread::Builder::new()
                .name("engine-stdout".into())
                .spawn(move || {
                    for line in BufReader::new(stdout).split(b'\n') {
                        let Ok(line) = line else { break };
                        let line = String::from_utf8_lossy(&line);
                        let line = line.trim();
                        if line.is_empty() {
                            continue;
                        }
                        match parse_line(line) {
                            Ok(Some(msg)) => sink(client_id, msg),
                            Ok(None) => {}
                            // Not protocol traffic (a library printed to stdout): keep it for diagnostics.
                            Err(()) => push_tail(&tail, format!("[stdout] {line}")),
                        }
                    }
                    // EOF: the process is ending. Wait for it (stdout closes at the very end of the interpreter's
                    // shutdown), then give stderr a moment to deliver its last lines.
                    let code = child.lock().unwrap_or_else(|e| e.into_inner()).wait().ok().and_then(|s| s.code());
                    let _ = exited_tx.send(());
                    let _ = stderr_done_rx.recv_timeout(STDERR_FLUSH);
                    sink(client_id, EngineMsg::Exited { code, stderr_tail: tail_string(&tail) });
                })
                .context("cannot start the stdout reader")?;
        }

        Ok(Self {
            id: client_id,
            child,
            stdin: Mutex::new(Some(stdin)),
            sink,
            exited: Mutex::new(exited_rx),
            next_id: AtomicU64::new(1),
            stderr_tail,
            log_path,
            shut_down: AtomicBool::new(false),
            _lock: lock,
            #[cfg(windows)]
            _job: job,
        })
    }

    /// Unique per spawned process (the first argument of every [`EngineSink`] call).
    pub fn id(&self) -> u64 {
        self.id
    }

    /// Returns the request id at once; the answer arrives as `EngineMsg::Response` (an `internal` error when stdin
    /// cannot be written).
    pub fn request(&self, method: &str, params: serde_json::Value) -> u64 {
        let id = self.reserve_id();
        self.request_with_id(id, method, params);
        id
    }

    /// An id for [`EngineClient::request_with_id`], so a caller can expect its answer before the request is sent.
    pub fn reserve_id(&self) -> u64 {
        self.next_id.fetch_add(1, Ordering::Relaxed)
    }

    pub fn request_with_id(&self, id: u64, method: &str, params: serde_json::Value) {
        let line = serde_json::json!({ "id": id.to_string(), "method": method, "params": params }).to_string();
        if let Err(e) = self.write_line(&line) {
            (self.sink)(
                self.id,
                EngineMsg::Response {
                    id,
                    result: Err(protocol::EngineError::new("internal", format!("engine is not running: {e}"))),
                },
            );
        }
    }

    pub fn send(&self, req: protocol::Request) -> u64 {
        self.request(req.0, req.1)
    }

    fn write_line(&self, line: &str) -> std::io::Result<()> {
        let mut guard = self.stdin.lock().unwrap_or_else(|e| e.into_inner());
        let stdin =
            guard.as_mut().ok_or_else(|| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "stdin closed"))?;
        stdin.write_all(line.as_bytes())?;
        stdin.write_all(b"\n")?;
        stdin.flush()
    }

    pub fn stderr_tail(&self) -> String {
        tail_string(&self.stderr_tail)
    }

    /// Truncated at every start.
    pub fn log_path(&self) -> &Path {
        &self.log_path
    }

    /// Asks the engine to exit without waiting for it, for the UI thread. [`EngineClient::shutdown`] (or dropping the
    /// client) finishes it.
    pub fn request_shutdown(&self) {
        let (method, params) = protocol::shutdown();
        let line = serde_json::json!({ "id": "0", "method": method, "params": params }).to_string();
        let _ = self.write_line(&line);
        self.stdin.lock().unwrap_or_else(|e| e.into_inner()).take();
    }

    /// Blocks up to [`SHUTDOWN_GRACE`] for the engine to exit, then kills it.
    pub fn shutdown(&self) {
        if self.shut_down.swap(true, Ordering::SeqCst) {
            return;
        }
        // Closing stdin also makes the engine exit (a no-op after `request_shutdown`).
        self.request_shutdown();

        let exited = self.exited.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(SHUTDOWN_GRACE);
        if exited.is_ok() {
            return;
        }
        // Still running. The reader holds the child only once stdout has closed (the process is then already at
        // its very end), so never block on it here.
        match self.child.try_lock() {
            Ok(mut child) => {
                let _ = child.kill();
                let _ = child.wait();
            }
            // The engine holds the data dir lock until it is gone, so a client started next must not race its end.
            Err(_) => {
                let _ = self.exited.lock().unwrap_or_else(|e| e.into_inner()).recv_timeout(STDERR_FLUSH);
            }
        }
    }
}

/// Windows file locks end with the process that took them, not with the engine: a job that kills the engine when the
/// client's handle closes (the client exiting, even killed) keeps "one engine per data dir".
#[cfg(windows)]
fn kill_on_close_job(child: &Child) -> Option<std::os::windows::io::OwnedHandle> {
    use std::os::windows::io::{AsRawHandle, FromRawHandle, OwnedHandle};
    use windows_sys::Win32::System::JobObjects::{
        AssignProcessToJobObject, CreateJobObjectW, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
        JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JobObjectExtendedLimitInformation, SetInformationJobObject,
    };
    // SAFETY: plain Win32 calls on a job handle this function owns (closed by OwnedHandle) and on the child's handle,
    // which outlives the call.
    unsafe {
        let raw = CreateJobObjectW(std::ptr::null(), std::ptr::null());
        if raw.is_null() {
            return None;
        }
        let job = OwnedHandle::from_raw_handle(raw);
        let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
        info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
        let set = SetInformationJobObject(
            raw,
            JobObjectExtendedLimitInformation,
            (&raw const info).cast(),
            size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as u32,
        );
        (set != 0 && AssignProcessToJobObject(raw, child.as_raw_handle()) != 0).then_some(job)
    }
}

impl Drop for EngineClient {
    fn drop(&mut self) {
        self.shutdown();
    }
}

/// Parses one stdout line. `Err(())` = not protocol traffic; `Ok(None)` = protocol line nobody waits for.
fn parse_line(line: &str) -> Result<Option<EngineMsg>, ()> {
    let v: Value = serde_json::from_str(line).map_err(|_| ())?;
    let obj = v.as_object().ok_or(())?;

    if let Some(name) = obj.get("event").and_then(Value::as_str) {
        let data = obj.get("data").cloned().unwrap_or(Value::Null);
        if name == "ready" {
            let mut hello: protocol::Hello = serde_json::from_value(data.clone()).unwrap_or_default();
            hello.raw = data;
            return Ok(Some(EngineMsg::Ready(Box::new(hello))));
        }
        return Ok(Some(EngineMsg::Event(protocol::Event {
            event: name.to_string(),
            job: obj.get("job").and_then(Value::as_str).map(str::to_string),
            data,
        })));
    }

    let id = match obj.get("id").ok_or(())? {
        Value::String(s) => s.parse::<u64>().map_err(|_| ())?,
        Value::Number(n) => n.as_u64().ok_or(())?,
        _ => return Err(()),
    };
    if id == 0 {
        // Answer to the internal shutdown request.
        return Ok(None);
    }
    let result = if let Some(err) = obj.get("error").filter(|e| !e.is_null()) {
        Err(serde_json::from_value(err.clone())
            .unwrap_or_else(|_| protocol::EngineError::new("internal", format!("malformed error from engine: {err}"))))
    } else {
        Ok(obj.get("result").cloned().unwrap_or(Value::Null))
    };
    Ok(Some(EngineMsg::Response { id, result }))
}

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

    #[test]
    fn one_lock_per_data_dir() {
        let dir = std::env::temp_dir().join(format!("mimvox-lock-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let first = lock_data_dir(&dir).unwrap();
        assert!(first.is_some());
        let second = lock_data_dir(&dir).unwrap_err().to_string();
        assert!(second.contains("already running"), "{second}");
        drop(first);
        // A child that a parallel test forks keeps a copy of the descriptor, and so the lock, until it execs.
        wait_for("the lock to be free", || lock_data_dir(&dir).is_ok_and(|l| l.is_some()));
        fs::remove_dir_all(&dir).unwrap();
    }

    const HOLDER_ENV: &str = "MIMVOX_TEST_LOCK_HOLDER";
    const HOLDER_TEST: &str = "tests::the_engine_keeps_its_data_dir_after_its_client_is_killed";
    /// Outlives its stdin until `release` appears in the data dir.
    const LINGERING_ENGINE: &str = r#"import os, pathlib, sys, time
data = pathlib.Path(sys.argv[sys.argv.index("--data-dir") + 1])
(data / "started").write_text(str(os.getpid()))
sys.stdin.read()
while not (data / "release").exists():
    time.sleep(0.05)
"#;

    fn python() -> PathBuf {
        let path = std::env::var_os("PATH").unwrap_or_default();
        std::env::split_paths(&path)
            .flat_map(|d| ["python3", "python", "python.exe"].map(|n| d.join(n)))
            // The first one that starts: on Windows PATH can list a Store alias that does not.
            .filter(|p| p.is_file())
            .find(|p| Command::new(p).arg("--version").output().is_ok_and(|o| o.status.success()))
            .expect("python3 on PATH")
    }

    fn lingering_engine(base: &Path) -> EngineConfig {
        let src = base.join("src");
        fs::create_dir_all(src.join("mimvox_engine")).unwrap();
        fs::write(src.join("mimvox_engine").join("__init__.py"), "").unwrap();
        fs::write(src.join("mimvox_engine").join("__main__.py"), LINGERING_ENGINE).unwrap();
        let python = python().display().to_string().replace('\\', "/");
        fs::write(base.join("runtime.toml"), format!("[python]\nengine = \"{python}\"\n")).unwrap();
        EngineConfig { runtime_toml: base.join("runtime.toml"), engine_src: src, data_dir: base.join("data") }
    }

    fn wait_for(what: &str, mut done: impl FnMut() -> bool) {
        let deadline = std::time::Instant::now() + Duration::from_secs(20);
        while !done() {
            assert!(std::time::Instant::now() < deadline, "timed out waiting for {what}");
            thread::sleep(Duration::from_millis(50));
        }
    }

    #[test]
    fn the_engine_keeps_its_data_dir_after_its_client_is_killed() {
        if let Some(base) = std::env::var_os(HOLDER_ENV) {
            let cfg = lingering_engine(Path::new(&base));
            let _client =
                EngineClient::spawn_with(&cfg, Arc::new(|_, _| {}), SpawnOptions { own_process_group: true }).unwrap();
            loop {
                thread::sleep(Duration::from_secs(60));
            }
        }
        let base = std::env::temp_dir().join(format!("mimvox-lock-engine-{}", std::process::id()));
        let cfg = lingering_engine(&base);
        let mut holder = Command::new(std::env::current_exe().unwrap())
            .args(["--exact", HOLDER_TEST, "--nocapture"])
            .env(HOLDER_ENV, &base)
            .stdout(Stdio::null())
            .spawn()
            .unwrap();
        let started = cfg.data_dir.join("started");
        wait_for("the engine to start", || fs::read_to_string(&started).is_ok_and(|pid| !pid.is_empty()));
        #[cfg(windows)]
        let engine = {
            use std::os::windows::io::{FromRawHandle, OwnedHandle};
            use windows_sys::Win32::System::Threading::{OpenProcess, PROCESS_SYNCHRONIZE};
            let pid: u32 = fs::read_to_string(&started).unwrap().trim().parse().unwrap();
            // SAFETY: a handle this test owns from here on.
            unsafe { OwnedHandle::from_raw_handle(OpenProcess(PROCESS_SYNCHRONIZE, 0, pid)) }
        };
        holder.kill().unwrap();
        holder.wait().unwrap();

        #[cfg(unix)]
        {
            let held = lock_data_dir(&cfg.data_dir).err().map(|e| e.to_string()).unwrap_or_default();
            fs::write(cfg.data_dir.join("release"), "").unwrap();
            assert!(held.contains("already running"), "the lock ended with the client while its engine runs");
        }
        #[cfg(windows)]
        {
            use std::os::windows::io::AsRawHandle;
            use windows_sys::Win32::Foundation::WAIT_OBJECT_0;
            use windows_sys::Win32::System::Threading::WaitForSingleObject;
            // SAFETY: a live process handle.
            let ended = unsafe { WaitForSingleObject(engine.as_raw_handle(), 20_000) };
            fs::write(cfg.data_dir.join("release"), "").unwrap();
            assert_eq!(ended, WAIT_OBJECT_0, "the engine outlived its killed client");
        }
        wait_for("the lock to be free", || lock_data_dir(&cfg.data_dir).is_ok_and(|l| l.is_some()));
        let _ = fs::remove_dir_all(&base);
    }
}