isothrum-runner 3.0.1

The Isothrum runner: runs a Compose project, a Vagrantfile or a Terraform module through its own tool (lifecycle, state and locks, the format drivers, events).
Documentation
//! What an operation's `result` event carries: one shape per operation, typed, so an embedder
//! reads `data` by its fields rather than walking untyped JSON. The JSON is the same as each
//! operation wrote by hand before: the enum is untagged, each shape told apart by its fields (the
//! embedder knows which operation it asked for).

use serde::{Deserialize, Serialize};

use crate::state::RunState;

/// What an operation found or produced, by operation.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(untagged, deny_unknown_fields)]
#[non_exhaustive]
pub enum ResultData {
    /// An `up` that came up: where the run stands, and its outputs.
    Started {
        /// Where the run stands (`ready`).
        state: RunState,
        /// Its outputs, sensitive values shown as `***`.
        outputs: Vec<ShownOutput>,
    },
    /// A `reap`: the expired runs it destroyed or would.
    Swept {
        /// The runs destroyed.
        destroyed: Vec<String>,
        /// The runs a dry run would destroy.
        pending: Vec<String>,
        /// The runs whose destroy failed, with why.
        failed: Vec<SweepFailure>,
    },
    /// An operation on one machine or on all (`attach`, `retire`, `exec`, `provision`): which.
    Machine {
        /// Its name in the project; none for every machine (a `provision` of the whole run).
        machine: Option<String>,
    },
    /// An operation that moved the run (`down`, `park`, `resume`): where it stands.
    Moved {
        /// Where the run stands now.
        state: RunState,
    },
}

/// An output as a `result` event shows it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ShownOutput {
    /// Its name.
    pub name: String,
    /// Its value, when it can be read; `***` when it is sensitive.
    pub value: Option<String>,
}

impl ShownOutput {
    /// `name`, showing `value`.
    #[must_use]
    pub fn new(name: impl Into<String>, value: Option<String>) -> ShownOutput {
        ShownOutput { name: name.into(), value }
    }
}

/// A run a `reap` couldn't destroy.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct SweepFailure {
    /// The run.
    pub run: String,
    /// Why its destroy failed.
    pub error: String,
}

impl SweepFailure {
    /// Run `run`'s destroy, failed for `error`.
    #[must_use]
    pub fn new(run: impl Into<String>, error: impl Into<String>) -> SweepFailure {
        SweepFailure {
            run: run.into(),
            error: error.into(),
        }
    }
}

impl ResultData {
    /// The data with every string `mask` returns for it: no sensitive value of the run shows.
    #[must_use]
    pub(crate) fn masked(self, mask: impl Fn(&str) -> String) -> ResultData {
        let m = |s: String| mask(&s);
        let mo = |s: Option<String>| s.map(|s| mask(&s));
        match self {
            ResultData::Started { state, outputs } => ResultData::Started {
                state,
                outputs: outputs
                    .into_iter()
                    .map(|o| ShownOutput {
                        name: m(o.name),
                        value: mo(o.value),
                    })
                    .collect(),
            },
            ResultData::Swept { destroyed, pending, failed } => ResultData::Swept {
                destroyed,
                pending,
                failed: failed.into_iter().map(|f| SweepFailure { run: f.run, error: m(f.error) }).collect(),
            },
            other => other,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Each shape is the JSON each operation wrote by hand before the type, and reads back as
    /// itself from it: its fields alone tell it apart.
    #[test]
    fn every_shape_is_its_wire_json_and_reads_back_from_it() {
        let shapes = [
            (
                ResultData::Started {
                    state: RunState::Ready,
                    outputs: vec![ShownOutput::new("web", Some("http://127.0.0.1:8080".into()))],
                },
                serde_json::json!({"state": "ready", "outputs": [{"name": "web", "value": "http://127.0.0.1:8080"}]}),
            ),
            (
                ResultData::Swept {
                    destroyed: vec!["a".into()],
                    pending: Vec::new(),
                    failed: vec![SweepFailure::new("b", "x")],
                },
                serde_json::json!({"destroyed": ["a"], "pending": [], "failed": [{"run": "b", "error": "x"}]}),
            ),
            (ResultData::Machine { machine: Some("web".into()) }, serde_json::json!({"machine": "web"})),
            (ResultData::Machine { machine: None }, serde_json::json!({"machine": null})),
            (ResultData::Moved { state: RunState::Parked }, serde_json::json!({"state": "parked"})),
        ];
        for (shape, json) in shapes {
            assert_eq!(serde_json::to_value(&shape).unwrap(), json, "{shape:?}");
            assert_eq!(serde_json::from_value::<ResultData>(json.clone()).unwrap(), shape, "{json}");
        }
    }
}