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};
8use std::sync::Arc;
9
10use oxdock_diagnostics::Diagnostic;
11use oxdock_parser::KEYWORD_EXIT;
12
13/// Pipeline exit request carrying the numeric code. Produced by `EXIT`,
14/// re-raised by `REMOTE` when the guest exits, and mapped to the process
15/// exit status by the CLI.
16///
17/// Carries an optional chained source: when an exit code attaches to a
18/// diagnostic that already has a cause, the prior cause rides behind
19/// the request instead of being dropped, so `exit_code_of_diag` finds the
20/// code first while causal inspection still reaches the cause.
21#[derive(Debug, Clone)]
22pub struct ExitRequest {
23    code: i64,
24    source: Option<Arc<dyn std::error::Error + Send + Sync>>,
25}
26
27impl ExitRequest {
28    /// Bare exit request with no chained cause.
29    pub fn new(code: i64) -> Self {
30        Self { code, source: None }
31    }
32
33    /// Exit request chained over a prior cause. The code stays the
34    /// outermost typed node; the cause remains reachable through
35    /// `Error::source`.
36    pub fn with_source(code: i64, source: Arc<dyn std::error::Error + Send + Sync>) -> Self {
37        Self {
38            code,
39            source: Some(source),
40        }
41    }
42
43    /// Numeric exit code.
44    pub fn code(&self) -> i64 {
45        self.code
46    }
47}
48
49impl PartialEq for ExitRequest {
50    fn eq(&self, other: &Self) -> bool {
51        self.code == other.code
52    }
53}
54
55impl Eq for ExitRequest {}
56
57impl Display for ExitRequest {
58    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
59        write!(f, "{KEYWORD_EXIT} requested with code {}", self.code)
60    }
61}
62
63impl std::error::Error for ExitRequest {
64    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
65        self.source
66            .as_deref()
67            .map(|cause| cause as &(dyn std::error::Error + 'static))
68    }
69}
70
71/// Outermost `EXIT` code in a `Diagnostic` source chain, if any. Walks
72/// `std::error::Error::source` links looking for `ExitRequest` or the
73/// keyed exit-requested diagnostic. Snapshot and step wrappers attach
74/// the request via `with_source`, so the code survives without
75/// flattening the message chain.
76pub fn exit_code_of_diag(err: &Diagnostic) -> Option<i64> {
77    let mut current: Option<&(dyn std::error::Error + 'static)> =
78        Some(err as &(dyn std::error::Error + 'static));
79    while let Some(node) = current {
80        if let Some(exit) = node.downcast_ref::<ExitRequest>() {
81            return Some(exit.code());
82        }
83        if let Some(diag) = node.downcast_ref::<Diagnostic>()
84            && let Some(code) = super::diagnostics::eval_exit_requested_code(diag)
85        {
86            return Some(code);
87        }
88        current = node.source();
89    }
90    None
91}
92
93/// Numeric code for a platform wait status, when the platform reports
94/// one. Signal terminations yield `None`; callers fall back to the
95/// platform `Display` for that case only, never hardcoding either
96/// rendering in templates or tests.
97pub fn exit_status_code(status: &std::process::ExitStatus) -> Option<i32> {
98    status.code()
99}
100
101/// Single owner for wait-status rendering in diagnostics. Prefers the
102/// numeric code when the platform reports one, otherwise uses the
103/// platform `Display` (signal termination). Templates store the
104/// numeric code as a field; tests pin the numeric prefix only.
105pub fn describe_exit_status(status: &std::process::ExitStatus) -> String {
106    match exit_status_code(status) {
107        Some(code) => code.to_string(),
108        None => status.to_string(),
109    }
110}
111
112#[cfg(test)]
113mod tests {
114    use super::{ExitRequest, exit_code_of_diag};
115    use oxdock_diagnostics::Diagnostic;
116    use std::sync::Arc;
117
118    #[test]
119    fn display_matches_historic_message() {
120        assert_eq!(
121            ExitRequest::new(3).to_string(),
122            "EXIT requested with code 3"
123        );
124    }
125
126    #[test]
127    fn diag_finds_code_through_source_chain() {
128        let inner = Diagnostic::new(
129            "dsl.eval.async_cancelled",
130            "ASYNC task cancelled".to_string(),
131            Diagnostic::make_fields(&[]),
132        )
133        .with_source(Arc::new(ExitRequest::new(7)));
134        assert_eq!(exit_code_of_diag(&inner), Some(7));
135    }
136
137    #[test]
138    fn chained_exit_keeps_code_and_prior_cause() {
139        use std::error::Error as _;
140        let cause = Arc::new(std::io::Error::new(std::io::ErrorKind::NotFound, "gone"));
141        let exit = ExitRequest::with_source(7, cause);
142        assert_eq!(exit.code(), 7);
143        let prior = exit
144            .source()
145            .expect("prior cause rides behind the request")
146            .downcast_ref::<std::io::Error>()
147            .expect("prior cause keeps its type");
148        assert_eq!(prior.kind(), std::io::ErrorKind::NotFound);
149        let diag = Diagnostic::new(
150            "dsl.eval.async_cancelled",
151            "ASYNC task cancelled".to_string(),
152            Diagnostic::make_fields(&[]),
153        )
154        .with_source(Arc::new(exit));
155        assert_eq!(exit_code_of_diag(&diag), Some(7));
156        assert!(
157            diag.source()
158                .and_then(|cause| cause.downcast_ref::<ExitRequest>())
159                .is_some()
160        );
161        assert_eq!(
162            ExitRequest::new(7),
163            ExitRequest::with_source(
164                7,
165                Arc::new(std::io::Error::new(std::io::ErrorKind::NotFound, "gone"))
166            )
167        );
168    }
169
170    #[test]
171    fn diag_none_without_exit() {
172        let diag = Diagnostic::new(
173            "dsl.eval.async_cancelled",
174            "ASYNC task cancelled".to_string(),
175            Diagnostic::make_fields(&[]),
176        );
177        assert_eq!(exit_code_of_diag(&diag), None);
178    }
179
180    #[test]
181    fn keyed_exit_requested_carries_code_without_source() {
182        use std::error::Error as _;
183        let diag = crate::exec::diagnostics::eval_exit_requested(7);
184        assert_eq!(diag.key(), "dsl.eval.exit_requested");
185        assert_eq!(diag.message(), "EXIT requested with code 7");
186        assert_eq!(diag.fields().get("code"), Some(&"7".to_string()));
187        assert!(
188            diag.source().is_none(),
189            "no identical source to duplicate rendering"
190        );
191        assert_eq!(exit_code_of_diag(&diag), Some(7));
192    }
193
194    #[test]
195    fn describe_prefers_numeric_code() {
196        let status = oxdock_sys_test_utils::exit_status_from_code(3);
197        assert_eq!(super::describe_exit_status(&status), "3");
198        assert_eq!(super::exit_status_code(&status), Some(3));
199    }
200}