unityrs-testkit 1.1.0

Synthetic Unity files built in code, for unityrs's own tests and the CLI's test hooks; not a stable API. Never game data.
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
//! One closure owns the WHOLE scene: servers, FIFOs, scratch and engine. An
//! outside SIGKILL restarts that closure, even when the killed child caused an
//! assertion or a broken pipe. Deliberate kills are explicit and never retried.
//! Spawn and reap on the calling, long-lived thread: Linux PDEATHSIG follows
//! the spawning thread. Every child has its own process group; cleanup kills
//! the group before reaping the child, including namespace wrappers/services.
use crate::{
    guard::{self, DEADLOCK_GUARD},
    scratch::Scratch,
};
use std::{
    fs::{File, OpenOptions},
    io::{self, Read},
    os::unix::{fs::OpenOptionsExt, process::CommandExt},
    path::{Path, PathBuf},
    process::{Child, ChildStderr, ChildStdin, ChildStdout, Command, ExitStatus},
    sync::mpsc::{self, Receiver},
    thread::JoinHandle,
    time::{Duration, Instant},
};

#[derive(Clone, Copy)]
pub struct Live(usize);
struct Owned {
    /// `None` for an adopted descendant ([`Scene::adopt`]), reaped by pid.
    child: Option<Child>,
    pid: u32,
    status: Option<ExitStatus>,
    deliberate: bool,
    service: bool,
    group: bool,
}
pub struct Scene {
    pub scratch: Scratch,
    children: Vec<Owned>,
    nested: bool,
}
/// Rebuild the complete scene after outside kills. Cleanup also runs on panic.
///
/// # Panics
/// Repeated outside SIGKILL or a scene assertion failure.
pub fn scene<T>(mut run: impl FnMut(&mut Scene) -> io::Result<T>) -> io::Result<T> {
    for attempt in 1..=super::KILLED_RUNS {
        let mut scene = Scene {
            scratch: Scratch::new("scene"),
            children: Vec::new(),
            nested: std::env::var_os("UNITYRS_TEST_INHERIT_GROUP").is_some(),
        };
        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| run(&mut scene)));
        // Observe endings before deliberate cleanup can disguise an outside kill.
        let (outside, unfinished) = scene.finish()?;
        if outside {
            assert!(
                attempt < super::KILLED_RUNS,
                "scene killed by SIGKILL on every run: the system ended it from outside"
            );
            continue;
        }
        return match result {
            Ok(Ok(_)) if unfinished => Err(io::Error::other(
                "scene returned while its engine was still alive",
            )),
            Ok(value) => value,
            Err(panic) => std::panic::resume_unwind(panic),
        };
    }
    unreachable!("the final killed scene fails above")
}
/// Spawn an engine or service in the current scene. Use `service=true` only
/// for a process intentionally retained until scene cleanup. All streams must
/// be drained by the caller when piped; `drain` supplies a continuous reader.
pub fn live(scene: &mut Scene, cmd: &mut Command, service: bool) -> io::Result<Live> {
    if !cmd.get_envs().any(|(k, _)| k == crate::scratch::VAR) {
        cmd.env(crate::scratch::VAR, scene.scratch.path());
    }
    if !scene.nested {
        cmd.process_group(0);
    }
    cmd.env("UNITYRS_TEST_INHERIT_GROUP", "1");
    let child = cmd
        .spawn()
        .map_err(|e| io::Error::new(e.kind(), format!("scene spawn: {e}")))?;
    let token = Live(scene.children.len());
    scene.children.push(Owned {
        pid: child.id(),
        child: Some(child),
        status: None,
        deliberate: false,
        service,
        group: !scene.nested,
    });
    Ok(token)
}
impl Scene {
    #[must_use]
    pub fn id(&self, live: Live) -> u32 {
        self.children[live.0].pid
    }
    /// The child's piped stdin, to write to. The scene hands out only stdio
    /// handles, never the `Child`: observing, killing and reaping go through
    /// the scene, so no test can reap a root whose group cleanup then kills.
    pub fn stdin(&mut self, live: Live) -> Option<&mut ChildStdin> {
        self.children[live.0].child.as_mut()?.stdin.as_mut()
    }
    /// Take the piped stdin (dropping it closes the child's stdin).
    pub fn take_stdin(&mut self, live: Live) -> Option<ChildStdin> {
        self.children[live.0].child.as_mut()?.stdin.take()
    }
    /// Take the piped stdout, for [`drain`].
    pub fn take_stdout(&mut self, live: Live) -> Option<ChildStdout> {
        self.children[live.0].child.as_mut()?.stdout.take()
    }
    /// Take the piped stderr, for [`drain`].
    pub fn take_stderr(&mut self, live: Live) -> Option<ChildStderr> {
        self.children[live.0].child.as_mut()?.stderr.take()
    }
    /// Adopt a descendant re-parented to this process (a Linux subreaper's
    /// orphan): the scene observes, reaps and on cleanup kills it as one of
    /// its own, so its outside SIGKILL is the scene's retry case. Its group
    /// is never signalled, since it may be this process's own.
    ///
    /// # Errors
    /// `ECHILD` when `pid` is not (yet) this process's child.
    pub fn adopt(&mut self, pid: u32, service: bool) -> io::Result<Live> {
        sys::exited(pid).map_err(|e| io::Error::new(e.kind(), format!("scene adopt: {e}")))?;
        let token = Live(self.children.len());
        self.children.push(Owned {
            child: None,
            pid,
            status: None,
            deliberate: false,
            service,
            group: false,
        });
        Ok(token)
    }
    /// Observe/reap through the scene so descendants are killed before the
    /// root pid can be recycled.
    pub fn running(&mut self, live: Live) -> io::Result<bool> {
        let owned = &mut self.children[live.0];
        if owned.status.is_none()
            && sys::exited(owned.pid)
                .map_err(|e| io::Error::new(e.kind(), format!("scene waitid: {e}")))?
        {
            if owned.group {
                sys::cleanup_exited_group(owned.pid)?;
            }
            owned.status = Some(match &mut owned.child {
                Some(child) => child.wait()?,
                None => sys::reap(owned.pid)?,
            });
        }
        Ok(owned.status.is_none())
    }
    /// Wait for a filesystem mark (a file another process creates) while
    /// watching `watched`. One that ends first returns `BrokenPipe` at once,
    /// so an outside SIGKILL reaches scene arbitration, not the guard.
    ///
    /// # Panics
    /// When the mark outlasts the testkit deadlock guard.
    pub fn mark(&mut self, path: &Path, watched: &[Live]) -> io::Result<()> {
        let deadline = Instant::now() + DEADLOCK_GUARD;
        while !path.exists() {
            for live in watched {
                if !self.running(*live)? {
                    return Err(io::Error::new(
                        io::ErrorKind::BrokenPipe,
                        format!("scene child ended before mark {}", path.display()),
                    ));
                }
            }
            assert!(
                Instant::now() < deadline,
                "deadlock guard: scene mark {} missing",
                path.display()
            );
            std::thread::sleep(Duration::from_millis(1));
        }
        Ok(())
    }
    pub fn signal(&mut self, live: Live, signal: i32) -> io::Result<()> {
        if signal == libc::SIGKILL {
            return Err(io::ErrorKind::InvalidInput.into());
        }
        if !self.running(live)? {
            return Err(io::ErrorKind::NotFound.into());
        }
        sys::signal(self.id(live), signal, false)
    }
    /// A test's deliberate SIGKILL never counts as an outside kill.
    pub fn kill(&mut self, live: Live) -> io::Result<()> {
        if !self.running(live)? {
            return Ok(());
        }
        let owned = &mut self.children[live.0];
        owned.deliberate = true;
        sys::signal(owned.pid, libc::SIGKILL, owned.group)
    }
    /// # Panics
    /// When the child outlasts the testkit deadlock guard.
    pub fn wait(&mut self, live: Live) -> io::Result<ExitStatus> {
        let deadline = Instant::now() + DEADLOCK_GUARD;
        loop {
            if let Some(status) = self.children[live.0].status {
                return Ok(status);
            }
            if !self.running(live)? {
                continue;
            }
            assert!(
                Instant::now() < deadline,
                "deadlock guard: child did not exit"
            );
            std::thread::sleep(Duration::from_millis(1));
        }
    }
    fn finish(&mut self) -> io::Result<(bool, bool)> {
        let mut outside = false;
        let mut unfinished = false;
        for i in 0..self.children.len() {
            let _ = self.running(Live(i))?;
            if self.children[i].status.is_none() {
                unfinished |= !self.children[i].service;
                // Failure paths must not wait ten minutes for a held engine.
                self.kill(Live(i))?;
            }
            let status = self.wait(Live(i))?;
            outside |= super::killed(status) && !self.children[i].deliberate;
        }
        Ok((outside, unfinished))
    }
}
impl Drop for Scene {
    fn drop(&mut self) {
        for owned in &mut self.children {
            if owned.status.is_none() {
                // Before reaping, this pid/group cannot name an unrelated run.
                let _ = sys::signal(owned.pid, libc::SIGKILL, owned.group);
                let _ = match &mut owned.child {
                    Some(child) => child.wait(),
                    None => sys::reap(owned.pid),
                };
            }
        }
    }
}
/// Continuously drain a pipe before waiting for the next protocol event.
#[must_use]
pub fn drain(mut input: impl Read + Send + 'static) -> (Receiver<Vec<u8>>, JoinHandle<()>) {
    let (tx, rx) = mpsc::channel();
    let thread = std::thread::spawn(move || {
        loop {
            let mut bytes = vec![0; 4096];
            match input.read(&mut bytes) {
                Ok(0) => break,
                Ok(n) => {
                    bytes.truncate(n);
                    // Dropping the observer must not close the child's pipe or
                    // turn its later diagnostics into EPIPE. Drain until EOF even
                    // when the scene only wanted an early protocol observation.
                    let _ = tx.send(bytes);
                }
                Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
                Err(_) => break,
            }
        }
    });
    (rx, thread)
}
/// A fresh scene-local FIFO opened before engine spawn. Its dedicated reader
/// drains continuously, preserving partial lines; no stale file can satisfy a
/// later scene's wait. Drop ends the reader without waiting for engine exit.
pub struct Fifo {
    path: PathBuf,
    rx: Receiver<String>,
    stop: std::sync::Arc<std::sync::atomic::AtomicBool>,
    /// Reads the reader found the FIFO empty: [`Self::line_while`] waits for
    /// two more once its child has ended, so every line the child wrote has
    /// been sent before it calls the FIFO done.
    empty: std::sync::Arc<std::sync::atomic::AtomicU64>,
    thread: Option<JoinHandle<()>>,
}
impl Fifo {
    pub fn new(scene: &Scene, name: &str) -> io::Result<Self> {
        let path = scene.scratch.path().join(name);
        sys::fifo(&path).map_err(|e| io::Error::new(e.kind(), format!("scene mkfifo: {e}")))?;
        let mut file: File = OpenOptions::new()
            .read(true)
            .write(true)
            .custom_flags(libc::O_NONBLOCK | libc::O_CLOEXEC)
            .open(&path)?;
        let stop = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
        let stopping = stop.clone();
        let empty = std::sync::Arc::new(std::sync::atomic::AtomicU64::new(0));
        let emptied = empty.clone();
        let (tx, rx) = mpsc::channel();
        let thread = std::thread::spawn(move || {
            let mut pending = Vec::new();
            let mut bytes = [0; 4096];
            while !stopping.load(std::sync::atomic::Ordering::Acquire) {
                match file.read(&mut bytes) {
                    Ok(n) => {
                        for b in &bytes[..n] {
                            if *b == b'\n' {
                                if tx
                                    .send(String::from_utf8_lossy(&pending).into_owned())
                                    .is_err()
                                {
                                    return;
                                }
                                pending.clear();
                            } else {
                                pending.push(*b);
                            }
                        }
                    }
                    Err(e) if e.kind() == io::ErrorKind::WouldBlock => {
                        emptied.fetch_add(1, std::sync::atomic::Ordering::Release);
                        std::thread::sleep(Duration::from_millis(1));
                    }
                    Err(e) if e.kind() == io::ErrorKind::Interrupted => {}
                    Err(_) => return,
                }
            }
        });
        Ok(Self {
            path,
            rx,
            stop,
            empty,
            thread: Some(thread),
        })
    }
    #[must_use]
    pub fn path(&self) -> &Path {
        &self.path
    }
    #[must_use]
    pub fn line(&self) -> String {
        guard::recv(&self.rx, "fresh lifecycle FIFO line")
    }
    /// Wait for a trace while also observing child death. An outside SIGKILL
    /// returns to scene arbitration immediately instead of spending the guard
    /// waiting on a FIFO whose read/write keeper intentionally prevents EOF.
    /// A line the child wrote before it ended is still returned: the reader
    /// polls, so it can lag an exit, and calling the FIFO done then lost a
    /// stopped engine's last trace (URS-33).
    ///
    /// # Panics
    /// When no line arrives before the testkit deadlock guard.
    pub fn line_while(&self, scene: &mut Scene, live: Live) -> io::Result<String> {
        let deadline = Instant::now() + DEADLOCK_GUARD;
        loop {
            match self.rx.recv_timeout(Duration::from_millis(1)) {
                Ok(text) => return Ok(text),
                Err(mpsc::RecvTimeoutError::Disconnected) => {
                    return Err(io::ErrorKind::BrokenPipe.into());
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {}
            }
            if !scene.running(live)? {
                return self.rest(deadline);
            }
            assert!(
                Instant::now() < deadline,
                "deadlock guard: lifecycle FIFO line missing"
            );
        }
    }
    /// A line its ended writer left, or `BrokenPipe` when there is none,
    /// within the caller's `deadline`. The read that bumps the empty count to
    /// `seen + 1` may have started before the exit; the one after it started
    /// later, so it found every byte the writer wrote, and the reader sent
    /// their lines before it.
    fn rest(&self, deadline: Instant) -> io::Result<String> {
        use std::sync::atomic::Ordering;
        let seen = self.empty.load(Ordering::Acquire);
        while self.empty.load(Ordering::Acquire) < seen + 2 {
            match self.rx.recv_timeout(Duration::from_millis(1)) {
                Ok(text) => return Ok(text),
                Err(mpsc::RecvTimeoutError::Disconnected) => break,
                Err(mpsc::RecvTimeoutError::Timeout) => {}
            }
            assert!(
                Instant::now() < deadline,
                "deadlock guard: FIFO reader after its writer ended"
            );
        }
        self.rx
            .try_recv()
            .map_err(|_| io::ErrorKind::BrokenPipe.into())
    }
}
impl Drop for Fifo {
    fn drop(&mut self) {
        self.stop.store(true, std::sync::atomic::Ordering::Release);
        if let Some(thread) = self.thread.take() {
            let _ = thread.join();
        }
    }
}
#[path = "sys.rs"]
mod sys;

#[cfg(test)]
#[path = "live_tests.rs"]
mod tests;