job-limits 0.1.0

Memory limits for child processes, and a guard that cleans up the whole process tree (same API on unix and Windows)
Documentation
# job-limits

[![Crates.io](https://img.shields.io/crates/v/job-limits.svg)](https://crates.io/crates/job-limits)
[![docs.rs](https://img.shields.io/docsrs/job-limits)](https://docs.rs/job-limits)
[![CI](https://github.com/lovelygenerator/job-limits/actions/workflows/ci.yml/badge.svg)](https://github.com/lovelygenerator/job-limits/actions/workflows/ci.yml)
[![License](https://img.shields.io/crates/l/job-limits.svg)](#license)
[![MSRV](https://img.shields.io/badge/rustc-1.88+-blue.svg)](#requirements)

English | [日本語]README.ja.md

A Rust crate that puts a memory limit on a child process, and ends the child and all its descendants when the `Guard` is dropped. It works the same way on unix and Windows.

## Requirements

- Rust 1.88 or later (edition 2024). Installing it with `rustup` gives you `cargo`, `rustfmt` and `clippy`.
- Supported OS: Linux, macOS and Windows.
- Users of the crate need no extra tools or system libraries. The dependencies are `rustix` on unix, `windows-sys` on Windows, and `tokio` only with the `tokio` feature.
- To check the crate during development, run one of these from the repository root:
  - Git Bash (unix works too): `bash check.sh`
  - By hand: `cargo fmt --check`, `cargo clippy --all-targets --all-features -- -D warnings`, `cargo test --all-features`

## Usage

```rust
use std::process::Command;

let limits = job_limits::Limits::new().process_memory(1 << 30);
let (mut child, guard) = limits.spawn(&mut Command::new("my-tool"))?;
child.wait()?;
drop(guard); // ends any grandchildren left behind
# Ok::<(), std::io::Error>(())
```

To spawn a tokio `Command`, enable the `tokio` feature and use `spawn_tokio`. Put a time limit on it yourself with `tokio::time::timeout`.

```toml
[dependencies]
job-limits = { version = "0.1", features = ["tokio"] }
```

```rust
use std::time::Duration;

let mut command = tokio::process::Command::new("my-tool");
let (mut child, guard) = job_limits::Limits::new()
    .process_memory(256 << 20)
    .spawn_tokio(&mut command)?;
if tokio::time::timeout(Duration::from_secs(5), child.wait()).await.is_err() {
    let _ = child.kill().await;
}
drop(guard); // ends any grandchildren too
```

Runnable samples are in `examples/`.

```bash
# Spawn with a 256 MiB memory limit. On unix the child sees `ulimit -v` = 262144
cargo run --example run -- sh -c 'ulimit -v'

# Spawn with a memory limit and a 5 second time limit
cargo run --example tokio_timeout --features tokio -- sleep 30
```

On Windows, pass something like `cmd /c echo hello` instead of `sh -c 'ulimit -v'` (there is no `ulimit` on Windows).

Git Bash treats arguments such as `/c` as paths and rewrites them to `C:/`, so `cmd` does not get `/c` and waits for input. Set `MSYS_NO_PATHCONV=1`, or double the slash (`//c`).

```bash
MSYS_NO_PATHCONV=1 cargo run --example run -- cmd /c echo hello
```

## How it works

| | unix | Windows |
|---|---|---|
| Memory limit | `setrlimit(RLIMIT_AS)` before the child starts | `PROCESS_MEMORY` of a Job Object |
| Cleanup | The child gets its own process group; dropping the `Guard` sends `SIGKILL` to the whole group | `KILL_ON_JOB_CLOSE` of a Job Object |

## Notes

- The limit is counted differently on each OS (address space on unix, commit charge on Windows).
- Linux enforces the limit. macOS may not enforce `RLIMIT_AS`; a failure to set it is ignored.
- On Windows, the limit is not in effect for the short time between starting the child and putting it into the Job.
- On unix, dropping a `Guard` after the child has ended and its process group has become empty can kill an unrelated group through process ID reuse. Drop the `Guard` right after `wait`ing for the child.

## About unsafe

The public API (`Limits` and `Guard`) consists only of safe functions. Callers never write `unsafe`.

The crate sets `unsafe_code = "deny"`, and only the two modules that need `unsafe` allow it with `#![allow(unsafe_code)]`. Every use has a `SAFETY:` comment giving its reason.

| Where | What uses `unsafe` | Why |
|---|---|---|
| `src/unix.rs` | `CommandExt::pre_exec` | To set the memory limit after fork and before exec. The function is `unsafe` because the closure must be async-signal-safe. The closure only makes the `setrlimit` system call; it neither allocates nor takes locks |
| `src/windows.rs` | `CreateJobObjectW`, `SetInformationJobObject`, `AssignProcessToJobObject`, `CloseHandle` | Win32 FFI calls are all `unsafe` |
| `src/windows.rs` | `Send` and `Sync` for `Guard` | A Job Object handle can be used and closed from any thread |

The invariants it keeps:

- The Windows Job handle is created by `attach`, owned only by `Guard`, and closed exactly once in `Drop`. `Guard` is created first, so the handle is not leaked when a later step fails.
- The structure passed to `SetInformationJobObject` matches the information class and has the right size.
- The child process handle is only borrowed from the caller (a live handle, right after spawn) and never closed.

On unix, `setrlimit` and `kill` go through the safe API of `rustix` (the crate does not use `libc` directly).

## License

Licensed under either of MIT or Apache-2.0, at your option.