Skip to main content

vitrify_cli/cmd/
journal.rs

1//! `vitrify journal append|replay` — the journal verbs (NDJSON events).
2
3use vitrify_core::CoreError;
4use vitrify_core::journal::{self, Event};
5use vitrify_core::model::{Instance, UtcTime};
6
7use crate::cli::EventKind;
8use crate::out::{J, emit};
9
10fn load(sdd: Option<&str>) -> Result<Instance, CoreError> {
11    let root = super::repo_root();
12    Instance::load(super::resolve_sdd(&root, sdd, &super::cwd())?)
13}
14
15#[derive(Default)]
16pub struct AppendArgs {
17    pub unit: Option<String>,
18    pub actor: Option<String>,
19    pub claim_seq: Option<i64>,
20    pub entry: Option<String>,
21    pub stale: Option<String>,
22    pub cause: Option<String>,
23    pub findings: Option<i64>,
24    pub commit: Option<String>,
25    pub sdd: Option<String>,
26}
27
28pub fn append(event: EventKind, args: AppendArgs) -> Result<u8, CoreError> {
29    let unit_required = matches!(
30        event,
31        EventKind::Claim
32            | EventKind::Renew
33            | EventKind::Release
34            | EventKind::Built
35            | EventKind::Verified
36            | EventKind::Stale
37            | EventKind::Retired
38    );
39    if unit_required && args.unit.is_none() {
40        return Err(CoreError::refusal(
41            2,
42            format!("error: --event {} requires --unit", event.as_str()),
43        ));
44    }
45    let inst = load(args.sdd.as_deref())?;
46    let handle = inst.handle();
47    let (events, _) = journal::read(&handle)?;
48    let stale = args.stale.map(|s| {
49        s.split(',')
50            .map(str::trim)
51            .filter(|x| !x.is_empty())
52            .map(str::to_string)
53            .collect::<Vec<_>>()
54    });
55    let e = Event {
56        seq: events.last().map(|e| e.seq).unwrap_or(0) + 1,
57        at: UtcTime::now().format(),
58        event: event.as_str().to_string(),
59        unit: args.unit,
60        actor: args.actor,
61        claim_seq: args.claim_seq,
62        entry: args.entry,
63        stale,
64        cause: args.cause,
65        findings: args.findings,
66        suite: None,
67        sdd: inst.meta.get_str_or("version", "0.0.0").to_string(),
68        commit: args.commit,
69    };
70    let line = journal::render_line(&e);
71    journal::append_line(&handle, &line)?;
72    emit(&line);
73    Ok(0)
74}
75
76/// A journal replayed against the units' front matter.
77pub struct Replayed {
78    pub events: usize,
79    pub projection: journal::Projection,
80    pub mismatches: Vec<journal::VerifyMismatch>,
81    pub consistent: bool,
82}
83
84/// Replay `inst`'s journal and compare it with front matter; `None` when
85/// the SDD has no journal, or an empty one.
86pub fn replayed(inst: &Instance) -> Result<Option<Replayed>, CoreError> {
87    let (events, exists) = journal::read(&inst.handle())?;
88    if !exists || events.is_empty() {
89        return Ok(None);
90    }
91    let projection = journal::replay(&events);
92    let mismatches = journal::verify(&projection, &inst.units);
93    let consistent = mismatches.is_empty() && projection.order_findings.is_empty();
94    Ok(Some(Replayed {
95        events: events.len(),
96        projection,
97        mismatches,
98        consistent,
99    }))
100}
101
102impl Replayed {
103    /// The exit code `journal replay` gives it.
104    pub fn code(&self) -> u8 {
105        if self.consistent { 0 } else { 3 }
106    }
107
108    /// Every problem as `(subject, cause, remediation)`.
109    pub fn findings(&self) -> Vec<(String, String, String)> {
110        let mut out: Vec<(String, String, String)> = self
111            .projection
112            .order_findings
113            .iter()
114            .map(|f| {
115                (
116                    "journal".to_string(),
117                    f.clone(),
118                    "restore the journal from version control: it is append-only, and only vitrify's verbs append to it".to_string(),
119                )
120            })
121            .collect();
122        for m in &self.mismatches {
123            out.push((
124                m.unit.clone(),
125                format!(
126                    "{}: journal projects {}, front matter says {}",
127                    m.field,
128                    m.projected.repr(),
129                    m.current.repr()
130                ),
131                format!(
132                    "set {}'s {} back to {}, as the journal projects; state changes go through vitrify's verbs, never by hand",
133                    m.unit,
134                    m.field,
135                    m.projected.repr()
136                ),
137            ));
138        }
139        out
140    }
141
142    /// `{events, consistent, order_findings, mismatches, projection}`.
143    fn json(&self) -> Vec<(String, J)> {
144        let jm: Vec<J> = self
145            .mismatches
146            .iter()
147            .map(|m| {
148                let val = |v: &journal::FieldVal| match v {
149                    journal::FieldVal::Str(s) => J::s(s.clone()),
150                    journal::FieldVal::Int(i) => J::Int(*i),
151                };
152                J::Obj(vec![
153                    ("unit".into(), J::s(m.unit.clone())),
154                    ("field".into(), J::s(m.field)),
155                    ("projected".into(), val(&m.projected)),
156                    ("current".into(), val(&m.current)),
157                ])
158            })
159            .collect();
160        vec![
161            ("events".into(), J::Int(self.events as i64)),
162            ("consistent".into(), J::Bool(self.consistent)),
163            (
164                "order_findings".into(),
165                J::Arr(
166                    self.projection
167                        .order_findings
168                        .iter()
169                        .map(|f| J::s(f.clone()))
170                        .collect(),
171                ),
172            ),
173            ("mismatches".into(), J::Arr(jm)),
174            (
175                "projection".into(),
176                J::Obj(
177                    self.projection
178                        .status
179                        .iter()
180                        .map(|(u, s)| (u.clone(), J::s(s.clone())))
181                        .collect(),
182                ),
183            ),
184        ]
185    }
186
187    /// The text report, each line under `under`.
188    fn emit_text(&self, under: &str) {
189        if self.consistent {
190            emit(&format!(
191                "{under}journal consistent ({} events)",
192                self.events
193            ));
194            return;
195        }
196        for f in &self.projection.order_findings {
197            emit(&format!("{under}order: {f}"));
198        }
199        for m in &self.mismatches {
200            emit(&format!(
201                "{under}mismatch {}.{}: journal projects {}, front matter says {}",
202                m.unit,
203                m.field,
204                m.projected.repr(),
205                m.current.repr()
206            ));
207        }
208    }
209}
210
211pub fn replay(json: bool, sdd: Option<&str>, all: bool) -> Result<u8, CoreError> {
212    if !all {
213        let inst = load(sdd)?;
214        let Some(r) = replayed(&inst)? else {
215            return Err(CoreError::refusal(4, "error: no journal found (or empty)"));
216        };
217        if json {
218            emit(&J::Obj(r.json()).dumps_indent2());
219        } else {
220            r.emit_text("");
221        }
222        return Ok(r.code());
223    }
224
225    // every SDD: each line under its SDD's name; one with no journal yet is
226    // reported and fails nothing
227    let root = super::repo_root();
228    let sdds = super::targets(&root, sdd, true, &super::cwd())?;
229    let mut reports: Vec<J> = Vec::new();
230    let code = super::each(&root, &sdds, |sdd| {
231        let inst = Instance::load(sdd.clone())?;
232        let name = super::label(sdd, &root);
233        let r = replayed(&inst)?;
234        if json {
235            let mut pairs = vec![
236                ("sdd".into(), J::s(name)),
237                ("root".into(), J::s(super::shown(&root, &sdd.root))),
238            ];
239            match &r {
240                Some(r) => pairs.extend(r.json()),
241                None => pairs.extend([
242                    ("events".into(), J::Int(0)),
243                    ("consistent".into(), J::Null),
244                    ("order_findings".into(), J::Arr(Vec::new())),
245                    ("mismatches".into(), J::Arr(Vec::new())),
246                    ("projection".into(), J::Obj(Vec::new())),
247                ]),
248            }
249            reports.push(J::Obj(pairs));
250        } else {
251            match &r {
252                Some(r) => r.emit_text(&format!("{name}: ")),
253                None => emit(&format!("{name}: no journal yet")),
254            }
255        }
256        Ok(r.as_ref().map_or(0, Replayed::code))
257    });
258    if json {
259        emit(&J::Arr(reports).dumps_indent2());
260    }
261    Ok(code)
262}