1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
// On docs.rs (which builds with `--cfg docsrs`, see `[package.metadata.docs.rs]`)
// derive the "Available on crate feature `X`" badges from the existing `#[cfg]`
// gates. `doc_cfg` (which absorbed `doc_auto_cfg` in 1.92) is nightly-only, so
// it is gated behind `docsrs` — stable/CI `cargo doc` ignores it.
//! `processkit` — child-process management for Rust.
//!
//! Two layers:
//!
//! - **[`ProcessGroup`]** — a kill-on-drop container for a process *tree*. Every
//! child spawned into the group, and everything those children spawn, dies
//! with the group, so an exiting or panicking owner never leaks subprocesses.
//! Containment is a Windows [Job Object], a Linux [cgroup v2] (with a POSIX
//! process-group fallback), a POSIX process group on macOS/BSD, or nothing on
//! other targets — observable via [`Mechanism`]. The whole tree can be
//! signalled (`ProcessGroup::signal`, see `Signal`), paused/resumed
//! (`ProcessGroup::suspend` / `ProcessGroup::resume`), and inspected
//! (`ProcessGroup::members`); [`wait_any`] races several running processes
//! and reports the first to exit.
//! - **runner** — async run-and-capture built on the group. Describe a run with
//! [`Command`], then drive it to completion ([`Command::output_string`],
//! [`Command::run`], …) or [`start`](Command::start) it for streaming and
//! interactive I/O. The [`ProcessRunner`] trait runs commands to completion
//! and is the mock seam (see [`ScriptedRunner`]). A
//! [`Supervisor`] keeps a command *alive* — restarting it per policy with
//! backoff — where [`Command::retry`] merely replays one run to success.
//! Readiness probes ([`RunningProcess::wait_for_line`] /
//! [`wait_for_port`](RunningProcess::wait_for_port) /
//! [`wait_for`](RunningProcess::wait_for)) wait until a started child is
//! actually *ready* instead of sleeping. A [`Pipeline`]
//! ([`Command::pipe`]) chains commands stdout→stdin without a shell — one
//! shared group, pipefail outcome. Spawn-time sandboxing knobs:
//! [`Command::inherit_env`] (env allow-list), [`Command::uid`] /
//! [`Command::gid`] (Unix privilege drop), [`Command::setsid`],
//! [`Command::create_no_window`].
//!
//! Async throughout (tokio). Errors are the structured [`Error`]; a non-zero
//! exit is reported in [`ProcessResult`], not raised, until you call
//! [`ProcessResult::ensure_success`].
//!
//! Beyond this page, the repository ships a narrative [guide set] — a
//! task-oriented [cookbook] ("I want to …" → snippet), a deep guide per
//! capability, and every per-platform caveat collected in one place.
//!
//! [guide set]: https://github.com/ZelAnton/ProcessKit-rs/tree/main/docs#readme
//! [cookbook]: https://github.com/ZelAnton/ProcessKit-rs/blob/main/docs/cookbook.md
//!
//! **Run vocabulary** — one verb, one meaning, at every layer ([`Command`],
//! [`ProcessRunner`]/[`ProcessRunnerExt`], [`CliClient`]):
//!
//! - **`run`** — require a zero exit and return stdout as a `String`, trailing
//! whitespace trimmed (`trim_end`: the final newline is noise, but leading
//! whitespace can be significant). **`run_unit`** — the same, discarding the
//! output.
//! - **`output`** — return the full [`ProcessResult`]; a non-zero exit is
//! *not* an error here. (`Command` splits the verb by payload:
//! `output_string` / `output_bytes`.)
//! - **`exit_code`** — the exit code, with a missing code surfaced as an
//! error. (On a [`ProcessResult`], [`code`](ProcessResult::code) is the
//! plain `Option<i32>` accessor — `None` for a timeout/signal kill, never a
//! `-1` sentinel.)
//! - **`probe`** — run a predicate and read its exit code as a `bool`: `0` →
//! `true`, `1` → `false`, anything else is an error (`git diff --quiet`, …).
//!
//! ```no_run
//! # async fn demo() -> processkit::Result<()> {
//! use processkit::Command;
//!
//! // Capture output; a non-zero exit does not error on its own.
//! let result = Command::new("git").args(["rev-parse", "HEAD"]).output_string().await?;
//! println!("HEAD is {}", result.stdout().trim());
//!
//! // Or require success and get trimmed stdout directly.
//! let version = Command::new("cargo").arg("--version").run().await?;
//! # let _ = version;
//! # Ok(())
//! # }
//! ```
//!
//! # Recipes
//!
//! ```no_run
//! # use std::time::Duration;
//! # async fn demo() -> processkit::Result<()> {
//! use processkit::{Command, Error};
//!
//! // Exit code *is* the answer (0 = yes, 1 = no; anything else errors):
//! let clean = Command::new("git").args(["diff", "--quiet"]).probe().await?;
//!
//! // Retry a transient failure (replays the command; classifier inspects the error):
//! let fetched = Command::new("git")
//! .args(["fetch", "--quiet"])
//! .timeout(Duration::from_secs(10))
//! .retry(3, Duration::from_millis(200), |e| {
//! matches!(e, Error::Timeout { .. })
//! || e.diagnostic().is_some_and(|m| m.contains("Could not resolve host"))
//! })
//! .run()
//! .await;
//!
//! // A friendly failure message — stderr, falling back to stdout (git writes
//! // `CONFLICT …` / `nothing to commit` there):
//! if let Err(e) = Command::new("git").args(["merge", "topic"]).run().await {
//! eprintln!("merge failed: {}", e.diagnostic().unwrap_or("(no output)"));
//! }
//!
//! // Set an env var once for every command (typed CLI wrapper):
//! use processkit::CliClient;
//! let git = CliClient::new("git").default_env("GIT_TERMINAL_PROMPT", "0");
//! let _ = git.run(git.command(["status", "--porcelain"])).await?;
//! # let _ = (clean, fetched);
//! # Ok(())
//! # }
//! ```
//!
//! # Features
//!
//! Every flag is *additive* and gates visibility only — the kill-on-drop tree
//! guarantee is unconditional in every configuration.
//!
//! - **`stats`** *(default)* — resource measurement: `ProcessGroupStats`,
//! `ProcessGroup::stats` (plus the `sample_stats` time-series sampler), the
//! per-process `RunningProcess::cpu_time`/`peak_memory_bytes` diagnostics,
//! and the `RunningProcess::profile` run summary. Disable
//! (`default-features = false`) to compile the accounting code out.
//! - **`process-control`** *(default)* — tree control beyond contain+kill:
//! `Signal` and `ProcessGroup::{signal, suspend, resume, members, adopt}`.
//! - **`limits`** — whole-tree resource caps: `ResourceLimits`, the
//! `memory_max`/`max_processes`/`cpu_quota` builders on
//! [`ProcessGroupOptions`], and `Error::ResourceLimit`. Implies `stats`.
//! - **`mock`** — the `mockall`-generated `MockRunner` for consumers' tests.
//! - **`tracing`** — `tracing` events on the `processkit` target: spawn and
//! exit (program/pid/mechanism), timeout and cancellation firing, group
//! terminate/shutdown, retry attempts, supervisor restarts and storm
//! pauses, and teardown anomalies (stdin-writer failures, pump overruns).
//! Never logs argv or environment values.
//! - **`cancellation`** — first-class run cancellation:
//! `Command::cancel_on` ties a run to a `CancellationToken`; cancelling it
//! kills the tree and every consuming path resolves to `Error::Cancelled`.
//! Re-exports `CancellationToken` (from `tokio-util`).
//! - **`record`** — record/replay cassettes over the [`ProcessRunner`] seam:
//! `RecordReplayRunner` records real `Invocation → ProcessResult` pairs to a
//! JSON fixture once, then replays them hermetically — no subprocess in CI.
//! Pulls in `serde` + `serde_json`.
//!
//! [Job Object]: https://learn.microsoft.com/windows/win32/procthread/job-objects
//! [cgroup v2]: https://docs.kernel.org/admin-guide/cgroup-v2.html
pub use output_all;
pub use ;
pub use RecordReplayRunner;
pub use CliClient;
pub use Command;
pub use ;
pub use Encoding;
pub use ;
pub use ;
pub use ResourceLimits;
pub use Mechanism;
pub use Pipeline;
pub use ;
pub use ;
pub use ;
pub use Signal;
pub use ;
pub use ;
pub use ;
// Re-exported so callers can `use processkit::StreamExt;` to consume
// [`RunningProcess::stdout_lines`]'s [`StdoutLines`] stream (`.next().await`,
// combinators) without depending on `tokio-stream` directly.
pub use StreamExt;
// `cli_client!` is exported at the crate root via `#[macro_export]`.
use OsStr;
/// Run `program` with `args` inside a private job and return trimmed stdout, or
/// an [`Error`] on a non-zero exit / spawn failure / timeout. A thin shim over
/// [`Command`]; use the builder for a working directory, env, stdin, or timeout.
pub async
/// Run `program` with `args` inside a private job and capture the result
/// without erroring on a non-zero exit — for commands whose exit code is meaningful.
pub async
/// Wait for whichever of several running processes exits **first**, returning
/// its index in `processes` and its exit code (`None` for a signal-killed run,
/// matching [`RunningProcess::wait`]).
///
/// The processes are only *borrowed*: the race is cancel-safe, so the losers —
/// and the winner, whose exit status tokio caches — remain fully usable
/// afterwards ([`wait`](RunningProcess::wait), another `wait_any`, …). This is
/// the natural primitive for supervising several long-lived children: race
/// them, handle the one that finished, keep watching the rest.
///
/// ```no_run
/// # async fn demo() -> processkit::Result<()> {
/// use processkit::{Command, ProcessGroup, wait_any};
///
/// let group = ProcessGroup::new()?;
/// let mut a = group.start(&Command::new("server-a")).await?;
/// let mut b = group.start(&Command::new("server-b")).await?;
/// let (idx, code) = wait_any(&mut [&mut a, &mut b]).await?;
/// println!("contender #{idx} exited first with {code:?}");
/// # Ok(())
/// # }
/// ```
///
/// Two deliberate non-features:
///
/// - **No per-process [`timeout`](Command::timeout)** — the configured deadline
/// is armed by the consuming wait paths, not here. Bound the whole race with
/// [`tokio::time::timeout`] when a deadline is wanted.
/// - **No output pumping** — a contender that fills its stdout/stderr pipe
/// blocks and never exits. Drain chatty children first (e.g. via
/// [`stdout_lines`](RunningProcess::stdout_lines)) or race low-output ones.
/// Note the interplay: a [`tokio::time::timeout`] bounding the race fires,
/// but leaves such pipe-blocked contenders alive and still wedged — kill or
/// drain them afterwards; the timeout alone is not the mitigation.
///
/// An empty `processes` slice is an error ([`Error::Io`] with
/// [`InvalidInput`](std::io::ErrorKind::InvalidInput)) rather than a future
/// that never resolves.
pub async
/// Wait for **all** of several running processes to exit, returning their exit
/// codes (`None` for a signal-killed run) in the same order as `processes`.
///
/// The companion to [`wait_any`]: where `wait_any` races and returns the first
/// finisher, `wait_all` drives every contender to completion concurrently and
/// collects them. The processes are only *borrowed* and stay usable afterwards
/// (the exit status tokio caches remains re-readable). This is the natural
/// primitive for fanning a fixed set of children out and joining on the lot.
///
/// ```no_run
/// # async fn demo() -> processkit::Result<()> {
/// use processkit::{Command, ProcessGroup, wait_all};
///
/// let group = ProcessGroup::new()?;
/// let mut a = group.start(&Command::new("worker-a")).await?;
/// let mut b = group.start(&Command::new("worker-b")).await?;
/// let codes = wait_all(&mut [&mut a, &mut b]).await?;
/// assert_eq!(codes.len(), 2); // one entry per process, in input order
/// # Ok(())
/// # }
/// ```
///
/// Same two non-features as [`wait_any`]: **no per-process
/// [`timeout`](Command::timeout)** (bound the whole batch with
/// [`tokio::time::timeout`]) and **no output pumping** (a contender that fills
/// its stdout/stderr pipe blocks forever — drain chatty children first). Unlike
/// `wait_any`, an empty slice resolves immediately to an empty `Vec`: collecting
/// zero outcomes is well-defined, where racing none is not.
///
/// If a contender fails to reap (an OS I/O error), that `Err` is returned and
/// the remaining processes stay waitable (cancel-safe).
pub async
/// The `mockall`-generated mock of [`ProcessRunner`] (enabled by the `mock`
/// feature), re-exported under a friendlier name.
pub use MockProcessRunner as MockRunner;
/// Re-exported (under the `cancellation` feature) so callers can
/// `use processkit::CancellationToken;` without a direct `tokio-util`
/// dependency. See [`Command::cancel_on`].
pub use CancellationToken;