Skip to main content

command_stream/
stream.rs

1//! Streaming and async iteration support
2//!
3//! This module provides async streaming capabilities similar to JavaScript's
4//! async iterators and stream handling in `$.stream-utils.mjs`.
5//!
6//! It mirrors the JavaScript implementation's behavior for issue #155:
7//!
8//!   1. The stream yields an explicit `OutputChunk::Exit(code)` when the
9//!      process exits, so consumers can observe the exit code from inside the
10//!      loop.
11//!   2. The stream does not hang forever when the process has exited but a
12//!      grandchild keeps the stdio pipes open (the readers are drained with a
13//!      grace period and then aborted).
14//!   3. The process can be stopped from inside the loop via
15//!      [`OutputStream::kill`] / [`OutputStream::kill_with`], and abandoning the
16//!      stream (e.g. `break`) also stops the process.
17//!   4. The stop signal is configurable via
18//!      [`StreamingRunner::kill_signal`] (default `SIGTERM`), just like the
19//!      JavaScript `killSignal` option.
20//!
21//! ## Usage
22//!
23//! ```rust,no_run
24//! use command_stream::{StreamingRunner, OutputChunk};
25//!
26//! #[tokio::main]
27//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
28//!     let runner = StreamingRunner::new("yes hello");
29//!
30//!     // Stream output as it arrives
31//!     let mut stream = runner.stream();
32//!     let mut count = 0;
33//!     while let Some(chunk) = stream.next().await {
34//!         match chunk {
35//!             OutputChunk::Stdout(data) => {
36//!                 print!("{}", String::from_utf8_lossy(&data));
37//!                 count += 1;
38//!                 if count >= 5 {
39//!                     // Stop the process from inside the loop.
40//!                     stream.kill();
41//!                 }
42//!             }
43//!             OutputChunk::Stderr(data) => {
44//!                 eprint!("{}", String::from_utf8_lossy(&data));
45//!             }
46//!             OutputChunk::Exit(code) => {
47//!                 println!("Process exited with code: {}", code);
48//!                 break;
49//!             }
50//!         }
51//!     }
52//!
53//!     Ok(())
54//! }
55//! ```
56
57use std::collections::HashMap;
58use std::ffi::OsString;
59use std::path::PathBuf;
60use std::process::Stdio;
61use std::time::Duration;
62use tokio::io::BufReader;
63use tokio::process::Command;
64use tokio::sync::{mpsc, watch};
65use tokio::task::JoinHandle;
66
67use crate::signal::{
68    send_signal_to_process, signal_exit_code, Delivery, DEFAULT_KILL_GRACE_MS, DEFAULT_KILL_SIGNAL,
69};
70use crate::trace::trace_lazy;
71use crate::{CommandResult, Result};
72
73/// Default grace period (in milliseconds) to keep draining the stdio pipes
74/// after the process has exited before aborting any lingering readers. Mirrors
75/// the JavaScript `exitPumpGrace` default.
76const DEFAULT_EXIT_PUMP_GRACE_MS: u64 = 100;
77
78/// A chunk of output from a streaming process
79#[derive(Debug, Clone)]
80pub enum OutputChunk {
81    /// Stdout data
82    Stdout(Vec<u8>),
83    /// Stderr data
84    Stderr(Vec<u8>),
85    /// Process exit code
86    Exit(i32),
87}
88
89/// A streaming process runner that allows async iteration over output
90pub struct StreamingRunner {
91    command: StreamingCommand,
92    cwd: Option<PathBuf>,
93    env: Option<HashMap<String, String>>,
94    stdin_content: Option<String>,
95    kill_signal: String,
96    kill_grace_ms: u64,
97    exit_pump_grace_ms: u64,
98}
99
100#[derive(Clone)]
101enum StreamingCommand {
102    Shell(String),
103    Argv {
104        program: OsString,
105        args: Vec<OsString>,
106    },
107}
108
109impl StreamingRunner {
110    /// Create a streaming runner for a command string interpreted by the
111    /// platform shell.
112    pub fn new(command: impl Into<String>) -> Self {
113        Self::with_command(StreamingCommand::Shell(command.into()))
114    }
115
116    /// Create a streaming runner for an executable and exact argument vector.
117    ///
118    /// Unlike [`StreamingRunner::new`], this constructor bypasses the platform
119    /// shell. Argument boundaries are therefore preserved on every platform,
120    /// including Windows, without requiring shell-specific quoting.
121    pub fn from_argv<P, I, S>(program: P, args: I) -> Self
122    where
123        P: Into<OsString>,
124        I: IntoIterator<Item = S>,
125        S: Into<OsString>,
126    {
127        Self::with_command(StreamingCommand::Argv {
128            program: program.into(),
129            args: args.into_iter().map(Into::into).collect(),
130        })
131    }
132
133    fn with_command(command: StreamingCommand) -> Self {
134        StreamingRunner {
135            command,
136            cwd: None,
137            env: None,
138            stdin_content: None,
139            kill_signal: DEFAULT_KILL_SIGNAL.to_string(),
140            kill_grace_ms: DEFAULT_KILL_GRACE_MS,
141            exit_pump_grace_ms: DEFAULT_EXIT_PUMP_GRACE_MS,
142        }
143    }
144
145    /// Set the working directory
146    pub fn cwd(mut self, path: impl Into<PathBuf>) -> Self {
147        self.cwd = Some(path.into());
148        self
149    }
150
151    /// Set environment variables
152    pub fn env(mut self, env: HashMap<String, String>) -> Self {
153        self.env = Some(env);
154        self
155    }
156
157    /// Set stdin content
158    pub fn stdin(mut self, content: impl Into<String>) -> Self {
159        self.stdin_content = Some(content.into());
160        self
161    }
162
163    /// Configure the signal used to stop the process when it is killed without
164    /// an explicit signal — i.e. [`OutputStream::kill`] or abandoning the
165    /// stream. Mirrors the JavaScript `killSignal` option (default `SIGTERM`).
166    ///
167    /// The reported exit code follows the conventional `128 + signal` mapping
168    /// (e.g. `SIGTERM` => 143, `SIGINT` => 130, `SIGKILL` => 137).
169    pub fn kill_signal(mut self, signal: impl Into<String>) -> Self {
170        self.kill_signal = signal.into();
171        self
172    }
173
174    /// Configure how long (in milliseconds) the child is given to handle the
175    /// kill signal before `SIGKILL` is sent. Mirrors the JavaScript `killGrace`
176    /// option (default 100ms).
177    ///
178    /// This is the window in which a child running its own `SIGTERM` handler
179    /// can shut down on its own terms. Set it to `0` to escalate immediately.
180    pub fn kill_grace_ms(mut self, ms: u64) -> Self {
181        self.kill_grace_ms = ms;
182        self
183    }
184
185    /// Configure the grace period (in milliseconds) to keep draining the stdio
186    /// pipes after the process exits before aborting lingering readers. Mirrors
187    /// the JavaScript `exitPumpGrace` option (default 100ms).
188    pub fn exit_pump_grace_ms(mut self, ms: u64) -> Self {
189        self.exit_pump_grace_ms = ms;
190        self
191    }
192
193    fn spawn(mut self) -> (OutputStream, JoinHandle<Result<()>>) {
194        let (tx, rx) = mpsc::channel(1024);
195        // Unbounded so a synchronous Drop can request a kill without awaiting.
196        let (kill_tx, kill_rx) = mpsc::unbounded_channel::<String>();
197        // The child is spawned inside the task below, so its id is not known
198        // when this returns. The task publishes it here as soon as the spawn
199        // succeeds; `OutputStream::pid` reads the latest value (issue #18).
200        let (pid_tx, pid_rx) = watch::channel(None);
201
202        // Spawn the process handling task
203        let command = self.command.clone();
204        let cwd = self.cwd.take();
205        let env = self.env.take();
206        let stdin_content = self.stdin_content.take();
207        let grace = GraceWindows {
208            exit_pump_ms: self.exit_pump_grace_ms,
209            kill_ms: self.kill_grace_ms,
210        };
211        let kill_signal = self.kill_signal.clone();
212
213        let task = tokio::spawn(async move {
214            let channels = StreamChannels {
215                output_tx: tx,
216                kill_rx,
217                pid_tx,
218            };
219            let result =
220                run_streaming_process(command, cwd, env, stdin_content, grace, channels).await;
221            if let Err(error) = &result {
222                trace_lazy("StreamingRunner", || format!("Error: {error}"));
223            }
224            result
225        });
226
227        (
228            OutputStream {
229                rx,
230                kill_tx,
231                kill_signal,
232                killed: false,
233                pid_rx,
234            },
235            task,
236        )
237    }
238
239    /// Start the process and return a stream of output chunks
240    pub fn stream(self) -> OutputStream {
241        self.spawn().0
242    }
243
244    /// Run to completion and collect all output
245    pub async fn collect(self) -> Result<CommandResult> {
246        let mut stdout = Vec::new();
247        let mut stderr = Vec::new();
248        let mut exit_code = 0;
249
250        let (mut stream, task) = self.spawn();
251        while let Some(chunk) = stream.rx.recv().await {
252            match chunk {
253                OutputChunk::Stdout(data) => stdout.extend(data),
254                OutputChunk::Stderr(data) => stderr.extend(data),
255                OutputChunk::Exit(code) => exit_code = code,
256            }
257        }
258
259        task.await.map_err(|error| {
260            std::io::Error::other(format!("streaming process task failed: {error}"))
261        })??;
262
263        Ok(CommandResult {
264            stdout: String::from_utf8_lossy(&stdout).to_string(),
265            stderr: String::from_utf8_lossy(&stderr).to_string(),
266            code: exit_code,
267        })
268    }
269}
270
271/// Stream of output chunks from a process
272pub struct OutputStream {
273    rx: mpsc::Receiver<OutputChunk>,
274    kill_tx: mpsc::UnboundedSender<String>,
275    kill_signal: String,
276    killed: bool,
277    pid_rx: watch::Receiver<Option<u32>>,
278}
279
280impl OutputStream {
281    /// Receive the next chunk
282    pub async fn next(&mut self) -> Option<OutputChunk> {
283        self.rx.recv().await
284    }
285
286    /// Process id of the streamed command, as currently known.
287    ///
288    /// The child is spawned by a background task, so this is `None` for the
289    /// short window between [`StreamingRunner::stream`] returning and the spawn
290    /// completing, and stays `None` if the spawn failed. From the first
291    /// delivered chunk onwards it is set, and it remains readable after the
292    /// process has exited. Use [`wait_for_pid`](Self::wait_for_pid) to avoid
293    /// the startup window.
294    pub fn pid(&self) -> Option<u32> {
295        *self.pid_rx.borrow()
296    }
297
298    /// Process id of the streamed command, waiting for the spawn to complete.
299    ///
300    /// Resolves as soon as the child exists, and returns `None` if the process
301    /// could never be spawned. This is the streaming counterpart of awaiting a
302    /// stream before reading `runner.pid` in JavaScript.
303    pub async fn wait_for_pid(&mut self) -> Option<u32> {
304        // `wait_for` checks the current value first, so an already-published id
305        // returns without waiting. An error means the sending task is gone,
306        // which only happens when the spawn failed.
307        match self.pid_rx.wait_for(|pid| pid.is_some()).await {
308            Ok(pid) => *pid,
309            Err(_) => None,
310        }
311    }
312
313    /// Stop the process using the configured kill signal (default `SIGTERM`).
314    ///
315    /// This can be called from inside the consumption loop to stop a
316    /// long-running or endless process; a terminating `OutputChunk::Exit` is
317    /// still delivered afterwards.
318    pub fn kill(&mut self) {
319        let signal = self.kill_signal.clone();
320        self.kill_with(&signal);
321    }
322
323    /// Stop the process using an explicit signal, overriding the configured
324    /// kill signal for this call.
325    pub fn kill_with(&mut self, signal: &str) {
326        if self.killed {
327            return;
328        }
329        self.killed = true;
330        trace_lazy("OutputStream", || format!("kill | signal={}", signal));
331        // Best effort: the task may have already finished, in which case the
332        // receiver is gone and the send fails harmlessly.
333        let _ = self.kill_tx.send(signal.to_string());
334    }
335
336    /// Collect all remaining output into vectors
337    pub async fn collect(mut self) -> (Vec<u8>, Vec<u8>, i32) {
338        let mut stdout = Vec::new();
339        let mut stderr = Vec::new();
340        let mut exit_code = 0;
341
342        while let Some(chunk) = self.rx.recv().await {
343            match chunk {
344                OutputChunk::Stdout(data) => stdout.extend(data),
345                OutputChunk::Stderr(data) => stderr.extend(data),
346                OutputChunk::Exit(code) => exit_code = code,
347            }
348        }
349
350        (stdout, stderr, exit_code)
351    }
352
353    /// Collect stdout only, discarding stderr
354    pub async fn collect_stdout(mut self) -> Vec<u8> {
355        let mut stdout = Vec::new();
356
357        while let Some(chunk) = self.rx.recv().await {
358            if let OutputChunk::Stdout(data) = chunk {
359                stdout.extend(data);
360            }
361        }
362
363        stdout
364    }
365}
366
367impl Drop for OutputStream {
368    fn drop(&mut self) {
369        // Abandoning the stream (e.g. `break`-ing out of the loop) must stop the
370        // process, matching the JavaScript iterator's `finally` cleanup. If the
371        // process already finished this is a harmless no-op.
372        if !self.killed {
373            let _ = self.kill_tx.send(self.kill_signal.clone());
374        }
375    }
376}
377
378/// The channels `run_streaming_process` communicates over: output chunks out,
379/// kill requests in, and the child's id published once the spawn succeeds.
380struct StreamChannels {
381    /// Carries the output chunks, and finally the `Exit` chunk, to the consumer.
382    output_tx: mpsc::Sender<OutputChunk>,
383    /// Carries kill requests, by signal name, in from the consumer.
384    kill_rx: mpsc::UnboundedReceiver<String>,
385    /// Publishes the child's id, which is only known inside the spawning task.
386    pid_tx: watch::Sender<Option<u32>>,
387}
388
389/// How long the runner waits, in milliseconds, at the two points where it gives
390/// something a chance to finish on its own before forcing the issue.
391#[derive(Debug, Clone, Copy)]
392struct GraceWindows {
393    /// Time allowed for the readers to drain buffered output after the child
394    /// exits, before the `Exit` chunk is emitted.
395    exit_pump_ms: u64,
396    /// Time allowed for the child to handle the delivered signal, before the
397    /// escalation to `SIGKILL`.
398    kill_ms: u64,
399}
400
401/// Run a streaming process and send output to the channel
402async fn run_streaming_process(
403    command: StreamingCommand,
404    cwd: Option<PathBuf>,
405    env: Option<HashMap<String, String>>,
406    stdin_content: Option<String>,
407    grace: GraceWindows,
408    channels: StreamChannels,
409) -> Result<()> {
410    let StreamChannels {
411        output_tx: tx,
412        mut kill_rx,
413        pid_tx,
414    } = channels;
415    trace_lazy("StreamingRunner", || match &command {
416        StreamingCommand::Shell(command) => format!("Starting: {command}"),
417        StreamingCommand::Argv { program, args } => {
418            format!("Starting argv command: {program:?} {args:?}")
419        }
420    });
421
422    let mut cmd = match command {
423        StreamingCommand::Shell(command) => crate::utils::shell_command(&command, env.as_ref()),
424        StreamingCommand::Argv { program, args } => {
425            let mut cmd = Command::new(program);
426            cmd.args(args);
427            cmd
428        }
429    };
430
431    // Configure stdio
432    if stdin_content.is_some() {
433        cmd.stdin(Stdio::piped());
434    } else {
435        cmd.stdin(Stdio::null());
436    }
437    cmd.stdout(Stdio::piped());
438    cmd.stderr(Stdio::piped());
439
440    // Run the child in its own process group so we can signal the whole group
441    // (parent + grandchildren), matching the JavaScript implementation.
442    #[cfg(unix)]
443    cmd.process_group(0);
444
445    // Set working directory
446    if let Some(ref cwd) = cwd {
447        cmd.current_dir(cwd);
448    }
449
450    // Set environment
451    if let Some(ref env_vars) = env {
452        for (key, value) in env_vars {
453            cmd.env(key, value);
454        }
455    }
456
457    let mut child = cmd.spawn()?;
458    // Publish the id before any awaiting, so a consumer asking for it as soon
459    // as the first chunk arrives already sees it.
460    let _ = pid_tx.send(child.id());
461
462    // Write stdin if needed
463    if let Some(content) = stdin_content {
464        if let Some(mut stdin) = child.stdin.take() {
465            use tokio::io::AsyncWriteExt;
466            let _ = stdin.write_all(content.as_bytes()).await;
467            let _ = stdin.shutdown().await;
468        }
469    }
470
471    // Spawn stdout reader
472    let stdout = child.stdout.take();
473    let tx_stdout = tx.clone();
474    let stdout_handle = stdout.map(|stdout| {
475        tokio::spawn(async move {
476            let mut reader = BufReader::new(stdout);
477            let mut buf = vec![0u8; 8192];
478            loop {
479                use tokio::io::AsyncReadExt;
480                match reader.read(&mut buf).await {
481                    Ok(0) => break,
482                    Ok(n) => {
483                        if tx_stdout
484                            .send(OutputChunk::Stdout(buf[..n].to_vec()))
485                            .await
486                            .is_err()
487                        {
488                            break;
489                        }
490                    }
491                    Err(_) => break,
492                }
493            }
494        })
495    });
496
497    // Spawn stderr reader
498    let stderr = child.stderr.take();
499    let tx_stderr = tx.clone();
500    let stderr_handle = stderr.map(|stderr| {
501        tokio::spawn(async move {
502            let mut reader = BufReader::new(stderr);
503            let mut buf = vec![0u8; 8192];
504            loop {
505                use tokio::io::AsyncReadExt;
506                match reader.read(&mut buf).await {
507                    Ok(0) => break,
508                    Ok(n) => {
509                        if tx_stderr
510                            .send(OutputChunk::Stderr(buf[..n].to_vec()))
511                            .await
512                            .is_err()
513                        {
514                            break;
515                        }
516                    }
517                    Err(_) => break,
518                }
519            }
520        })
521    });
522
523    // Wait for the process to exit OR for a kill request — crucially we do NOT
524    // wait for the readers first. If a grandchild keeps the pipe open the
525    // readers would never finish, so waiting on them before the exit (as the
526    // old implementation did) would hang forever (issue #155).
527    let pid = child.id();
528    let code;
529    tokio::select! {
530        status = child.wait() => {
531            code = status_to_code(status?);
532        }
533        maybe_signal = kill_rx.recv() => {
534            // A kill was requested (explicit kill()/kill_with() or the stream
535            // being dropped). Stop the process group with the requested signal.
536            let signal = maybe_signal.unwrap_or_else(|| DEFAULT_KILL_SIGNAL.to_string());
537            trace_lazy("StreamingRunner", || format!("Kill requested | signal={}", signal));
538            // Give the child its grace period to run its own handler and exit
539            // on its own terms, then escalate to a forceful kill so a process
540            // that ignores the signal still terminates.
541            //
542            // A zero grace period means the child is given no opportunity to
543            // handle the signal, so the requested signal is not delivered at
544            // all. Anything done between it and the forceful kill - a syscall,
545            // or awaiting a zero-length timeout, which yields to the runtime -
546            // is a window the child can be scheduled in, which made "no grace"
547            // a race the child occasionally won rather than a guarantee.
548            let survived_grace = if grace.kill_ms == 0 {
549                true
550            } else {
551                if let Some(pid) = pid {
552                    // The child is always spawned with `process_group(0)`
553                    // above, so it leads the group named by its own pid.
554                    send_signal_to_process(pid, &signal, Delivery::ProcessAndGroup);
555                }
556                tokio::time::timeout(Duration::from_millis(grace.kill_ms), child.wait())
557                    .await
558                    .is_err()
559            };
560            if survived_grace {
561                if let Some(pid) = pid {
562                    send_signal_to_process(pid, "SIGKILL", Delivery::ProcessAndGroup);
563                }
564                let _ = child.start_kill();
565                let _ = child.wait().await;
566            }
567            // Report the conventional 128 + signal code for the requested
568            // signal, matching the JavaScript implementation.
569            code = signal_exit_code(&signal);
570        }
571    }
572
573    // The process has exited. Give the readers a short grace period to flush any
574    // buffered output, then abort any that are still blocked on an inherited
575    // open pipe so we don't hang.
576    let stdout_abort = stdout_handle.as_ref().map(|h| h.abort_handle());
577    let stderr_abort = stderr_handle.as_ref().map(|h| h.abort_handle());
578    let drain = async {
579        if let Some(handle) = stdout_handle {
580            let _ = handle.await;
581        }
582        if let Some(handle) = stderr_handle {
583            let _ = handle.await;
584        }
585    };
586    if tokio::time::timeout(Duration::from_millis(grace.exit_pump_ms), drain)
587        .await
588        .is_err()
589    {
590        // A reader is still blocked on an inherited open pipe — abort it so the
591        // exit chunk is delivered without waiting for the grandchild.
592        if let Some(abort) = stdout_abort {
593            abort.abort();
594        }
595        if let Some(abort) = stderr_abort {
596            abort.abort();
597        }
598    }
599
600    // Send exit code (always — even if a reader was aborted).
601    let _ = tx.send(OutputChunk::Exit(code)).await;
602
603    trace_lazy("StreamingRunner", || format!("Exited with code: {}", code));
604
605    Ok(())
606}
607
608/// Convert an exit status into a numeric exit code, using the conventional
609/// `128 + signal` mapping when the process was terminated by a signal.
610fn status_to_code(status: std::process::ExitStatus) -> i32 {
611    if let Some(code) = status.code() {
612        return code;
613    }
614    #[cfg(unix)]
615    {
616        use std::os::unix::process::ExitStatusExt;
617        if let Some(sig) = status.signal() {
618            return 128 + sig;
619        }
620    }
621    -1
622}
623
624/// Async iterator trait for output streams
625#[async_trait::async_trait]
626pub trait AsyncIterator {
627    type Item;
628
629    /// Get the next item from the iterator
630    async fn next(&mut self) -> Option<Self::Item>;
631}
632
633#[async_trait::async_trait]
634impl AsyncIterator for OutputStream {
635    type Item = OutputChunk;
636
637    async fn next(&mut self) -> Option<Self::Item> {
638        self.rx.recv().await
639    }
640}
641
642/// Extension trait to convert ProcessRunner into a stream
643pub trait IntoStream {
644    /// Convert into an output stream
645    fn into_stream(self) -> OutputStream;
646}
647
648impl IntoStream for crate::ProcessRunner {
649    fn into_stream(self) -> OutputStream {
650        let streaming = StreamingRunner::new(self.command().to_string());
651        streaming.stream()
652    }
653}