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        sdd: inst.meta.get_str_or("version", "0.0.0").to_string(),
67        commit: args.commit,
68    };
69    let line = journal::render_line(&e);
70    journal::append_line(&handle, &line)?;
71    emit(&line);
72    Ok(0)
73}
74
75/// A journal replayed against the units' front matter.
76pub struct Replayed {
77    pub events: usize,
78    pub projection: journal::Projection,
79    pub mismatches: Vec<journal::VerifyMismatch>,
80    pub consistent: bool,
81}
82
83/// Replay `inst`'s journal and compare it with front matter; `None` when
84/// the SDD has no journal, or an empty one.
85pub fn replayed(inst: &Instance) -> Result<Option<Replayed>, CoreError> {
86    let (events, exists) = journal::read(&inst.handle())?;
87    if !exists || events.is_empty() {
88        return Ok(None);
89    }
90    let projection = journal::replay(&events);
91    let mismatches = journal::verify(&projection, &inst.units);
92    let consistent = mismatches.is_empty() && projection.order_findings.is_empty();
93    Ok(Some(Replayed {
94        events: events.len(),
95        projection,
96        mismatches,
97        consistent,
98    }))
99}
100
101impl Replayed {
102    /// The exit code `journal replay` gives it.
103    pub fn code(&self) -> u8 {
104        if self.consistent { 0 } else { 3 }
105    }
106
107    /// Every problem as `(subject, cause, remediation)`.
108    pub fn findings(&self) -> Vec<(String, String, String)> {
109        let mut out: Vec<(String, String, String)> = self
110            .projection
111            .order_findings
112            .iter()
113            .map(|f| {
114                (
115                    "journal".to_string(),
116                    f.clone(),
117                    "restore the journal from version control: it is append-only, and only vitrify's verbs append to it".to_string(),
118                )
119            })
120            .collect();
121        for m in &self.mismatches {
122            out.push((
123                m.unit.clone(),
124                format!(
125                    "{}: journal projects {}, front matter says {}",
126                    m.field,
127                    m.projected.repr(),
128                    m.current.repr()
129                ),
130                format!(
131                    "set {}'s {} back to {}, as the journal projects; state changes go through vitrify's verbs, never by hand",
132                    m.unit,
133                    m.field,
134                    m.projected.repr()
135                ),
136            ));
137        }
138        out
139    }
140
141    /// `{events, consistent, order_findings, mismatches, projection}`.
142    fn json(&self) -> Vec<(String, J)> {
143        let jm: Vec<J> = self
144            .mismatches
145            .iter()
146            .map(|m| {
147                let val = |v: &journal::FieldVal| match v {
148                    journal::FieldVal::Str(s) => J::s(s.clone()),
149                    journal::FieldVal::Int(i) => J::Int(*i),
150                };
151                J::Obj(vec![
152                    ("unit".into(), J::s(m.unit.clone())),
153                    ("field".into(), J::s(m.field)),
154                    ("projected".into(), val(&m.projected)),
155                    ("current".into(), val(&m.current)),
156                ])
157            })
158            .collect();
159        vec![
160            ("events".into(), J::Int(self.events as i64)),
161            ("consistent".into(), J::Bool(self.consistent)),
162            (
163                "order_findings".into(),
164                J::Arr(
165                    self.projection
166                        .order_findings
167                        .iter()
168                        .map(|f| J::s(f.clone()))
169                        .collect(),
170                ),
171            ),
172            ("mismatches".into(), J::Arr(jm)),
173            (
174                "projection".into(),
175                J::Obj(
176                    self.projection
177                        .status
178                        .iter()
179                        .map(|(u, s)| (u.clone(), J::s(s.clone())))
180                        .collect(),
181                ),
182            ),
183        ]
184    }
185
186    /// The text report, each line under `under`.
187    fn emit_text(&self, under: &str) {
188        if self.consistent {
189            emit(&format!(
190                "{under}journal consistent ({} events)",
191                self.events
192            ));
193            return;
194        }
195        for f in &self.projection.order_findings {
196            emit(&format!("{under}order: {f}"));
197        }
198        for m in &self.mismatches {
199            emit(&format!(
200                "{under}mismatch {}.{}: journal projects {}, front matter says {}",
201                m.unit,
202                m.field,
203                m.projected.repr(),
204                m.current.repr()
205            ));
206        }
207    }
208}
209
210pub fn replay(json: bool, sdd: Option<&str>, all: bool) -> Result<u8, CoreError> {
211    if !all {
212        let inst = load(sdd)?;
213        let Some(r) = replayed(&inst)? else {
214            return Err(CoreError::refusal(4, "error: no journal found (or empty)"));
215        };
216        if json {
217            emit(&J::Obj(r.json()).dumps_indent2());
218        } else {
219            r.emit_text("");
220        }
221        return Ok(r.code());
222    }
223
224    // every SDD: each line under its SDD's name; one with no journal yet is
225    // reported and fails nothing
226    let root = super::repo_root();
227    let sdds = super::targets(&root, sdd, true, &super::cwd())?;
228    let mut reports: Vec<J> = Vec::new();
229    let code = super::each(&root, &sdds, |sdd| {
230        let inst = Instance::load(sdd.clone())?;
231        let name = super::label(sdd, &root);
232        let r = replayed(&inst)?;
233        if json {
234            let mut pairs = vec![
235                ("sdd".into(), J::s(name)),
236                ("root".into(), J::s(super::shown(&root, &sdd.root))),
237            ];
238            match &r {
239                Some(r) => pairs.extend(r.json()),
240                None => pairs.extend([
241                    ("events".into(), J::Int(0)),
242                    ("consistent".into(), J::Null),
243                    ("order_findings".into(), J::Arr(Vec::new())),
244                    ("mismatches".into(), J::Arr(Vec::new())),
245                    ("projection".into(), J::Obj(Vec::new())),
246                ]),
247            }
248            reports.push(J::Obj(pairs));
249        } else {
250            match &r {
251                Some(r) => r.emit_text(&format!("{name}: ")),
252                None => emit(&format!("{name}: no journal yet")),
253            }
254        }
255        Ok(r.as_ref().map_or(0, Replayed::code))
256    });
257    if json {
258        emit(&J::Arr(reports).dumps_indent2());
259    }
260    Ok(code)
261}