thirdshift 0.13.0

Turn a GitHub issue into a ready-for-review pull request, unattended
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
400
401
402
403
404
405
406
407
408
409
410
411
//! Own a Command CLI child and all its I/O until completion or whole-tree cleanup.

use std::io::{Read, Write};
use std::os::unix::process::CommandExt;
use std::process::{Child, ChildStdout, Command, ExitStatus, Output, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, mpsc};
use std::thread::{self, JoinHandle};
use std::time::Duration;

use anyhow::{Context, Result, anyhow, bail};

use crate::interrupt;

mod tree;
pub(crate) use tree::stop;

#[cfg(test)]
mod faults;
#[cfg(test)]
mod tests;

/// Ordinary work stops for a recorded interrupt; completion work finishes
/// independently without clearing the Command's recorded request.
#[derive(Clone, Copy)]
pub(crate) enum Interruption {
    Ordinary,
    Completion,
}

impl Interruption {
    fn requested(self) -> bool {
        matches!(self, Self::Ordinary) && interrupt::requested()
    }

    pub(crate) fn check(self) -> Result<()> {
        if self.requested() {
            bail!("interrupted");
        }
        Ok(())
    }
}

/// Caller-supplied diagnostics and interruption behavior for one execution.
/// This immutable value owns no child or worker and grants no other execution
/// permission to ignore the Command's recorded interruption.
#[derive(Clone, Copy)]
pub(crate) struct Control<'a> {
    pub name: &'a str,
    pub interruption: Interruption,
    pub stop: &'a dyn Fn(&mut Child),
}

/// Capture both output pipes without interpreting the child's exit status.
pub(crate) fn output(
    command: &mut Command,
    input: Option<&[u8]>,
    control: Control<'_>,
) -> Result<Output> {
    let cli = control.name.to_owned();
    let (execution, _) = execute(command, input, control, true, move |pipe| {
        read(pipe).with_context(|| format!("could not read {cli}'s stdout"))
    });
    let (status, stdout, stderr) = execution?;
    Ok(Output {
        status,
        stdout,
        stderr,
    })
}

/// Recovered consumer state accompanies an independent execution result.
#[derive(Debug)]
pub(crate) struct Streamed<T> {
    pub execution: Result<ExitStatus>,
    pub state: T,
}

/// Consume stdout concurrently with prompt I/O, inheriting stderr. Preserve
/// state after any normal consumer return, even when execution fails. Return
/// only after completion or whole-tree cleanup and every worker is joined.
/// A consumer panic or any startup failure returns no state. Recorded ordinary
/// interruption suppresses recovery even after a normal consumer return.
pub(crate) fn streaming<T: Send + 'static>(
    command: &mut Command,
    input: Option<&[u8]>,
    control: Control<'_>,
    mut state: T,
    consume: impl FnOnce(ChildStdout, &mut T) -> Result<()> + Send + 'static,
) -> Result<Streamed<T>> {
    // One send fits without waiting for the caller, which must first finish
    // supervising and joining all workers, including on transport failure.
    let (completed, recovered) = mpsc::sync_channel(1);
    let (execution, started) = execute(command, input, control, false, move |pipe| {
        let result = consume(pipe, &mut state);
        let _ = completed.send(state);
        result
    });
    let execution = execution.map(|(status, (), _)| status);
    control.interruption.check()?;
    if !started {
        return Err(execution.expect_err("startup failure cannot execute successfully"));
    }
    match recovered.try_recv() {
        Ok(state) => Ok(Streamed { execution, state }),
        Err(_) => Err(execution.expect_err("a successful consumer always returns its state")),
    }
}

fn read(mut pipe: impl Read) -> std::io::Result<Vec<u8>> {
    let mut bytes = Vec::new();
    pipe.read_to_end(&mut bytes)?;
    Ok(bytes)
}

fn execute<T: Send + 'static>(
    command: &mut Command,
    input: Option<&[u8]>,
    control: Control<'_>,
    capture_stderr: bool,
    consume: impl FnOnce(ChildStdout) -> Result<T> + Send + 'static,
) -> (Result<(ExitStatus, T, Vec<u8>)>, bool) {
    let Control {
        name,
        interruption,
        stop: _,
    } = control;
    let mut started = false;
    let result = (|| {
        if interruption.requested() {
            bail!("interrupted");
        }
        let cli = name.to_owned();
        let (wake, awakened) = mpsc::channel();
        #[cfg(test)]
        let fault = faults::Fault::from(command);
        let child = command
            .process_group(0)
            .stdin(if input.is_some() {
                Stdio::piped()
            } else {
                Stdio::null()
            })
            .stdout(Stdio::piped())
            .stderr(if capture_stderr {
                Stdio::piped()
            } else {
                Stdio::inherit()
            })
            .spawn()
            .with_context(|| format!("could not run {cli}"))?;
        // Install ownership immediately: every fallible step after spawn is
        // covered, including pipe extraction and starting workers.
        let mut owned = Execution {
            control,
            child,
            awakened,
            stdout: None,
            stderr: None,
            stdin: None,
            completed: false,
        };
        let result = (|| {
            #[cfg(test)]
            fault.fire("stdout-pipe")?;
            let pipe = owned
                .child
                .stdout
                .take()
                .with_context(|| format!("no stdout from {name}"))?;
            let reader = if capture_stderr {
                format!("{cli}'s stdout reader")
            } else {
                "the session stream reader".to_string()
            };
            #[cfg(test)]
            fault.fire("stdout-start")?;
            #[cfg(test)]
            let stdout_fault = fault.clone();
            owned.stdout = Some(Worker::start(reader, wake.clone(), move || {
                #[cfg(test)]
                stdout_fault.fire("stdout-read")?;
                consume(pipe)
            })?);
            if capture_stderr {
                #[cfg(test)]
                fault.fire("stderr-pipe")?;
                let pipe = owned.child.stderr.take().context("no captured stderr")?;
                #[cfg(test)]
                fault.fire("stderr-start")?;
                #[cfg(test)]
                let stderr_fault = fault.clone();
                owned.stderr = Some(Worker::start(
                    format!("{cli}'s stderr reader"),
                    wake.clone(),
                    {
                        let cli = cli.clone();
                        move || {
                            #[cfg(test)]
                            stderr_fault.fire("stderr-read")?;
                            read(pipe).with_context(|| format!("could not read {cli}'s stderr"))
                        }
                    },
                )?);
            }
            if let Some(input) = input {
                #[cfg(test)]
                fault.fire("stdin-pipe")?;
                let mut pipe = owned.child.stdin.take().context("no prompt stdin")?;
                #[cfg(test)]
                fault.fire("stdin-start")?;
                let input = input.to_vec();
                #[cfg(test)]
                let stdin_fault = fault.clone();
                owned.stdin = Some(Worker::start(
                    format!("{cli}'s prompt writer"),
                    wake.clone(),
                    move || {
                        #[cfg(test)]
                        stdin_fault.fire("stdin-write")?;
                        pipe.write_all(&input)
                            .with_context(|| format!("could not write the prompt to {cli}"))
                        // Dropping the pipe closes stdin, including for an empty prompt.
                    },
                )?);
            }
            started = true;
            #[cfg(test)]
            fault.fire("wait")?;
            let status = owned.wait()?;
            let stdout = owned.stdout.as_mut().unwrap().value.take().unwrap();
            let stderr = owned
                .stderr
                .as_mut()
                .and_then(|worker| worker.value.take())
                .unwrap_or_default();
            Ok((status, stdout, stderr))
        })();
        if result.is_err() || interruption.requested() {
            owned.cleanup();
            // Interruption can also arrive during stopping or joining. Preserve
            // the original transport failure unless an interruption was observed.
            if interruption.requested() {
                bail!("interrupted");
            }
        } else {
            owned.completed = true;
        }
        result
    })();
    (interruption.check().and(result), started)
}

struct Execution<'a, T> {
    control: Control<'a>,
    child: Child,
    awakened: mpsc::Receiver<()>,
    stdout: Option<Worker<T>>,
    stderr: Option<Worker<Vec<u8>>>,
    stdin: Option<Worker<()>>,
    completed: bool,
}

impl<T> Execution<'_, T> {
    fn wait(&mut self) -> Result<ExitStatus> {
        let mut status = None;
        loop {
            if self.control.interruption.requested() {
                bail!("interrupted");
            }
            if status.is_none() {
                status = self
                    .child
                    .try_wait()
                    .with_context(|| format!("could not wait for {}", self.control.name))?;
            }
            let stdin_done = self
                .stdin
                .as_mut()
                .map(Worker::poll)
                .transpose()?
                .unwrap_or(true);
            let stdout_done = self.stdout.as_mut().unwrap().poll()?;
            let stderr_done = self
                .stderr
                .as_mut()
                .map(Worker::poll)
                .transpose()?
                .unwrap_or(true);
            if let Some(status) = status
                && stdin_done
                && stdout_done
                && stderr_done
            {
                if self.control.interruption.requested() {
                    bail!("interrupted");
                }
                return Ok(status);
            }
            // Worker completion (including unwind) wakes us immediately.
            // EOF can precede child exit: when all I/O is joined, recheck
            // the child promptly without treating EOF as completion.
            let wait = if stdin_done && stdout_done && stderr_done {
                1
            } else {
                100
            };
            let _ = self.awakened.recv_timeout(Duration::from_millis(wait));
        }
    }

    fn cleanup(&mut self) {
        if self.completed {
            return;
        }
        (self.control.stop)(&mut self.child);
        let _ = self.child.wait();
        // Pipes may still be attached if worker startup failed.
        drop(self.child.stdin.take());
        drop(self.child.stdout.take());
        drop(self.child.stderr.take());
        if let Some(worker) = &mut self.stdin {
            worker.join();
        }
        if let Some(worker) = &mut self.stdout {
            worker.join();
        }
        if let Some(worker) = &mut self.stderr {
            worker.join();
        }
        self.completed = true;
    }
}

impl<T> Drop for Execution<'_, T> {
    fn drop(&mut self) {
        self.cleanup();
    }
}

struct Worker<T> {
    handle: Option<JoinHandle<Result<T>>>,
    completed: Arc<AtomicBool>,
    value: Option<T>,
    name: String,
}

impl<T> Worker<T> {
    fn start(
        name: String,
        wake: mpsc::Sender<()>,
        work: impl FnOnce() -> Result<T> + Send + 'static,
    ) -> Result<Self>
    where
        T: Send + 'static,
    {
        let completed = Arc::new(AtomicBool::new(false));
        let notification = Completion {
            completed: Arc::clone(&completed),
            wake,
        };
        let handle = thread::Builder::new()
            .spawn(move || {
                let _notification = notification;
                work()
            })
            .with_context(|| format!("could not start {name}"))?;
        Ok(Self {
            handle: Some(handle),
            completed,
            value: None,
            name,
        })
    }

    /// Join only a completed worker while supervising the child. Its failure
    /// or panic must initiate cleanup even if the child has not exited yet.
    fn poll(&mut self) -> Result<bool> {
        if self.handle.is_some() && self.completed.load(Ordering::Acquire) {
            self.value = Some(self.handle.take().unwrap().join().map_err(|panic| {
                let cause = panic
                    .downcast_ref::<String>()
                    .map(String::as_str)
                    .or_else(|| panic.downcast_ref::<&str>().copied())
                    .unwrap_or("unknown panic");
                anyhow!("{} panicked: {cause}", self.name)
            })??);
        }
        Ok(self.handle.is_none())
    }

    fn join(&mut self) {
        if let Some(handle) = self.handle.take() {
            let _ = handle.join();
        }
    }
}

/// Dropped both on a normal worker return and while unwinding. Set readiness
/// before waking so the supervisor can join without racing is_finished().
struct Completion {
    completed: Arc<AtomicBool>,
    wake: mpsc::Sender<()>,
}

impl Drop for Completion {
    fn drop(&mut self) {
        self.completed.store(true, Ordering::Release);
        let _ = self.wake.send(());
    }
}