Skip to main content

dort_core/tools/install/
outcomes.rs

1//! Reads saved install results.
2use super::{Attempt, BinaryState, Outcome, PackageState, ProcessOutcome, Report, Scope};
3use serde::{Serialize, Serializer};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
6#[serde(rename_all = "snake_case")]
7pub enum Status {
8    Unresolved,
9    ExplicitlyClosed,
10    NoOp,
11    ExactReported,
12    CurrentReported,
13    ProcessFailed,
14    ProcessUnavailable,
15    ProcessUnverified,
16    DeadlineElapsed,
17    PackageAbsent,
18    PackageConflict,
19    PackageUnavailable,
20    OutcomeUnavailable,
21}
22impl Status {
23    pub fn label(self) -> &'static str {
24        match self {
25            Self::Unresolved => "UNRESOLVED",
26            Self::ExplicitlyClosed => "Explicitly closed",
27            Self::NoOp => "No installer ran",
28            Self::ExactReported => "Exact package reported",
29            Self::CurrentReported => "Current package reported",
30            Self::ProcessFailed => "Process failed",
31            Self::ProcessUnavailable => "Installer unavailable",
32            Self::ProcessUnverified => "Process status unknown",
33            Self::DeadlineElapsed => "Deadline elapsed",
34            Self::PackageAbsent => "Package absent",
35            Self::PackageConflict => "Package conflict",
36            Self::PackageUnavailable => "Package unknown",
37            Self::OutcomeUnavailable => "Outcome unknown",
38        }
39    }
40}
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
42#[serde(rename_all = "snake_case")]
43pub enum NextStep {
44    ReviewClosure,
45    FreshReview,
46}
47impl NextStep {
48    pub fn hint(self) -> &'static str {
49        match self {
50            Self::ReviewClosure => {
51                "Inspect attempt metadata; unresolved records need fresh-query closure before another install. Closure is not success, repair or proof of root termination."
52            }
53            Self::FreshReview => {
54                "Check installed again, then review and approve a new installation. Earlier approvals are not replayed."
55            }
56        }
57    }
58}
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
60pub struct Summary {
61    pub status: Status,
62    pub process: Option<ProcessOutcome>,
63    pub package: Option<PackageState>,
64    pub binary: Option<BinaryState>,
65    pub explanation: &'static str,
66    pub binary_note: &'static str,
67    pub next_step: NextStep,
68    pub next_step_hint: &'static str,
69    pub readiness_verified: bool,
70}
71impl Summary {
72    pub fn package_note(self) -> &'static str {
73        match self.package {
74            Some(PackageState::ExactPresent) => "Package: exact version reported present",
75            Some(PackageState::ProviderCurrentPresent) => {
76                "Package: provider-current reported present"
77            }
78            Some(PackageState::Absent) => "Package: reported absent",
79            Some(PackageState::Conflict) => "Package: conflicting observation",
80            Some(PackageState::Unavailable) => "Package: observation unavailable",
81            None if self.status == Status::NoOp => "Matching package; no installer ran",
82            None => "Package: no usable outcome",
83        }
84    }
85    pub fn binary_label(self) -> &'static str {
86        match self.binary {
87            Some(BinaryState::Missing) => "Binary missing; readiness unknown",
88            Some(BinaryState::Candidates) => "Binary candidates; readiness/ownership unknown",
89            Some(BinaryState::Unavailable) => "Binary observation unavailable",
90            None => "Binary readiness and ownership unverified",
91        }
92    }
93    pub fn process_label(self) -> &'static str {
94        match self.process {
95            Some(ProcessOutcome::Success) => "Process completed",
96            Some(ProcessOutcome::Failed) => "Unsuccessful exit",
97            Some(ProcessOutcome::Unavailable) => "Installer unavailable",
98            Some(ProcessOutcome::Pipe) => "Process I/O unavailable",
99            Some(ProcessOutcome::Wait) => "Process status unavailable",
100            Some(ProcessOutcome::Timeout) => "Requested deadline elapsed",
101            None if self.status == Status::NoOp => "No installer requested",
102            None => "No usable process outcome",
103        }
104    }
105    fn new(status: Status, outcome: Option<Outcome>) -> Self {
106        let next_step = if matches!(status, Status::Unresolved | Status::OutcomeUnavailable) {
107            NextStep::ReviewClosure
108        } else {
109            NextStep::FreshReview
110        };
111        let binary = outcome.map(|o| o.binary);
112        Self {
113            status,
114            process: outcome.map(|o| o.process),
115            package: outcome.map(|o| o.package),
116            binary,
117            explanation: match status {
118                Status::Unresolved => {
119                    "Attempt metadata is incomplete, malformed or changed; later Tools installs remain blocked."
120                }
121                Status::ExplicitlyClosed => {
122                    "Only unchanged historical metadata was acknowledged after fresh inspection; no install success, repair or root termination is implied."
123                }
124                Status::NoOp => {
125                    "A matching package was reported by fresh inspection; no installer or attempt was created."
126                }
127                Status::ExactReported => {
128                    "The process completed and the exact requested package version was reported; this is not verified binary readiness or ownership."
129                }
130                Status::CurrentReported => {
131                    "The process completed and a provider-current package was reported, not an exact pin; this is not verified binary readiness or ownership."
132                }
133                Status::ProcessFailed => match outcome.map(|o| o.package) {
134                    Some(PackageState::ExactPresent | PackageState::ProviderCurrentPresent) => {
135                        "The process did not complete successfully even though a package was reported present. Native effects may be partial or ongoing; presence does not turn failure into success."
136                    }
137                    Some(PackageState::Absent) => {
138                        "The process did not complete successfully and the package was reported absent. Native effects may be partial or ongoing; no rollback is implied."
139                    }
140                    _ => {
141                        "The process did not complete successfully; the package is conflicting or unavailable. Native effects may be partial or ongoing; no rollback is implied."
142                    }
143                },
144                Status::ProcessUnavailable => {
145                    "The installer could not be started. Earlier provider queries may have native cache effects; package presence does not authorize replay."
146                }
147                Status::ProcessUnverified => {
148                    "The process outcome could not be established; package presence alone is not process success. Native effects may be partial or ongoing; no rollback is implied."
149                }
150                Status::DeadlineElapsed => {
151                    "The requested deadline elapsed without verified success. Effects may be partial or ongoing; no privileged-termination or rollback proof is implied."
152                }
153                Status::PackageAbsent => {
154                    "The process completed but the requested package was reported absent; installation is not established and partial effects may remain."
155                }
156                Status::PackageConflict => {
157                    "The process completed but the observed package conflicts with the request; installation is not established and partial effects may remain."
158                }
159                Status::PackageUnavailable => {
160                    "The process completed but the package observation is unavailable, not healthy empty or verified success; partial effects may remain."
161                }
162                Status::OutcomeUnavailable => {
163                    "No usable outcome was reported; inspect attempt metadata before considering another install."
164                }
165            },
166            binary_note: match binary {
167                Some(BinaryState::Missing) => {
168                    "Declared binary missing; package presence does not establish readiness."
169                }
170                Some(BinaryState::Candidates) => {
171                    "Binary candidates observed as metadata only; none was executed or verified ready/owned."
172                }
173                Some(BinaryState::Unavailable) => {
174                    "Binary observation unavailable, not a healthy empty result or verified readiness."
175                }
176                None => "Binary state not reported here; readiness and ownership are not verified.",
177            },
178            next_step,
179            next_step_hint: next_step.hint(),
180            readiness_verified: false,
181        }
182    }
183}
184impl Outcome {
185    pub fn succeeded(self) -> bool {
186        self.process == ProcessOutcome::Success
187            && matches!(
188                self.package,
189                PackageState::ExactPresent | PackageState::ProviderCurrentPresent
190            )
191    }
192    pub fn summary(self) -> Summary {
193        let status = match self.process {
194            ProcessOutcome::Failed => Status::ProcessFailed,
195            ProcessOutcome::Unavailable => Status::ProcessUnavailable,
196            ProcessOutcome::Pipe | ProcessOutcome::Wait => Status::ProcessUnverified,
197            ProcessOutcome::Timeout => Status::DeadlineElapsed,
198            ProcessOutcome::Success => match self.package {
199                PackageState::ExactPresent => Status::ExactReported,
200                PackageState::ProviderCurrentPresent => Status::CurrentReported,
201                PackageState::Absent => Status::PackageAbsent,
202                PackageState::Conflict => Status::PackageConflict,
203                PackageState::Unavailable => Status::PackageUnavailable,
204            },
205        };
206        Summary::new(status, Some(self))
207    }
208}
209impl Attempt {
210    pub fn summary(&self) -> Summary {
211        if self.unresolved {
212            Summary::new(Status::Unresolved, self.outcome)
213        } else if self.explicitly_closed {
214            Summary::new(Status::ExplicitlyClosed, self.outcome)
215        } else {
216            self.outcome
217                .map(Outcome::summary)
218                .unwrap_or_else(|| Summary::new(Status::OutcomeUnavailable, None))
219        }
220    }
221}
222impl Report {
223    pub fn summary(&self) -> Summary {
224        if self.no_op {
225            Summary::new(Status::NoOp, self.outcome)
226        } else {
227            self.outcome
228                .map(Outcome::summary)
229                .unwrap_or_else(|| Summary::new(Status::OutcomeUnavailable, None))
230        }
231    }
232}
233// Only public reports gain derived fields. Persisted Intent/Completed/Closure,
234// their payload bytes, checksums and heads never pass through these views.
235impl Serialize for Attempt {
236    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
237        #[derive(Serialize)]
238        struct View<'a> {
239            id: &'a str,
240            scope: &'a Option<Scope>,
241            outcome: Option<Outcome>,
242            #[serde(skip_serializing_if = "Vec::is_empty")]
243            observed_versions: &'a Vec<String>,
244            problem: &'a Option<super::Problem>,
245            unresolved: bool,
246            explicitly_closed: bool,
247            summary: Summary,
248        }
249        View {
250            id: &self.id,
251            scope: &self.scope,
252            outcome: self.outcome,
253            observed_versions: &self.observed_versions,
254            problem: &self.problem,
255            unresolved: self.unresolved,
256            explicitly_closed: self.explicitly_closed,
257            summary: self.summary(),
258        }
259        .serialize(serializer)
260    }
261}
262impl Serialize for Report {
263    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
264        #[derive(Serialize)]
265        struct View<'a> {
266            scope: &'a Scope,
267            attempt_id: &'a Option<String>,
268            no_op: bool,
269            outcome: Option<Outcome>,
270            #[serde(skip_serializing_if = "Vec::is_empty")]
271            observed_versions: &'a Vec<String>,
272            possible_partial_effects: bool,
273            readiness_verified: bool,
274            summary: Summary,
275        }
276        View {
277            scope: &self.scope,
278            attempt_id: &self.attempt_id,
279            no_op: self.no_op,
280            outcome: self.outcome,
281            observed_versions: &self.observed_versions,
282            possible_partial_effects: self.possible_partial_effects,
283            readiness_verified: self.readiness_verified,
284            summary: self.summary(),
285        }
286        .serialize(serializer)
287    }
288}
289
290#[cfg(test)]
291mod tests {
292    use super::*;
293    #[test]
294    fn all_process_package_binary_combinations_preserve_independent_facts() {
295        for process in [
296            ProcessOutcome::Success,
297            ProcessOutcome::Failed,
298            ProcessOutcome::Unavailable,
299            ProcessOutcome::Pipe,
300            ProcessOutcome::Wait,
301            ProcessOutcome::Timeout,
302        ] {
303            for package in [
304                PackageState::ExactPresent,
305                PackageState::ProviderCurrentPresent,
306                PackageState::Absent,
307                PackageState::Conflict,
308                PackageState::Unavailable,
309            ] {
310                for binary in [
311                    BinaryState::Missing,
312                    BinaryState::Candidates,
313                    BinaryState::Unavailable,
314                ] {
315                    let o = Outcome {
316                        process,
317                        package,
318                        binary,
319                    };
320                    let s = o.summary();
321                    assert_eq!(
322                        (s.process, s.package, s.binary),
323                        (Some(process), Some(package), Some(binary))
324                    );
325                    assert!(!s.readiness_verified);
326                    assert_eq!(
327                        o.succeeded(),
328                        matches!(s.status, Status::ExactReported | Status::CurrentReported)
329                    );
330                    let expected = match (process, package) {
331                        (ProcessOutcome::Success, PackageState::ExactPresent) => {
332                            Status::ExactReported
333                        }
334                        (ProcessOutcome::Success, PackageState::ProviderCurrentPresent) => {
335                            Status::CurrentReported
336                        }
337                        (ProcessOutcome::Success, PackageState::Absent) => Status::PackageAbsent,
338                        (ProcessOutcome::Success, PackageState::Conflict) => {
339                            Status::PackageConflict
340                        }
341                        (ProcessOutcome::Success, PackageState::Unavailable) => {
342                            Status::PackageUnavailable
343                        }
344                        (ProcessOutcome::Failed, _) => Status::ProcessFailed,
345                        (ProcessOutcome::Unavailable, _) => Status::ProcessUnavailable,
346                        (ProcessOutcome::Pipe | ProcessOutcome::Wait, _) => {
347                            Status::ProcessUnverified
348                        }
349                        (ProcessOutcome::Timeout, _) => Status::DeadlineElapsed,
350                    };
351                    assert_eq!(s.status, expected);
352                    if binary == BinaryState::Candidates {
353                        assert!(s.binary_note.contains("none was executed"));
354                    }
355                    if package == PackageState::Unavailable && process == ProcessOutcome::Success {
356                        assert_eq!(s.status, Status::PackageUnavailable);
357                    }
358                    assert!(s.next_step_hint.contains("Check installed again"));
359                    assert!(
360                        s.next_step_hint
361                            .contains("Earlier approvals are not replayed")
362                    );
363                }
364            }
365        }
366    }
367    #[test]
368    fn damaged_and_explicitly_closed_history_never_becomes_install_success() {
369        let mut a = Attempt {
370            id: "a".repeat(64),
371            scope: None,
372            outcome: Some(Outcome {
373                process: ProcessOutcome::Success,
374                package: PackageState::ExactPresent,
375                binary: BinaryState::Candidates,
376            }),
377            observed_versions: vec![],
378            problem: Some(super::super::Problem::Malformed),
379            unresolved: true,
380            explicitly_closed: false,
381            head: "hidden".into(),
382        };
383        assert_eq!(a.summary().status, Status::Unresolved);
384        assert_eq!(a.summary().next_step, NextStep::ReviewClosure);
385        a.unresolved = false;
386        a.explicitly_closed = true;
387        assert_eq!(a.summary().status, Status::ExplicitlyClosed);
388        let json = serde_json::to_string(&a).unwrap();
389        assert!(!json.contains("hidden"));
390        assert!(json.contains("explicitly_closed") && json.contains("root termination"));
391        a.unresolved = true;
392        assert_eq!(a.summary().status, Status::Unresolved);
393    }
394}