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;
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
198        // Spawn the process handling task
199        let command = self.command.clone();
200        let cwd = self.cwd.take();
201        let env = self.env.take();
202        let stdin_content = self.stdin_content.take();
203        let grace = GraceWindows {
204            exit_pump_ms: self.exit_pump_grace_ms,
205            kill_ms: self.kill_grace_ms,
206        };
207        let kill_signal = self.kill_signal.clone();
208
209        let task = tokio::spawn(async move {
210            let result =
211                run_streaming_process(command, cwd, env, stdin_content, grace, tx, kill_rx).await;
212            if let Err(error) = &result {
213                trace_lazy("StreamingRunner", || format!("Error: {error}"));
214            }
215            result
216        });
217
218        (
219            OutputStream {
220                rx,
221                kill_tx,
222                kill_signal,
223                killed: false,
224            },
225            task,
226        )
227    }
228
229    /// Start the process and return a stream of output chunks
230    pub fn stream(self) -> OutputStream {
231        self.spawn().0
232    }
233
234    /// Run to completion and collect all output
235    pub async fn collect(self) -> Result<CommandResult> {
236        let mut stdout = Vec::new();
237        let mut stderr = Vec::new();
238        let mut exit_code = 0;
239
240        let (mut stream, task) = self.spawn();
241        while let Some(chunk) = stream.rx.recv().await {
242            match chunk {
243                OutputChunk::Stdout(data) => stdout.extend(data),
244                OutputChunk::Stderr(data) => stderr.extend(data),
245                OutputChunk::Exit(code) => exit_code = code,
246            }
247        }
248
249        task.await.map_err(|error| {
250            std::io::Error::other(format!("streaming process task failed: {error}"))
251        })??;
252
253        Ok(CommandResult {
254            stdout: String::from_utf8_lossy(&stdout).to_string(),
255            stderr: String::from_utf8_lossy(&stderr).to_string(),
256            code: exit_code,
257        })
258    }
259}
260
261/// Stream of output chunks from a process
262pub struct OutputStream {
263    rx: mpsc::Receiver<OutputChunk>,
264    kill_tx: mpsc::UnboundedSender<String>,
265    kill_signal: String,
266    killed: bool,
267}
268
269impl OutputStream {
270    /// Receive the next chunk
271    pub async fn next(&mut self) -> Option<OutputChunk> {
272        self.rx.recv().await
273    }
274
275    /// Stop the process using the configured kill signal (default `SIGTERM`).
276    ///
277    /// This can be called from inside the consumption loop to stop a
278    /// long-running or endless process; a terminating `OutputChunk::Exit` is
279    /// still delivered afterwards.
280    pub fn kill(&mut self) {
281        let signal = self.kill_signal.clone();
282        self.kill_with(&signal);
283    }
284
285    /// Stop the process using an explicit signal, overriding the configured
286    /// kill signal for this call.
287    pub fn kill_with(&mut self, signal: &str) {
288        if self.killed {
289            return;
290        }
291        self.killed = true;
292        trace_lazy("OutputStream", || format!("kill | signal={}", signal));
293        // Best effort: the task may have already finished, in which case the
294        // receiver is gone and the send fails harmlessly.
295        let _ = self.kill_tx.send(signal.to_string());
296    }
297
298    /// Collect all remaining output into vectors
299    pub async fn collect(mut self) -> (Vec<u8>, Vec<u8>, i32) {
300        let mut stdout = Vec::new();
301        let mut stderr = Vec::new();
302        let mut exit_code = 0;
303
304        while let Some(chunk) = self.rx.recv().await {
305            match chunk {
306                OutputChunk::Stdout(data) => stdout.extend(data),
307                OutputChunk::Stderr(data) => stderr.extend(data),
308                OutputChunk::Exit(code) => exit_code = code,
309            }
310        }
311
312        (stdout, stderr, exit_code)
313    }
314
315    /// Collect stdout only, discarding stderr
316    pub async fn collect_stdout(mut self) -> Vec<u8> {
317        let mut stdout = Vec::new();
318
319        while let Some(chunk) = self.rx.recv().await {
320            if let OutputChunk::Stdout(data) = chunk {
321                stdout.extend(data);
322            }
323        }
324
325        stdout
326    }
327}
328
329impl Drop for OutputStream {
330    fn drop(&mut self) {
331        // Abandoning the stream (e.g. `break`-ing out of the loop) must stop the
332        // process, matching the JavaScript iterator's `finally` cleanup. If the
333        // process already finished this is a harmless no-op.
334        if !self.killed {
335            let _ = self.kill_tx.send(self.kill_signal.clone());
336        }
337    }
338}
339
340/// How long the runner waits, in milliseconds, at the two points where it gives
341/// something a chance to finish on its own before forcing the issue.
342#[derive(Debug, Clone, Copy)]
343struct GraceWindows {
344    /// Time allowed for the readers to drain buffered output after the child
345    /// exits, before the `Exit` chunk is emitted.
346    exit_pump_ms: u64,
347    /// Time allowed for the child to handle the delivered signal, before the
348    /// escalation to `SIGKILL`.
349    kill_ms: u64,
350}
351
352/// Run a streaming process and send output to the channel
353async fn run_streaming_process(
354    command: StreamingCommand,
355    cwd: Option<PathBuf>,
356    env: Option<HashMap<String, String>>,
357    stdin_content: Option<String>,
358    grace: GraceWindows,
359    tx: mpsc::Sender<OutputChunk>,
360    mut kill_rx: mpsc::UnboundedReceiver<String>,
361) -> Result<()> {
362    trace_lazy("StreamingRunner", || match &command {
363        StreamingCommand::Shell(command) => format!("Starting: {command}"),
364        StreamingCommand::Argv { program, args } => {
365            format!("Starting argv command: {program:?} {args:?}")
366        }
367    });
368
369    let mut cmd = match command {
370        StreamingCommand::Shell(command) => {
371            let shell = find_available_shell();
372            let mut cmd = Command::new(&shell.cmd);
373            cmd.args(&shell.args);
374            crate::utils::append_shell_command(&mut cmd, &command, env.as_ref());
375            cmd
376        }
377        StreamingCommand::Argv { program, args } => {
378            let mut cmd = Command::new(program);
379            cmd.args(args);
380            cmd
381        }
382    };
383
384    // Configure stdio
385    if stdin_content.is_some() {
386        cmd.stdin(Stdio::piped());
387    } else {
388        cmd.stdin(Stdio::null());
389    }
390    cmd.stdout(Stdio::piped());
391    cmd.stderr(Stdio::piped());
392
393    // Run the child in its own process group so we can signal the whole group
394    // (parent + grandchildren), matching the JavaScript implementation.
395    #[cfg(unix)]
396    cmd.process_group(0);
397
398    // Set working directory
399    if let Some(ref cwd) = cwd {
400        cmd.current_dir(cwd);
401    }
402
403    // Set environment
404    if let Some(ref env_vars) = env {
405        for (key, value) in env_vars {
406            cmd.env(key, value);
407        }
408    }
409
410    let mut child = cmd.spawn()?;
411
412    // Write stdin if needed
413    if let Some(content) = stdin_content {
414        if let Some(mut stdin) = child.stdin.take() {
415            use tokio::io::AsyncWriteExt;
416            let _ = stdin.write_all(content.as_bytes()).await;
417            let _ = stdin.shutdown().await;
418        }
419    }
420
421    // Spawn stdout reader
422    let stdout = child.stdout.take();
423    let tx_stdout = tx.clone();
424    let stdout_handle = stdout.map(|stdout| {
425        tokio::spawn(async move {
426            let mut reader = BufReader::new(stdout);
427            let mut buf = vec![0u8; 8192];
428            loop {
429                use tokio::io::AsyncReadExt;
430                match reader.read(&mut buf).await {
431                    Ok(0) => break,
432                    Ok(n) => {
433                        if tx_stdout
434                            .send(OutputChunk::Stdout(buf[..n].to_vec()))
435                            .await
436                            .is_err()
437                        {
438                            break;
439                        }
440                    }
441                    Err(_) => break,
442                }
443            }
444        })
445    });
446
447    // Spawn stderr reader
448    let stderr = child.stderr.take();
449    let tx_stderr = tx.clone();
450    let stderr_handle = stderr.map(|stderr| {
451        tokio::spawn(async move {
452            let mut reader = BufReader::new(stderr);
453            let mut buf = vec![0u8; 8192];
454            loop {
455                use tokio::io::AsyncReadExt;
456                match reader.read(&mut buf).await {
457                    Ok(0) => break,
458                    Ok(n) => {
459                        if tx_stderr
460                            .send(OutputChunk::Stderr(buf[..n].to_vec()))
461                            .await
462                            .is_err()
463                        {
464                            break;
465                        }
466                    }
467                    Err(_) => break,
468                }
469            }
470        })
471    });
472
473    // Wait for the process to exit OR for a kill request — crucially we do NOT
474    // wait for the readers first. If a grandchild keeps the pipe open the
475    // readers would never finish, so waiting on them before the exit (as the
476    // old implementation did) would hang forever (issue #155).
477    let pid = child.id();
478    let code;
479    tokio::select! {
480        status = child.wait() => {
481            code = status_to_code(status?);
482        }
483        maybe_signal = kill_rx.recv() => {
484            // A kill was requested (explicit kill()/kill_with() or the stream
485            // being dropped). Stop the process group with the requested signal.
486            let signal = maybe_signal.unwrap_or_else(|| DEFAULT_KILL_SIGNAL.to_string());
487            trace_lazy("StreamingRunner", || format!("Kill requested | signal={}", signal));
488            // Give the child its grace period to run its own handler and exit
489            // on its own terms, then escalate to a forceful kill so a process
490            // that ignores the signal still terminates.
491            //
492            // A zero grace period means the child is given no opportunity to
493            // handle the signal, so the requested signal is not delivered at
494            // all. Anything done between it and the forceful kill - a syscall,
495            // or awaiting a zero-length timeout, which yields to the runtime -
496            // is a window the child can be scheduled in, which made "no grace"
497            // a race the child occasionally won rather than a guarantee.
498            let survived_grace = if grace.kill_ms == 0 {
499                true
500            } else {
501                if let Some(pid) = pid {
502                    // The child is always spawned with `process_group(0)`
503                    // above, so it leads the group named by its own pid.
504                    send_signal_to_process(pid, &signal, Delivery::ProcessAndGroup);
505                }
506                tokio::time::timeout(Duration::from_millis(grace.kill_ms), child.wait())
507                    .await
508                    .is_err()
509            };
510            if survived_grace {
511                if let Some(pid) = pid {
512                    send_signal_to_process(pid, "SIGKILL", Delivery::ProcessAndGroup);
513                }
514                let _ = child.start_kill();
515                let _ = child.wait().await;
516            }
517            // Report the conventional 128 + signal code for the requested
518            // signal, matching the JavaScript implementation.
519            code = signal_exit_code(&signal);
520        }
521    }
522
523    // The process has exited. Give the readers a short grace period to flush any
524    // buffered output, then abort any that are still blocked on an inherited
525    // open pipe so we don't hang.
526    let stdout_abort = stdout_handle.as_ref().map(|h| h.abort_handle());
527    let stderr_abort = stderr_handle.as_ref().map(|h| h.abort_handle());
528    let drain = async {
529        if let Some(handle) = stdout_handle {
530            let _ = handle.await;
531        }
532        if let Some(handle) = stderr_handle {
533            let _ = handle.await;
534        }
535    };
536    if tokio::time::timeout(Duration::from_millis(grace.exit_pump_ms), drain)
537        .await
538        .is_err()
539    {
540        // A reader is still blocked on an inherited open pipe — abort it so the
541        // exit chunk is delivered without waiting for the grandchild.
542        if let Some(abort) = stdout_abort {
543            abort.abort();
544        }
545        if let Some(abort) = stderr_abort {
546            abort.abort();
547        }
548    }
549
550    // Send exit code (always — even if a reader was aborted).
551    let _ = tx.send(OutputChunk::Exit(code)).await;
552
553    trace_lazy("StreamingRunner", || format!("Exited with code: {}", code));
554
555    Ok(())
556}
557
558/// Convert an exit status into a numeric exit code, using the conventional
559/// `128 + signal` mapping when the process was terminated by a signal.
560fn status_to_code(status: std::process::ExitStatus) -> i32 {
561    if let Some(code) = status.code() {
562        return code;
563    }
564    #[cfg(unix)]
565    {
566        use std::os::unix::process::ExitStatusExt;
567        if let Some(sig) = status.signal() {
568            return 128 + sig;
569        }
570    }
571    -1
572}
573
574/// Shell configuration
575#[derive(Debug, Clone)]
576struct ShellConfig {
577    cmd: String,
578    args: Vec<String>,
579}
580
581/// Find an available shell
582fn find_available_shell() -> ShellConfig {
583    let is_windows = cfg!(windows);
584
585    if is_windows {
586        ShellConfig {
587            cmd: "cmd.exe".to_string(),
588            args: vec!["/c".to_string()],
589        }
590    } else {
591        let shells = [
592            ("/bin/sh", "-c"),
593            ("/usr/bin/sh", "-c"),
594            ("/bin/bash", "-c"),
595        ];
596
597        for (cmd, arg) in shells {
598            if std::path::Path::new(cmd).exists() {
599                return ShellConfig {
600                    cmd: cmd.to_string(),
601                    args: vec![arg.to_string()],
602                };
603            }
604        }
605
606        ShellConfig {
607            cmd: "/bin/sh".to_string(),
608            args: vec!["-c".to_string()],
609        }
610    }
611}
612
613/// Async iterator trait for output streams
614#[async_trait::async_trait]
615pub trait AsyncIterator {
616    type Item;
617
618    /// Get the next item from the iterator
619    async fn next(&mut self) -> Option<Self::Item>;
620}
621
622#[async_trait::async_trait]
623impl AsyncIterator for OutputStream {
624    type Item = OutputChunk;
625
626    async fn next(&mut self) -> Option<Self::Item> {
627        self.rx.recv().await
628    }
629}
630
631/// Extension trait to convert ProcessRunner into a stream
632pub trait IntoStream {
633    /// Convert into an output stream
634    fn into_stream(self) -> OutputStream;
635}
636
637impl IntoStream for crate::ProcessRunner {
638    fn into_stream(self) -> OutputStream {
639        let streaming = StreamingRunner::new(self.command().to_string());
640        streaming.stream()
641    }
642}