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` 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 the chain, if any. Relays preserve the code
72/// unchanged, so first-found and last-found agree; outermost wins because
73/// it is the most recent relay decision. Matches both the typed
74/// `ExitRequest` carrier and the keyed `dsl.eval.exit_requested`
75/// diagnostic (code field, no source so `{err:#}` renders once).
76pub fn exit_code_of(err: &anyhow::Error) -> Option<i64> {
77    err.chain().find_map(|cause| {
78        if let Some(exit) = cause.downcast_ref::<ExitRequest>() {
79            return Some(exit.code());
80        }
81        if let Some(diag) = cause.downcast_ref::<Diagnostic>() {
82            return super::diagnostics::eval_exit_requested_code(diag);
83        }
84        None
85    })
86}
87
88/// Outermost `EXIT` code in a `Diagnostic` source chain, if any.
89/// Mirrors [`exit_code_of`] for the Diagnostic-native path: walks
90/// `std::error::Error::source` links looking for `ExitRequest` or the
91/// keyed exit-requested diagnostic. Snapshot and step wrappers attach
92/// the request via `with_source`, so the code survives without
93/// flattening the message chain.
94pub fn exit_code_of_diag(err: &Diagnostic) -> Option<i64> {
95    let mut current: Option<&(dyn std::error::Error + 'static)> =
96        Some(err as &(dyn std::error::Error + 'static));
97    while let Some(node) = current {
98        if let Some(exit) = node.downcast_ref::<ExitRequest>() {
99            return Some(exit.code());
100        }
101        if let Some(diag) = node.downcast_ref::<Diagnostic>()
102            && let Some(code) = super::diagnostics::eval_exit_requested_code(diag)
103        {
104            return Some(code);
105        }
106        current = node.source();
107    }
108    None
109}
110
111/// Numeric code for a platform wait status, when the platform reports
112/// one. Signal terminations yield `None`; callers fall back to the
113/// platform `Display` for that case only, never hardcoding either
114/// rendering in templates or tests.
115pub fn exit_status_code(status: &std::process::ExitStatus) -> Option<i32> {
116    status.code()
117}
118
119/// Single owner for wait-status rendering in diagnostics. Prefers the
120/// numeric code when the platform reports one, otherwise uses the
121/// platform `Display` (signal termination). Templates store the
122/// numeric code as a field; tests pin the numeric prefix only.
123pub fn describe_exit_status(status: &std::process::ExitStatus) -> String {
124    match exit_status_code(status) {
125        Some(code) => code.to_string(),
126        None => status.to_string(),
127    }
128}
129
130#[cfg(test)]
131mod tests {
132    use super::{ExitRequest, exit_code_of, exit_code_of_diag};
133    use oxdock_diagnostics::Diagnostic;
134    use std::sync::Arc;
135
136    #[test]
137    fn display_matches_historic_message() {
138        assert_eq!(
139            ExitRequest::new(3).to_string(),
140            "EXIT requested with code 3"
141        );
142    }
143
144    #[test]
145    fn finds_code_through_context_wrappers() {
146        let err = anyhow::Error::new(ExitRequest::new(3)).context("REMOTE 'prod' failed");
147        assert_eq!(exit_code_of(&err), Some(3));
148    }
149
150    #[test]
151    fn none_without_exit() {
152        let err = anyhow::anyhow!("boom").context("wrapped");
153        assert_eq!(exit_code_of(&err), None);
154    }
155
156    #[test]
157    fn diag_finds_code_through_source_chain() {
158        let inner = Diagnostic::new(
159            "dsl.eval.async_cancelled",
160            "ASYNC task cancelled".to_string(),
161            Diagnostic::make_fields(&[]),
162        )
163        .with_source(Arc::new(ExitRequest::new(7)));
164        assert_eq!(exit_code_of_diag(&inner), Some(7));
165    }
166
167    #[test]
168    fn chained_exit_keeps_code_and_prior_cause() {
169        use std::error::Error as _;
170        let cause = Arc::new(std::io::Error::new(std::io::ErrorKind::NotFound, "gone"));
171        let exit = ExitRequest::with_source(7, cause);
172        assert_eq!(exit.code(), 7);
173        let prior = exit
174            .source()
175            .expect("prior cause rides behind the request")
176            .downcast_ref::<std::io::Error>()
177            .expect("prior cause keeps its type");
178        assert_eq!(prior.kind(), std::io::ErrorKind::NotFound);
179        let diag = Diagnostic::new(
180            "dsl.eval.async_cancelled",
181            "ASYNC task cancelled".to_string(),
182            Diagnostic::make_fields(&[]),
183        )
184        .with_source(Arc::new(exit));
185        assert_eq!(exit_code_of_diag(&diag), Some(7));
186        assert!(
187            diag.source()
188                .and_then(|cause| cause.downcast_ref::<ExitRequest>())
189                .is_some()
190        );
191        let carried = exit_code_of(&anyhow::Error::new(diag));
192        assert_eq!(carried, Some(7));
193        assert_eq!(
194            ExitRequest::new(7),
195            ExitRequest::with_source(
196                7,
197                Arc::new(std::io::Error::new(std::io::ErrorKind::NotFound, "gone"))
198            )
199        );
200    }
201
202    #[test]
203    fn diag_none_without_exit() {
204        let diag = Diagnostic::new(
205            "dsl.eval.async_cancelled",
206            "ASYNC task cancelled".to_string(),
207            Diagnostic::make_fields(&[]),
208        );
209        assert_eq!(exit_code_of_diag(&diag), None);
210    }
211
212    #[test]
213    fn keyed_exit_requested_carries_code_without_source() {
214        use std::error::Error as _;
215        let diag = crate::exec::diagnostics::eval_exit_requested(7);
216        assert_eq!(diag.key(), "dsl.eval.exit_requested");
217        assert_eq!(diag.message(), "EXIT requested with code 7");
218        assert_eq!(diag.fields().get("code"), Some(&"7".to_string()));
219        assert!(
220            diag.source().is_none(),
221            "no identical source to duplicate rendering"
222        );
223        assert_eq!(exit_code_of_diag(&diag), Some(7));
224        let carried = exit_code_of(&anyhow::Error::new(diag).context("step 2"));
225        assert_eq!(carried, Some(7));
226    }
227
228    #[test]
229    fn describe_prefers_numeric_code() {
230        let status = oxdock_sys_test_utils::exit_status_from_code(3);
231        assert_eq!(super::describe_exit_status(&status), "3");
232        assert_eq!(super::exit_status_code(&status), Some(3));
233    }
234}