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
9use oxdock_parser::KEYWORD_EXIT;
10
11/// Pipeline exit request carrying the numeric code. Produced by `EXIT`,
12/// re-raised by `REMOTE` when the guest exits, and mapped to the process
13/// exit status by the CLI.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub struct ExitRequest(pub i64);
16
17impl Display for ExitRequest {
18    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
19        write!(f, "{KEYWORD_EXIT} requested with code {}", self.0)
20    }
21}
22
23impl std::error::Error for ExitRequest {}
24
25/// Outermost `EXIT` code in the chain, if any. Relays preserve the code
26/// unchanged, so first-found and last-found agree; outermost wins because
27/// it is the most recent relay decision.
28pub fn exit_code_of(err: &anyhow::Error) -> Option<i64> {
29    err.chain()
30        .find_map(|cause| cause.downcast_ref::<ExitRequest>().map(|exit| exit.0))
31}
32
33#[cfg(test)]
34mod tests {
35    use super::{ExitRequest, exit_code_of};
36
37    #[test]
38    fn display_matches_historic_message() {
39        assert_eq!(ExitRequest(3).to_string(), "EXIT requested with code 3");
40    }
41
42    #[test]
43    fn finds_code_through_context_wrappers() {
44        let err = anyhow::Error::new(ExitRequest(3)).context("REMOTE 'prod' failed");
45        assert_eq!(exit_code_of(&err), Some(3));
46    }
47
48    #[test]
49    fn none_without_exit() {
50        let err = anyhow::anyhow!("boom").context("wrapped");
51        assert_eq!(exit_code_of(&err), None);
52    }
53}