Lutra/crates/proc/src/lib.rs
danny ebbc89832c F3: suspended Phpactor start, ConPTY shell in a job, cancel superseded completions, syntax proptest
- lutra_proc::spawn_suspended: CREATE_SUSPENDED, join the kill-on-close
  job, resume via a Tool Help thread snapshot. Opt-in for long-lived
  children (Phpactor); git, php -l and the probe keep spawn because the
  snapshot costs ~60 ms per start.
- lutra_proc::adopt + Guard (Windows): the terminal's ConPTY shell joins a
  job, so processes it started end with the tab or with Lutra.
- lsp.completion cancels the previous pending completion on the same
  server ($/cancelRequest); the cancelled command resolves empty.
- Syntax proptests compare leaf kinds, outline and folding instead of the
  S-expression (tree-sitter-php 0.25.1 keeps a union_type wrapper after
  an undo); Malte's seed added.
- docs/development.md: data dirs, target dir inside the repo, parallel
  builds, deleting ui/node_modules.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:28:54 +01:00

251 lines
8.5 KiB
Rust

//! Child processes that die with Lutra (layer L0).
//!
//! [`spawn`] starts a [`std::process::Command`] inside a group that the
//! operating system tears down when Lutra's process ends, even when Lutra
//! is killed hard, and returns a [`Child`] whose [`Child::kill`] and
//! [`Drop`] take the whole group (the child and everything it started).
//! Phpactor uses it now; git, `php -l` and other tools use it next.
//!
//! - **Windows:** every child gets its own job object with
//! `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`. Lutra holds the only handle, so
//! the job closes, and kills its processes, when the [`Child`] is dropped
//! or when Lutra's process ends in any way (the kernel closes its
//! handles). Jobs nest (Windows 8 and later), so this works when Lutra
//! itself runs inside a job (a terminal, `cargo`, a CI runner).
//! Processes the child starts are in the job too.
//! - **Unix:** the child leads a new process group. A watchdog
//! (`/bin/sh`, in its own process group) blocks on a pipe whose write end
//! only Lutra holds; when the pipe closes, because the [`Child`] is
//! dropped or killed, because Lutra quits, or because Lutra is killed
//! with `SIGKILL`, it sends `SIGKILL` to the child's group. What a
//! `SIGKILL` of Lutra can still leave behind: processes that left the
//! group themselves (`setsid`, `setpgid`, i.e. daemons), and the child if
//! Lutra dies in the microseconds between starting it and starting its
//! watchdog. If the watchdog itself is killed, the group is only killed
//! by an explicit [`Child::kill`] or drop, which then signal the direct
//! child only.
//!
//! A child started by [`spawn`] runs before it is put into its job (Windows)
//! or before its watchdog exists (Unix), so a grandchild it starts in that
//! window (microseconds) can escape. Short-lived tools (git, `php -l`, the
//! PHP probe) accept that: they start their own children (git hooks) much
//! later, when they are in the job already. [`spawn_suspended`] closes the
//! window on Windows for long-lived children (Phpactor) at the cost of a
//! system-wide thread snapshot (about 60 ms per start).
//!
//! [`adopt`] (Windows) puts a process started by someone else, the
//! integrated terminal's ConPTY shell, into a kill-on-close job and returns
//! a [`Guard`] that holds it.
use std::io;
use std::ops::{Deref, DerefMut};
use std::process::{Command, ExitStatus};
#[cfg(unix)]
mod unix;
#[cfg(windows)]
mod windows;
#[cfg(unix)]
use unix::Group;
#[cfg(windows)]
use windows::Group;
/// The group a child runs in on platforms without job objects or process
/// groups: nothing beyond the child itself.
#[cfg(not(any(unix, windows)))]
struct Group;
#[cfg(not(any(unix, windows)))]
impl Group {
/// Nothing to set up.
fn prepare(_command: &mut Command) {}
/// Nothing to attach.
///
/// # Errors
/// Never.
fn attach(_child: &std::process::Child) -> io::Result<Self> {
Ok(Self)
}
/// Nothing to kill beyond the child, which [`Child::kill`] handles.
fn kill(&mut self) {}
}
/// A child process in its own kill-on-close group.
///
/// It dereferences to [`std::process::Child`] for the pipes, `id`,
/// `try_wait` and `wait`. [`Child::kill`] replaces the standard `kill` and
/// takes the whole group. Dropping it kills the group and reaps the child,
/// so a [`Child`] must be kept for as long as the process should run.
pub struct Child {
/// The process itself.
inner: std::process::Child,
/// Its job object (Windows) or watchdog (Unix).
group: Group,
}
/// Starts `command` in a new kill-on-close group (see the crate docs).
///
/// Everything else about `command` (arguments, environment, working
/// directory, stdio, Windows creation flags) is used as given.
///
/// # Errors
/// The error of [`Command::spawn`], or the error of setting up the group
/// (Windows: creating the job or assigning the process to it; Unix:
/// starting the watchdog). When the group cannot be set up, the child that
/// was already started is killed and reaped before the error is returned,
/// so it never runs unguarded.
pub fn spawn(command: Command) -> io::Result<Child> {
spawn_with(command, Group::prepare, Group::attach)
}
/// Like [`spawn`], but on Windows the child is created suspended and resumed
/// only once it is in its job, so not even its first instruction runs
/// outside it. Meant for long-lived children: finding the child's primary
/// thread to resume it takes a snapshot of every thread on the machine
/// (about 60 ms). On other platforms it is [`spawn`].
///
/// On Windows the creation flags of `command` are replaced by
/// `CREATE_SUSPENDED | CREATE_NO_WINDOW`.
///
/// # Errors
/// The errors of [`spawn`], and on Windows the error of resuming the child;
/// the child is killed and reaped before an error is returned.
pub fn spawn_suspended(command: Command) -> io::Result<Child> {
#[cfg(windows)]
{
spawn_with(command, Group::prepare_suspended, Group::attach_suspended)
}
#[cfg(not(windows))]
{
spawn(command)
}
}
/// Starts `command` after `prepare` and puts it into the group `attach`
/// creates; kills and reaps the child when `attach` fails.
///
/// # Errors
/// The error of [`Command::spawn`] or of `attach`.
fn spawn_with(
mut command: Command,
prepare: fn(&mut Command),
attach: fn(&std::process::Child) -> io::Result<Group>,
) -> io::Result<Child> {
prepare(&mut command);
let mut inner = command.spawn()?;
match attach(&inner) {
Ok(group) => Ok(Child { inner, group }),
Err(error) => {
let _ = inner.kill();
let _ = inner.wait();
Err(error)
}
}
}
/// A kill-on-close job for a process Lutra did not start through [`spawn`]
/// (Windows only, see [`adopt`]). Dropping it kills the process and
/// everything it started.
#[cfg(windows)]
pub struct Guard {
/// The job object.
group: Group,
}
/// Puts the process behind `process` into a new kill-on-close job, so it
/// and everything it starts from now on die with Lutra or with the returned
/// [`Guard`]. Processes it started before are not adopted.
///
/// `process` needs `PROCESS_SET_QUOTA | PROCESS_TERMINATE` access (a handle
/// from `CreateProcess` has all access) and stays owned by the caller.
///
/// # Errors
/// The OS error of creating the job or assigning the process to it.
#[cfg(windows)]
pub fn adopt(process: std::os::windows::io::RawHandle) -> io::Result<Guard> {
Group::adopt(process).map(|group| Guard { group })
}
#[cfg(windows)]
impl Guard {
/// Terminates every process in the job.
pub fn kill(&mut self) {
self.group.kill();
}
}
#[cfg(windows)]
impl std::fmt::Debug for Guard {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Guard").finish_non_exhaustive()
}
}
#[cfg(windows)]
impl Drop for Guard {
/// Kills the job's processes; closing the job handle right after would
/// do the same.
fn drop(&mut self) {
self.group.kill();
}
}
impl Child {
/// Kills the child and every process in its group, without waiting for
/// the child; call [`std::process::Child::wait`] to reap it.
///
/// Killing a child that has exited already is not an error.
///
/// # Errors
/// The error of killing the direct child, as
/// [`std::process::Child::kill`] reports it. Failing to reach the rest
/// of the group is not reported: the job (Windows) or watchdog (Unix)
/// is the only handle on it, and it is consumed either way.
pub fn kill(&mut self) -> io::Result<()> {
self.group.kill();
self.inner.kill()
}
/// Kills the group (see [`Child::kill`]) and waits for the child.
///
/// # Errors
/// The error of [`std::process::Child::wait`].
pub fn kill_and_wait(&mut self) -> io::Result<ExitStatus> {
let _ = self.kill();
self.inner.wait()
}
}
impl Deref for Child {
type Target = std::process::Child;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for Child {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl std::fmt::Debug for Child {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Child")
.field("id", &self.inner.id())
.finish_non_exhaustive()
}
}
impl Drop for Child {
/// Kills the group and reaps the child. Errors are ignored on purpose:
/// the process may have exited already, and a destructor has no one to
/// report to.
fn drop(&mut self) {
let _ = self.kill_and_wait();
}
}