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
/*******************************************************************************
*
* Copyright (c) 2026 Haixing Hu.
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0.
*
******************************************************************************/
use std::{
process::ExitStatus,
thread,
time::{
Duration,
Instant,
},
};
use super::{
command_io::CommandIo,
error_mapping::{
kill_failed,
wait_failed,
},
finished_command::FinishedCommand,
managed_child_process::ManagedChildProcess,
wait_policy::next_sleep,
};
use crate::CommandError;
/// Running command state that owns process and I/O helper lifetimes.
pub(crate) struct RunningCommand {
/// Human-readable command text for diagnostics.
command_text: String,
/// Child process managed by the command runner.
child_process: ManagedChildProcess,
/// Output readers and optional stdin writer.
io: CommandIo,
/// Time when the child process started being monitored.
started_at: Instant,
}
impl RunningCommand {
/// Creates a running command state object.
///
/// # Parameters
///
/// * `command_text` - Human-readable command text for diagnostics.
/// * `child_process` - Child process managed by the runner.
/// * `io` - Output readers and optional stdin writer.
///
/// # Returns
///
/// Running command state that owns the process and its I/O helpers.
pub(crate) fn new(
command_text: String,
child_process: ManagedChildProcess,
io: CommandIo,
) -> Self {
Self {
command_text,
child_process,
io,
started_at: Instant::now(),
}
}
/// Waits for the child process to complete or time out.
///
/// # Parameters
///
/// * `timeout` - Optional command timeout.
///
/// # Returns
///
/// Finished command output when the child exits normally.
///
/// # Errors
///
/// Returns [`CommandError`] if waiting fails, timeout handling fails, output
/// collection fails, or stdin writing fails. Wait-error cleanup only joins I/O
/// helpers after a non-blocking check confirms the child has exited.
pub(crate) fn wait_for_completion(
mut self,
timeout: Option<Duration>,
) -> Result<FinishedCommand, CommandError> {
loop {
let maybe_status = match self.child_process.try_wait() {
Ok(status) => status,
Err(source) => {
let error = wait_failed(&self.command_text, source);
return Err(self.clean_up_after_wait_error(error));
}
};
if let Some(status) = maybe_status {
return self.complete_after_exit(status, timeout);
}
if let Some(timeout) = timeout
&& self.started_at.elapsed() >= timeout
{
return self.handle_timeout(timeout);
}
thread::sleep(next_sleep(timeout, self.started_at.elapsed()));
}
}
/// Completes a command after the direct child exits.
///
/// # Parameters
///
/// * `status` - Exit status reported by the direct child process.
/// * `timeout` - Optional command timeout that also bounds I/O collection.
///
/// # Returns
///
/// Finished command output when all I/O helpers finish before the timeout.
///
/// # Errors
///
/// Returns [`CommandError::TimedOut`] if inherited output pipes keep I/O
/// helpers alive beyond the configured timeout, or another [`CommandError`]
/// if cleanup or output collection fails.
fn complete_after_exit(
self,
status: ExitStatus,
timeout: Option<Duration>,
) -> Result<FinishedCommand, CommandError> {
if let Some(timeout) = timeout {
while !self.io.is_finished() {
let elapsed = self.started_at.elapsed();
if elapsed >= timeout {
return self.handle_output_collection_timeout(status, timeout);
}
thread::sleep(next_sleep(Some(timeout), elapsed));
}
}
self.complete(status)
}
/// Handles timeout reached while collecting inherited output pipes.
///
/// # Parameters
///
/// * `status` - Exit status reported by the direct child process.
/// * `timeout` - Timeout that has been exceeded.
///
/// # Errors
///
/// Returns [`CommandError::TimedOut`] after terminating the process tree and
/// collecting final output, or the process-control / collection error that
/// prevented timeout output from being built.
fn handle_output_collection_timeout(
mut self,
status: ExitStatus,
timeout: Duration,
) -> Result<FinishedCommand, CommandError> {
if let Err(source) = self.child_process.start_kill() {
return Err(kill_failed(self.command_text.clone(), timeout, source));
}
while !self.io.is_finished() {
thread::sleep(next_sleep(None, self.started_at.elapsed()));
}
let finished = self.complete(status)?;
Err(CommandError::TimedOut {
command: finished.command_text,
timeout,
output: Box::new(finished.output),
})
}
/// Handles timeout by killing the child process and collecting final output.
///
/// # Parameters
///
/// * `timeout` - Timeout that has been exceeded.
///
/// # Errors
///
/// Returns [`CommandError::TimedOut`] after successful kill and wait, or the
/// process-control error if killing or waiting fails. Cleanup after those
/// errors only joins I/O helpers if the child is already confirmed exited.
fn handle_timeout(mut self, timeout: Duration) -> Result<FinishedCommand, CommandError> {
if let Err(source) = self.child_process.start_kill() {
let error = kill_failed(self.command_text.clone(), timeout, source);
return Err(self.collect_if_child_exited(error));
}
let exit_status = match self.child_process.wait() {
Ok(status) => status,
Err(source) => {
let error = wait_failed(&self.command_text, source);
return Err(self.collect_if_child_exited(error));
}
};
let finished = self.complete(exit_status)?;
Err(CommandError::TimedOut {
command: finished.command_text,
timeout,
output: Box::new(finished.output),
})
}
/// Completes a known-exited command by joining all I/O helpers.
///
/// # Parameters
///
/// * `status` - Exit status reported by the child process.
///
/// # Returns
///
/// Finished command output with retained stdout and stderr bytes.
///
/// # Errors
///
/// Returns [`CommandError`] if output collection or stdin writing fails.
fn complete(self, status: ExitStatus) -> Result<FinishedCommand, CommandError> {
let output = self
.io
.collect(&self.command_text, status, self.started_at.elapsed())?;
Ok(FinishedCommand {
command_text: self.command_text,
output,
})
}
/// Attempts non-blocking cleanup after a wait error.
///
/// # Parameters
///
/// * `error` - Original wait error to preserve.
///
/// # Returns
///
/// The original error after best-effort cleanup. This method deliberately does
/// not call blocking wait APIs because it is already handling a wait failure.
fn clean_up_after_wait_error(mut self, error: CommandError) -> CommandError {
let _ = self.child_process.start_kill();
self.collect_if_child_exited(error)
}
/// Drains I/O helpers if the child is already known to have exited.
///
/// # Parameters
///
/// * `error` - Original process-control error to preserve.
///
/// # Returns
///
/// The original error. Output collection failures during cleanup are ignored
/// so the primary process-control failure remains visible.
fn collect_if_child_exited(mut self, error: CommandError) -> CommandError {
if let Ok(Some(status)) = self.child_process.try_wait() {
let _ = self.complete(status);
}
error
}
}