Skip to main content

isothrum_runner/events/
result_data.rs

1//! What an operation's `result` event carries: one shape per operation, typed, so an embedder
2//! reads `data` by its fields rather than walking untyped JSON. The JSON is the same as each
3//! operation wrote by hand before: the enum is untagged, each shape told apart by its fields (the
4//! embedder knows which operation it asked for).
5
6use serde::{Deserialize, Serialize};
7
8use crate::state::RunState;
9
10/// What an operation found or produced, by operation.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
12#[serde(untagged, deny_unknown_fields)]
13#[non_exhaustive]
14pub enum ResultData {
15    /// An `up` that came up: where the run stands, and its outputs.
16    Started {
17        /// Where the run stands (`ready`).
18        state: RunState,
19        /// Its outputs, sensitive values shown as `***`.
20        outputs: Vec<ShownOutput>,
21    },
22    /// A `reap`: the expired runs it destroyed or would.
23    Swept {
24        /// The runs destroyed.
25        destroyed: Vec<String>,
26        /// The runs a dry run would destroy.
27        pending: Vec<String>,
28        /// The runs whose destroy failed, with why.
29        failed: Vec<SweepFailure>,
30    },
31    /// An operation on one machine or on all (`attach`, `retire`, `exec`, `provision`): which.
32    Machine {
33        /// Its name in the project; none for every machine (a `provision` of the whole run).
34        machine: Option<String>,
35    },
36    /// An operation that moved the run (`down`, `park`, `resume`): where it stands.
37    Moved {
38        /// Where the run stands now.
39        state: RunState,
40    },
41}
42
43/// An output as a `result` event shows it.
44#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
45#[serde(deny_unknown_fields)]
46#[non_exhaustive]
47pub struct ShownOutput {
48    /// Its name.
49    pub name: String,
50    /// Its value, when it can be read; `***` when it is sensitive.
51    pub value: Option<String>,
52}
53
54impl ShownOutput {
55    /// `name`, showing `value`.
56    #[must_use]
57    pub fn new(name: impl Into<String>, value: Option<String>) -> ShownOutput {
58        ShownOutput { name: name.into(), value }
59    }
60}
61
62/// A run a `reap` couldn't destroy.
63#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
64#[serde(deny_unknown_fields)]
65#[non_exhaustive]
66pub struct SweepFailure {
67    /// The run.
68    pub run: String,
69    /// Why its destroy failed.
70    pub error: String,
71}
72
73impl SweepFailure {
74    /// Run `run`'s destroy, failed for `error`.
75    #[must_use]
76    pub fn new(run: impl Into<String>, error: impl Into<String>) -> SweepFailure {
77        SweepFailure {
78            run: run.into(),
79            error: error.into(),
80        }
81    }
82}
83
84impl ResultData {
85    /// The data with every string `mask` returns for it: no sensitive value of the run shows.
86    #[must_use]
87    pub(crate) fn masked(self, mask: impl Fn(&str) -> String) -> ResultData {
88        let m = |s: String| mask(&s);
89        let mo = |s: Option<String>| s.map(|s| mask(&s));
90        match self {
91            ResultData::Started { state, outputs } => ResultData::Started {
92                state,
93                outputs: outputs
94                    .into_iter()
95                    .map(|o| ShownOutput {
96                        name: m(o.name),
97                        value: mo(o.value),
98                    })
99                    .collect(),
100            },
101            ResultData::Swept { destroyed, pending, failed } => ResultData::Swept {
102                destroyed,
103                pending,
104                failed: failed.into_iter().map(|f| SweepFailure { run: f.run, error: m(f.error) }).collect(),
105            },
106            other => other,
107        }
108    }
109}
110
111#[cfg(test)]
112mod tests {
113    use super::*;
114
115    /// Each shape is the JSON each operation wrote by hand before the type, and reads back as
116    /// itself from it: its fields alone tell it apart.
117    #[test]
118    fn every_shape_is_its_wire_json_and_reads_back_from_it() {
119        let shapes = [
120            (
121                ResultData::Started {
122                    state: RunState::Ready,
123                    outputs: vec![ShownOutput::new("web", Some("http://127.0.0.1:8080".into()))],
124                },
125                serde_json::json!({"state": "ready", "outputs": [{"name": "web", "value": "http://127.0.0.1:8080"}]}),
126            ),
127            (
128                ResultData::Swept {
129                    destroyed: vec!["a".into()],
130                    pending: Vec::new(),
131                    failed: vec![SweepFailure::new("b", "x")],
132                },
133                serde_json::json!({"destroyed": ["a"], "pending": [], "failed": [{"run": "b", "error": "x"}]}),
134            ),
135            (ResultData::Machine { machine: Some("web".into()) }, serde_json::json!({"machine": "web"})),
136            (ResultData::Machine { machine: None }, serde_json::json!({"machine": null})),
137            (ResultData::Moved { state: RunState::Parked }, serde_json::json!({"state": "parked"})),
138        ];
139        for (shape, json) in shapes {
140            assert_eq!(serde_json::to_value(&shape).unwrap(), json, "{shape:?}");
141            assert_eq!(serde_json::from_value::<ResultData>(json.clone()).unwrap(), shape, "{json}");
142        }
143    }
144}