cosca 0.7.0

Unified cross-platform subprocess management: spawning, stdio, process trees, stable identity, and elevation.
Documentation
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
//! A stated-facts [`OsChild`]: what each call answers, in order, and nothing the OS would do. A call
//! past its table panics. It never blocks; a `Running` answer hands out a [`WaitFor`] that the test
//! fires with [`FakeProcess::wake`], and the driver's own blocking call is what a test counts.
//!
//! [`FakeProcess::over`] puts a real [`OsChild`] behind the tables: a call the table has an answer
//! for gets it, and every other call, `os_handle` included, is the real one.

use std::collections::VecDeque;
use std::fmt;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Instant;

#[cfg(any(target_os = "linux", windows))]
use super::child::KillRefusal;
use super::child::{ExitRecord, Foreign, OsChild, PeekOutcome, TryReapOutcome};
use super::{Exit, OsProcess, WaitFor};
use crate::error::Error;
use crate::signal::{Sent, Sig};

/// One scripted answer of [`OsProcess::exited`].
#[derive(Debug, Clone, Copy)]
pub(crate) enum Answer {
    Exited,
    Running,
    /// The look fails with an `Error::Io` of this kind.
    Err(std::io::ErrorKind),
}

/// One scripted answer of [`OsChild::try_reap`].
#[derive(Debug, Clone, Copy)]
pub(crate) enum ReapAnswer {
    Reaped(ExitRecord),
    Running,
    Recheck,
    Foreign(Foreign),
    /// The reap fails with an `Error::Io` of this kind.
    Err(std::io::ErrorKind),
}

/// One scripted answer of [`OsChild::peek`]. A failure is the whole `io::Error`, so a test can name
/// its message.
pub(crate) type PeekAnswer = Result<PeekOutcome, std::io::Error>;

/// One scripted answer of [`OsProcess::signal`]. A failure is the whole `io::Error`, so a test can
/// state a raw errno.
pub(crate) type SignalAnswer = Result<Sent, std::io::Error>;

/// A failed [`SignalAnswer`]: the signal is refused with the raw `errno`.
#[cfg(unix)]
pub(crate) fn failed_signal(errno: i32) -> SignalAnswer {
    Err(std::io::Error::from_raw_os_error(errno))
}

/// Cloning gives another handle on the same tables and the same wake source: the test keeps one,
/// the code under test owns the other.
#[derive(Clone)]
pub(crate) struct FakeProcess(Arc<Shared>);

struct Shared {
    script: Mutex<Script>,
    source: Source,
    /// What answers a call the tables have nothing for. `None`: such a call panics.
    real: Option<Box<dyn OsChild>>,
}

/// What calls consume and record, behind one lock so a `&FakeProcess` is `Sync`.
struct Script {
    /// What [`OsChild::pid`] answers. `None`: the real child's, if there is one, else no pid.
    pid: Option<u32>,
    /// What [`OsChild::kill_refusal`] answers. `None`: the real child's, if there is one; a fake
    /// with none states it or panics.
    #[cfg(any(target_os = "linux", windows))]
    kill_refusal: Option<KillRefusal>,
    exits: VecDeque<Answer>,
    peeks: VecDeque<PeekAnswer>,
    reaps: VecDeque<ReapAnswer>,
    signals: VecDeque<SignalAnswer>,
    /// What a peek answers once `peeks` is empty. `None`: such a call falls through.
    peeks_always: Option<Box<dyn FnMut() -> PeekAnswer + Send>>,
    /// What a reap answers once `reaps` is empty.
    reaps_always: Option<ReapAnswer>,
    /// Calls that the repeated answers took.
    repeats: usize,
    /// `exited` and `try_reap` calls: the looks.
    looks: usize,
    look_times: Vec<Instant>,
    signal_calls: Vec<Sig>,
    on_look: Option<Box<dyn FnMut(usize) + Send>>,
}

impl FakeProcess {
    /// A process that answers `exits` to successive `exited` looks. Every table starts empty, and a
    /// call past its table panics.
    pub(crate) fn new(exits: impl IntoIterator<Item = Answer>) -> Self {
        Self::with(exits, None)
    }

    /// A process that answers from its tables (all empty to start) and, where a table has nothing,
    /// from `real`.
    pub(crate) fn over(real: Box<dyn OsChild>) -> Self {
        Self::with([], Some(real))
    }

    fn with(exits: impl IntoIterator<Item = Answer>, real: Option<Box<dyn OsChild>>) -> Self {
        Self(Arc::new(Shared {
            script: Mutex::new(Script {
                pid: None,
                #[cfg(any(target_os = "linux", windows))]
                kill_refusal: None,
                exits: exits.into_iter().collect(),
                peeks: VecDeque::new(),
                reaps: VecDeque::new(),
                signals: VecDeque::new(),
                peeks_always: None,
                reaps_always: None,
                repeats: 0,
                looks: 0,
                look_times: Vec::new(),
                signal_calls: Vec::new(),
                on_look: None,
            }),
            source: Source::new(),
            real,
        }))
    }

    /// Answer `pid` to [`OsChild::pid`]. Without it, a fake over a real child answers that child's,
    /// and any other has no pid.
    pub(crate) fn with_pid(self, pid: u32) -> Self {
        self.script().pid = Some(pid);
        self
    }

    /// Answer `refusal` to [`OsChild::kill_refusal`]. Without it, a fake over a real child answers
    /// that child's, and any other panics.
    #[cfg(windows)]
    pub(crate) fn with_kill_refusal(self, refusal: KillRefusal) -> Self {
        self.script().kill_refusal = Some(refusal);
        self
    }

    /// Answer `peeks` to successive [`OsChild::peek`] calls.
    pub(crate) fn peeks(self, peeks: impl IntoIterator<Item = PeekAnswer>) -> Self {
        self.script().peeks = peeks.into_iter().collect();
        self
    }

    /// Answer every [`OsChild::peek`] that the `peeks` table has nothing left for with `answer()`,
    /// however many calls there are.
    #[cfg(target_os = "macos")]
    pub(crate) fn peeks_always(self, answer: impl FnMut() -> PeekAnswer + Send + 'static) -> Self {
        self.script().peeks_always = Some(Box::new(answer));
        self
    }

    /// How many scripted [`OsChild::peek`] answers no call has consumed.
    #[cfg(unix)]
    pub(crate) fn peeks_left(&self) -> usize {
        self.script().peeks.len()
    }

    /// Panics unless every scripted peek answer was consumed: a test that counts on a number of
    /// looks asserts it, so a look that stopped happening fails.
    #[cfg(unix)]
    #[track_caller]
    pub(crate) fn assert_peeks_exhausted(&self) {
        let left = self.peeks_left();
        assert_eq!(left, 0, "{left} scripted peek answer(s) were never consumed");
    }

    /// Answer `reaps` to successive [`OsChild::try_reap`] calls.
    pub(crate) fn reaps(self, reaps: impl IntoIterator<Item = ReapAnswer>) -> Self {
        self.script().reaps = reaps.into_iter().collect();
        self
    }

    /// Answer every [`OsChild::try_reap`] that the `reaps` table has nothing left for with `answer`,
    /// however many calls there are.
    #[cfg(target_os = "macos")]
    pub(crate) fn reaps_always(self, answer: ReapAnswer) -> Self {
        self.script().reaps_always = Some(answer);
        self
    }

    /// Stops [`peeks_always`](Self::peeks_always) and [`reaps_always`](Self::reaps_always) from
    /// answering: once the tables are empty, calls go to the real child.
    #[cfg(target_os = "macos")]
    pub(crate) fn no_repeats(self) -> Self {
        self.script().peeks_always = None;
        self.script().reaps_always = None;
        self
    }

    /// How many calls [`peeks_always`](Self::peeks_always) and [`reaps_always`](Self::reaps_always)
    /// answered.
    #[cfg(target_os = "macos")]
    pub(crate) fn repeats(&self) -> usize {
        self.script().repeats
    }

    /// Answer `signals` to successive [`OsProcess::signal`] calls.
    pub(crate) fn signals(self, signals: impl IntoIterator<Item = SignalAnswer>) -> Self {
        self.script().signals = signals.into_iter().collect();
        self
    }

    /// Fire the [`WaitFor`] that `Running` answers hand out; it stays fired, except that each
    /// `Running` answer of [`OsChild::try_reap`] hands out an unfired one.
    pub(crate) fn wake(&self) {
        self.0.source.fire();
    }

    /// How many looks were made: calls of `exited` and of `try_reap`.
    pub(crate) fn looks(&self) -> usize {
        self.script().looks
    }

    /// The `wait::now()` of each look, taken after its `on_look` hook ran.
    pub(crate) fn look_times(&self) -> Vec<Instant> {
        self.script().look_times.clone()
    }

    /// Each signal sent, in order.
    pub(crate) fn signal_calls(&self) -> Vec<Sig> {
        self.script().signal_calls.clone()
    }

    /// Run `hook` with the index of each look, at the start of the look. It runs with no lock held,
    /// so it may park, and other calls are answered meanwhile.
    pub(crate) fn on_look(&self, hook: impl FnMut(usize) + Send + 'static) {
        self.script().on_look = Some(Box::new(hook));
    }

    /// The lock, whether or not a hook panicked under it.
    fn script(&self) -> MutexGuard<'_, Script> {
        self.0.script.lock().unwrap_or_else(PoisonError::into_inner)
    }

    /// Count a look and run its hook.
    fn begin_look(&self) {
        let (index, hook) = {
            let mut script = self.script();
            let index = script.looks;
            script.looks += 1;
            (index, script.on_look.take())
        };
        if let Some(mut hook) = hook {
            hook(index);
            let mut script = self.script();
            if script.on_look.is_none() {
                script.on_look = Some(hook);
            }
        }
        self.script().look_times.push(crate::wait::now());
    }
}

impl fmt::Debug for FakeProcess {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let script = self.script();
        f.debug_struct("FakeProcess")
            .field("exits", &script.exits)
            .field("looks", &script.looks)
            .field("repeats", &script.repeats)
            .finish_non_exhaustive()
    }
}

impl OsProcess for FakeProcess {
    fn signal(&self, sig: Sig) -> Result<Sent, Error> {
        let scripted = {
            let mut script = self.script();
            script.signal_calls.push(sig);
            script.signals.pop_front()
        };
        match (scripted, &self.0.real) {
            (Some(Ok(sent)), _) => Ok(sent),
            (Some(Err(error)), _) => Err(Error::Io(error)),
            (None, Some(real)) => real.signal(sig),
            (None, None) => panic!("FakeProcess: a signal was sent past the scripted answers"),
        }
    }

    fn exited(&self) -> Result<Exit<'_>, Error> {
        self.begin_look();
        let scripted = self.script().exits.pop_front();
        match (scripted, &self.0.real) {
            (Some(Answer::Exited), _) => Ok(Exit::Exited),
            (Some(Answer::Running), _) => Ok(Exit::Running(self.0.source.wait_for())),
            (Some(Answer::Err(kind)), _) => Err(Error::Io(kind.into())),
            (None, Some(real)) => real.exited(),
            (None, None) => panic!("FakeProcess: a look was made past the scripted answers"),
        }
    }

    #[cfg(any(target_os = "linux", windows))]
    fn os_handle(&self) -> super::child::OsHandle<'_> {
        match &self.0.real {
            Some(real) => real.os_handle(),
            None => self.0.source.os_handle(),
        }
    }
}

impl OsChild for FakeProcess {
    fn pid(&self) -> Option<u32> {
        let stated = self.script().pid;
        stated.or_else(|| self.0.real.as_ref().and_then(|real| real.pid()))
    }

    #[cfg(any(target_os = "linux", windows))]
    fn kill_refusal(&self) -> KillRefusal {
        let stated = self.script().kill_refusal;
        match (stated, &self.0.real) {
            (Some(refusal), _) => refusal,
            (None, Some(real)) => real.kill_refusal(),
            (None, None) => panic!("FakeProcess: a kill refusal was asked past the stated facts"),
        }
    }

    fn peek(&self) -> Result<PeekOutcome, Error> {
        let scripted = {
            let mut script = self.script();
            script.peeks.pop_front().or_else(|| {
                let repeated = script.peeks_always.as_mut().map(|always| always());
                script.repeats += usize::from(repeated.is_some());
                repeated
            })
        };
        match (scripted, &self.0.real) {
            (Some(Ok(outcome)), _) => Ok(outcome),
            (Some(Err(error)), _) => Err(Error::Io(error)),
            (None, Some(real)) => real.peek(),
            (None, None) => panic!("FakeProcess: a peek was made past the scripted answers"),
        }
    }

    fn try_reap(&self) -> Result<TryReapOutcome<'_>, Error> {
        self.begin_look();
        let scripted = {
            let mut script = self.script();
            script.reaps.pop_front().or_else(|| {
                let repeated = script.reaps_always;
                script.repeats += usize::from(repeated.is_some());
                repeated
            })
        };
        match (scripted, &self.0.real) {
            (Some(ReapAnswer::Reaped(record)), _) => Ok(TryReapOutcome::Reaped(record)),
            (Some(ReapAnswer::Running), _) => {
                // Each reap that runs is a new wait: one holder's wake is not the next one's.
                self.0.source.reset();
                Ok(TryReapOutcome::Running(self.0.source.wait_for()))
            }
            (Some(ReapAnswer::Recheck), _) => Ok(TryReapOutcome::Recheck),
            (Some(ReapAnswer::Foreign(foreign)), _) => Ok(TryReapOutcome::Foreign(foreign)),
            (Some(ReapAnswer::Err(kind)), _) => Err(Error::Io(kind.into())),
            (None, Some(real)) => real.try_reap(),
            (None, None) => panic!("FakeProcess: a reap was made past the scripted answers"),
        }
    }
}

/// What a `Running` answer hands out, and the way a test fires it.
#[cfg(unix)]
struct Source {
    rx: std::io::PipeReader,
    tx: std::io::PipeWriter,
}

#[cfg(unix)]
impl Source {
    fn new() -> Self {
        let (rx, tx) = std::io::pipe().expect("FakeProcess: pipe");
        Self { rx, tx }
    }

    fn fire(&self) {
        use std::io::Write;
        (&self.tx).write_all(&[1]).expect("FakeProcess: fire the pipe");
    }

    /// Unfire it: read what `fire` wrote.
    fn reset(&self) {
        use std::io::Read;
        use std::os::fd::AsFd;
        while crate::os_process::poll::is_readable(self.rx.as_fd()).expect("FakeProcess: poll the pipe") {
            (&self.rx).read_exact(&mut [0]).expect("FakeProcess: unfire the pipe");
        }
    }

    fn wait_for(&self) -> WaitFor<'_> {
        use std::os::fd::AsFd;
        WaitFor::Readable(self.rx.as_fd())
    }

    #[cfg(target_os = "linux")]
    fn os_handle(&self) -> std::os::fd::BorrowedFd<'_> {
        use std::os::fd::AsFd;
        self.rx.as_fd()
    }
}

#[cfg(windows)]
struct Source(std::os::windows::io::OwnedHandle);

#[cfg(windows)]
impl Source {
    fn new() -> Self {
        Self(crate::os_process::windows::cancel::new_cancel_event().expect("FakeProcess: create the event"))
    }

    fn fire(&self) {
        crate::os_process::windows::cancel::signal_cancel(&self.0);
    }

    /// Unfire it.
    fn reset(&self) {
        use std::os::windows::io::AsRawHandle;
        // SAFETY: the event is alive for the call.
        unsafe {
            windows::Win32::System::Threading::ResetEvent(windows::Win32::Foundation::HANDLE(self.0.as_raw_handle()))
        }
        .expect("FakeProcess: reset the event");
    }

    fn wait_for(&self) -> WaitFor<'_> {
        WaitFor::Signalled(self.os_handle())
    }

    fn os_handle(&self) -> std::os::windows::io::BorrowedHandle<'_> {
        use std::os::windows::io::AsHandle;
        self.0.as_handle()
    }
}