Skip to main content

dort_core/environment/
run.rs

1use super::*;
2use crate::lifecycle;
3
4#[derive(Clone, Serialize, Deserialize)]
5#[serde(tag = "state", rename_all = "snake_case")]
6enum StepState {
7    Pending,
8    InProgress {
9        check: String,
10    },
11    Confirmed {
12        proof: String,
13        operation: Option<String>,
14    },
15    Uncertain {
16        check: String,
17    },
18}
19impl StepState {
20    fn label(&self) -> &'static str {
21        match self {
22            Self::Pending => "Pending",
23            Self::Confirmed { .. } => "Confirmed",
24            Self::Uncertain { .. } | Self::InProgress { .. } => "Uncertain",
25        }
26    }
27}
28#[derive(Clone, Serialize, Deserialize)]
29pub(super) struct Step {
30    item: Item,
31    approved: String,
32    #[serde(skip_serializing_if = "Option::is_none")]
33    source: Option<Entry>,
34    #[serde(skip_serializing_if = "Option::is_none")]
35    destination: Option<Entry>,
36    progress: StepState,
37}
38#[derive(Clone, Serialize, Deserialize)]
39pub struct Run {
40    id: String,
41    input: String,
42    steps: Vec<Step>,
43    problem: Option<String>,
44    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
45    pub(super) abandoned: bool,
46    #[serde(default, skip_serializing_if = "Option::is_none")]
47    pub(super) stale_check: Option<String>,
48}
49impl Run {
50    pub fn latest(host: &HostContext, root: &Path) -> Result<Option<Self>> {
51        let local = LocalConfig::load(host)?;
52        let id = local
53            .repositories
54            .iter()
55            .find(|(_, record)| record.root == root)
56            .map(|(id, _)| id)
57            .ok_or_else(|| invalid("Choose a registered repository."))?;
58        directory(host, id, false)?
59            .map(|dir| read(&dir, "run.json"))
60            .transpose()
61            .map(Option::flatten)
62    }
63
64    fn uncertain_tool(&self) -> bool {
65        self.steps.iter().any(|step| {
66            matches!(step.item, Item::Tool(_))
67                && matches!(
68                    step.progress,
69                    StepState::InProgress { .. } | StepState::Uncertain { .. }
70                )
71        })
72    }
73
74    pub(super) fn review_resume(&self, plan: &Plan) -> Vec<String> {
75        if self.abandoned {
76            return vec!["This run was abandoned. Review a new environment plan.".into()];
77        }
78        if self.complete() {
79            return vec!["The last run is complete. Review a new plan.".into()];
80        }
81        if self.input != plan.input.stamp || self.steps.len() != plan.rows.len() {
82            return vec!["Manifest or profile choices changed. Review a new plan.".into()];
83        }
84        self.steps
85            .iter()
86            .zip(&plan.rows)
87            .filter_map(|(step, row)| {
88                verify(step, row, plan.check.as_ref())
89                    .err()
90                    .map(|error| error.to_string())
91            })
92            .collect()
93    }
94
95    pub fn abandoned(&self) -> bool {
96        self.abandoned
97    }
98
99    pub fn complete(&self) -> bool {
100        self.problem.is_none()
101            && self
102                .steps
103                .iter()
104                .all(|step| matches!(step.progress, StepState::Confirmed { .. }))
105    }
106    pub fn human(&self) -> String {
107        let mut text = format!(
108            "Environment run {}{}\n",
109            self.id,
110            if self.abandoned { " (abandoned)" } else { "" }
111        );
112        for step in &self.steps {
113            text.push_str(&format!("{}: {}\n", step.item.id(), step.progress.label()));
114        }
115        if let Some(problem) = &self.problem {
116            text.push_str(problem);
117        }
118        text
119    }
120}
121
122#[derive(Serialize)]
123pub struct AbandonPreview {
124    repository: PathBuf,
125    archive: PathBuf,
126    run: Run,
127    new_stale_check: Option<String>,
128    #[serde(skip)]
129    original: String,
130}
131
132impl AbandonPreview {
133    pub fn prepare(host: &HostContext, root: &Path) -> Result<Self> {
134        let local = LocalConfig::load(host)?;
135        let id = local
136            .repositories
137            .iter()
138            .find(|(_, record)| record.root == root)
139            .map(|(id, _)| id)
140            .ok_or_else(|| invalid("Choose a registered repository."))?;
141        let dir =
142            directory(host, id, false)?.ok_or_else(|| invalid("No unfinished environment run."))?;
143        if observation::inspect(&dir.path.join("run.json"), false)?.kind == Kind::Missing {
144            return Err(invalid("No unfinished environment run."));
145        }
146        let original = String::from_utf8(journal::read_bytes(&dir, "run.json")?)
147            .map_err(|_| invalid("Cannot read the saved environment record."))?;
148        let run: Run = serde_json::from_str(&original)
149            .map_err(|_| invalid("Cannot read the saved environment record."))?;
150        if run.complete() || run.abandoned {
151            return Err(invalid("No unfinished environment run."));
152        }
153        let new_stale_check = if run.uncertain_tool() {
154            read::<Check>(&dir, "check.json")?.map(|c| c.generation)
155        } else {
156            run.stale_check.clone()
157        };
158        Ok(Self {
159            repository: root.to_owned(),
160            archive: dir.path.join(format!(
161                "abandoned-{}.json",
162                journal::digest(original.as_bytes())
163            )),
164            run,
165            new_stale_check,
166            original,
167        })
168    }
169
170    pub fn repository(&self) -> &Path {
171        &self.repository
172    }
173
174    pub fn human(&self) -> String {
175        format!(
176            "Repository: {:?}\n\n{}\n\nKeep the old record at {:?} and mark this run abandoned.\nKeep completed effects in place. No file or package is changed.\nBefore retrying an uncertain install, close any unresolved record in Tools History, run Environment check, then review a new plan.",
177            self.repository,
178            self.run.human(),
179            self.archive
180        )
181    }
182
183    pub fn approve(self) -> AbandonApproval {
184        AbandonApproval(self)
185    }
186}
187
188pub struct AbandonApproval(AbandonPreview);
189
190impl AbandonApproval {
191    pub fn execute(self, host: &HostContext) -> Result<Run> {
192        let _lock = WriterLock::acquire(host)?;
193        let p = self.0;
194        let fresh = AbandonPreview::prepare(host, &p.repository)?;
195        if digest(&p)? != digest(&fresh)? {
196            return Err(invalid(
197                "Environment run or check changed. Review abandonment again.",
198            ));
199        }
200        let dir = PrivateDir::open(p.archive.parent().expect("archive has parent"), false)?
201            .ok_or_else(|| invalid("Environment record directory is missing."))?;
202        let name = p
203            .archive
204            .file_name()
205            .and_then(|s| s.to_str())
206            .expect("generated archive name");
207        dir.replace(name, &p.original)?;
208        let mut run = p.run;
209        run.abandoned = true;
210        run.stale_check = p.new_stale_check;
211        save(&dir, "run.json", &run)?;
212        Ok(run)
213    }
214}
215
216impl PreparedRow {
217    pub(super) fn step(&self) -> Result<Step> {
218        let approved = if let Some(p) = &self.install {
219            install::preview_binding(p)?
220        } else if self.file.is_some() {
221            digest(&self.row)?
222        } else {
223            self.proof.clone().unwrap_or_default()
224        };
225        Ok(Step {
226            item: self.row.item.clone(),
227            approved,
228            source: self
229                .file
230                .as_ref()
231                .and_then(|f| f.source.clone())
232                .map(Entry::stable_parents),
233            destination: self
234                .file
235                .as_ref()
236                .and_then(|f| f.destination.clone())
237                .map(Entry::stable_parents),
238            progress: StepState::Pending,
239        })
240    }
241}
242
243pub struct Approval(Preview);
244
245impl Approval {
246    pub(super) fn new(preview: Preview) -> Self {
247        Self(preview)
248    }
249}
250
251fn same_destination(old: &Entry, fresh: &Entry) -> bool {
252    if old.kind != Kind::Missing {
253        return same(old, fresh);
254    }
255    old.path == fresh.path
256        && fresh.kind == Kind::Missing
257        && old.parents.len() <= fresh.parents.len()
258        && old.parents.iter().zip(&fresh.parents).all(|(a, b)| {
259            a.path == b.path && adoption::parent_identity(&a.fingerprint, &b.fingerprint)
260        })
261}
262
263fn verify(step: &Step, row: &PreparedRow, check: Option<&Check>) -> Result<()> {
264    let changed = || invalid(format!("{} changed. Review a new plan.", step.item.id()));
265    if step.item != row.row.item {
266        return Err(changed());
267    }
268    if !row.row.blockers.is_empty()
269        && !matches!(
270            step.progress,
271            StepState::InProgress { .. } | StepState::Uncertain { .. }
272        )
273    {
274        return Err(changed());
275    }
276    if let Some(file) = &row.file
277        && !step
278            .source
279            .as_ref()
280            .zip(file.source.as_ref())
281            .is_some_and(|(a, b)| same(a, b))
282    {
283        return Err(changed());
284    }
285    match &step.progress {
286        StepState::Pending => {
287            if let Some(file) = &row.file {
288                if step.approved == row.step()?.approved
289                    && step
290                        .destination
291                        .as_ref()
292                        .zip(file.destination.as_ref())
293                        .is_some_and(|(a, b)| same_destination(a, b))
294                {
295                    return Ok(());
296                }
297            } else if step.approved == row.step()?.approved {
298                return Ok(());
299            }
300            Err(changed())
301        }
302        StepState::Confirmed { proof, .. } if row.proof.as_ref() == Some(proof) => Ok(()),
303        StepState::Confirmed { .. } => Err(changed()),
304        StepState::InProgress { check: before } | StepState::Uncertain { check: before } => {
305            let fresh_check = check.is_some_and(|check| check.generation != *before);
306            if row.proof.is_some() && (matches!(step.item, Item::File(_)) || fresh_check) {
307                Ok(())
308            } else {
309                Err(invalid(format!(
310                    "{} is uncertain. Check or repair it before resuming.",
311                    step.item.id()
312                )))
313            }
314        }
315    }
316}
317
318fn refresh(host: &HostContext, input: &Inputs, check: &mut Check) -> Result<()> {
319    for catalog in &mut check.catalogs {
320        if !catalog.current() {
321            return Err(invalid(
322                "Package manager changed. Run Environment check and review again.",
323            ));
324        }
325        let report = catalog.scope.preview(&host.home)?.approve().inspect();
326        if !catalog.current() {
327            return Err(invalid("Package manager changed during the check."));
328        }
329        catalog.observation = report.observation;
330    }
331    let current = Inputs::read(
332        host,
333        &input.files.repository,
334        &input.files.temporary_profiles,
335    )?;
336    if current.stamp != input.stamp {
337        return Err(invalid(
338            "Manifest or profile choices changed. Review a new plan.",
339        ));
340    }
341    check.when = now();
342    Ok(())
343}
344
345impl Approval {
346    pub fn execute(
347        self,
348        host: &HostContext,
349        mut observer: impl FnMut(&adoption::Event) -> Result<()>,
350    ) -> Result<Run> {
351        let lock = WriterLock::acquire(host)?;
352        journal::ensure_writable(host)?;
353        let p = self.0;
354        let root = &p.plan.input.files.repository;
355        let temporary = &p.plan.input.files.temporary_profiles;
356        let fresh = Preview::prepare(host, root, temporary, p.resume)?;
357        if fresh.blocked() || fresh.binding()? != p.binding()? {
358            return Err(invalid("Environment review changed. Review again."));
359        }
360        let dir = directory(host, &fresh.plan.input.repository_id, true)?
361            .expect("created environment directory");
362        let input = fresh.plan.input.stamp.clone();
363        let mut run = if p.resume {
364            fresh.previous.ok_or_else(|| invalid("No run to resume."))?
365        } else {
366            Run {
367                id: adoption::transaction_id(),
368                input: input.clone(),
369                steps: fresh
370                    .plan
371                    .rows
372                    .iter()
373                    .map(PreparedRow::step)
374                    .collect::<Result<_>>()?,
375                problem: None,
376                abandoned: false,
377                stale_check: fresh.previous.and_then(|run| run.stale_check),
378            }
379        };
380        run.problem = None;
381        save(&dir, "run.json", &run)?;
382        let mut check = fresh.plan.check;
383        for idx in 0..run.steps.len() {
384            let result = (|| {
385                let current = Inputs::read(host, root, temporary)?;
386                if current.stamp != input {
387                    return Err(invalid(
388                        "Manifest or profile choices changed. Review a new plan.",
389                    ));
390                }
391                if let Some(check) = &mut check {
392                    refresh(host, &current, check)?;
393                }
394                let current =
395                    Plan::from_check(host, Inputs::read(host, root, temporary)?, check.clone())?;
396                if current.input.stamp != input || current.rows.len() != run.steps.len() {
397                    return Err(invalid("Environment inputs changed. Review a new plan."));
398                }
399                for (step, row) in run.steps.iter().zip(&current.rows) {
400                    verify(step, row, check.as_ref())?;
401                }
402                let step = &run.steps[idx];
403                let row = &current.rows[idx];
404                if matches!(step.progress, StepState::Confirmed { .. }) {
405                    return Ok(());
406                }
407                if let Some(proof) = &row.proof {
408                    if matches!(
409                        step.progress,
410                        StepState::InProgress { .. } | StepState::Uncertain { .. }
411                    ) && p.plan.rows[idx].proof.as_ref() != Some(proof)
412                    {
413                        return Err(invalid(
414                            "The checked version or file changed. Review again.",
415                        ));
416                    }
417                    run.steps[idx].progress = StepState::Confirmed {
418                        proof: proof.clone(),
419                        operation: None,
420                    };
421                    return save(&dir, "run.json", &run);
422                }
423                let check_id = check
424                    .as_ref()
425                    .map(|c| c.generation.clone())
426                    .unwrap_or_default();
427                run.steps[idx].progress = StepState::InProgress {
428                    check: check_id.clone(),
429                };
430                save(&dir, "run.json", &run)?;
431                let mut rows = current.rows;
432                let row = rows.swap_remove(idx);
433                let operation = match (row.row.item, row.install) {
434                    (Item::Tool(_), Some(install)) => {
435                        let outcome = install::execute(host, &lock, install.approve(), |_| ())?;
436                        if !outcome.no_op
437                            && !outcome.outcome.is_some_and(install::Outcome::succeeded)
438                        {
439                            return Err(invalid(
440                                "Install result is uncertain. Check or repair the tool before resuming.",
441                            ));
442                        }
443                        outcome.attempt_id
444                    }
445                    (Item::File(id), None) => {
446                        let mut snapshot = current.input.files;
447                        snapshot.files.retain(|file| file.mapping.id == id);
448                        lifecycle::execute_environment(
449                            host,
450                            &lock,
451                            planner::plan_environment(snapshot),
452                            &id,
453                            &mut observer,
454                        )?
455                    }
456                    _ => return Err(invalid("No approved step is available. Review again.")),
457                };
458                let after = Inputs::read(host, root, temporary)?;
459                if after.stamp != input {
460                    return Err(invalid("Environment inputs changed while the step ran."));
461                }
462                if matches!(run.steps[idx].item, Item::Tool(_))
463                    && let Some(check) = &mut check
464                {
465                    refresh(host, &after, check)?;
466                }
467                let confirmed = Plan::from_check(host, after, check.clone())?;
468                let proof = confirmed
469                    .rows
470                    .get(idx)
471                    .and_then(|row| row.proof.clone())
472                    .ok_or_else(|| {
473                        invalid("Result is uncertain. Check or repair the step before resuming.")
474                    })?;
475                if let Some(check) = &check {
476                    save(&dir, "check.json", check)?;
477                }
478                run.steps[idx].progress = StepState::Confirmed { proof, operation };
479                save(&dir, "run.json", &run)
480            })();
481            if let Err(error) = result {
482                if let StepState::InProgress { check } = &run.steps[idx].progress {
483                    run.steps[idx].progress = StepState::Uncertain {
484                        check: check.clone(),
485                    };
486                }
487                let diagnostic = match error {
488                    Error::Parse(_) => {
489                        "Manifest became invalid. Fix dort.toml and review again.".into()
490                    }
491                    error => error.to_string(),
492                };
493                run.problem = Some(diagnostic);
494                save(&dir, "run.json", &run)?;
495                break;
496            }
497        }
498        Ok(run)
499    }
500}