Skip to main content

oxdock_core/exec/
exit.rs

1//! Typed EXIT request: `EXIT <code>` aborts the pipeline, and the code
2//! must survive every transport it crosses (anyhow chains, `ASYNC` thread
3//! boundaries, the `REMOTE` wire protocol) so the CLI can relay it to the
4//! process exit status. The display string matches the historic message so
5//! existing assertions keep passing; new code should match on the type.
6
7use std::fmt::{Display, Formatter, Result as FmtResult};
8
9/// Pipeline exit request carrying the numeric code. Produced by `EXIT`,
10/// re-raised by `REMOTE` when the guest exits, and mapped to the process
11/// exit status by the CLI.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub struct ExitRequest(pub i64);
14
15impl Display for ExitRequest {
16    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
17        write!(f, "EXIT requested with code {}", self.0)
18    }
19}
20
21impl std::error::Error for ExitRequest {}
22
23/// Outermost `EXIT` code in the chain, if any. Relays preserve the code
24/// unchanged, so first-found and last-found agree; outermost wins because
25/// it is the most recent relay decision.
26pub fn exit_code_of(err: &anyhow::Error) -> Option<i64> {
27    err.chain()
28        .find_map(|cause| cause.downcast_ref::<ExitRequest>().map(|exit| exit.0))
29}
30
31#[cfg(test)]
32mod tests {
33    use super::{ExitRequest, exit_code_of};
34
35    #[test]
36    fn display_matches_historic_message() {
37        assert_eq!(ExitRequest(3).to_string(), "EXIT requested with code 3");
38    }
39
40    #[test]
41    fn finds_code_through_context_wrappers() {
42        let err = anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' failed");
43        assert_eq!(exit_code_of(&err), Some(3));
44    }
45
46    #[test]
47    fn none_without_exit() {
48        let err = anyhow::anyhow!("boom").context("wrapped");
49        assert_eq!(exit_code_of(&err), None);
50    }
51}