Skip to main content

surjection_core/apply/
rollback.rs

1//! One-click rollback of an apply run (SPEC 8.7).
2//!
3//! An apply run is found by its `Surjection-Apply` trailer. Rolling it back
4//! restores, in a new commit, every desired-state file the run changed to
5//! the state this machine had applied before it, then applies that commit
6//! through the normal planner, so ownership rules hold: entries the run
7//! created are removed only when unchanged since, and foreign entries are
8//! never touched. History is never rewritten; `auto/pre-rollback/<ts>`
9//! marks the commit before the rollback.
10//!
11//! "Applied before it" is the nearest earlier apply commit of this machine,
12//! or the initial commit. In instant mode, where every edit is its own apply
13//! commit, that is the parent of the apply commit; in review mode it also
14//! covers the edits the run applied, which the parent commit already holds.
15//! Other machines' files and every `*.applied.toml` are left alone. Rolling
16//! back a rollback restores the original.
17
18use std::path::PathBuf;
19
20use crate::apply::exec::{ApplyReport, ApplyRequest, apply_in};
21use crate::apply::plan::PlanOptions;
22use crate::apply::{ApplyEnv, backup};
23use crate::error::{CoreError, ErrorCode};
24use crate::model::applied::ApplyTrigger;
25use crate::store::diff::trailer_entities;
26use crate::store::{CommitId, LogEntry, LogFilter, Machine, Operation, Store};
27
28/// Which apply run to roll back.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum ApplySelector {
31    /// This machine's latest apply run.
32    Last,
33    /// An apply id.
34    Id(String),
35}
36
37impl ApplySelector {
38    /// `last` or an apply id.
39    pub fn parse(text: &str) -> Self {
40        if text == "last" {
41            Self::Last
42        } else {
43            Self::Id(text.to_owned())
44        }
45    }
46}
47
48/// What a rollback restores.
49#[derive(Debug, Clone)]
50pub struct RollbackPlan {
51    pub apply_id: String,
52    /// The commit that carries the run's trailer.
53    pub apply_commit: CommitId,
54    /// The commit whose desired state is restored.
55    pub restore_from: CommitId,
56    /// Store files restored (store-relative).
57    pub files: Vec<String>,
58    /// Restored files that commits after the run changed too.
59    pub changed_since: Vec<String>,
60    /// Whether the run is this machine's latest apply run.
61    pub latest: bool,
62}
63
64impl RollbackPlan {
65    /// Rolling back an older run over later changes to the same files
66    /// needs an explicit confirmation; the latest run never asks.
67    pub fn needs_confirmation(&self) -> bool {
68        !self.latest && !self.changed_since.is_empty()
69    }
70}
71
72/// The result of a rollback.
73#[derive(Debug)]
74pub struct RollbackReport {
75    pub plan: RollbackPlan,
76    /// The `auto/pre-rollback/<ts>` tag.
77    pub tag: String,
78    pub apply: ApplyReport,
79    pub commit: Option<CommitId>,
80    /// Client files whose content from before the run is no longer kept:
81    /// their backup of that run held old secret values and was removed on
82    /// request (M35), so `restore --files` cannot bring it back either.
83    pub unavailable_originals: Vec<PathBuf>,
84}
85
86/// This machine's apply commits, newest first.
87pub fn apply_commits(store: &Store<'_>, machine_id: &str) -> Result<Vec<LogEntry>, CoreError> {
88    Ok(store
89        .log(&LogFilter::default())?
90        .into_iter()
91        .filter(|entry| {
92            entry.trailers.apply.is_some()
93                && entry
94                    .trailers
95                    .machine
96                    .as_ref()
97                    .is_some_and(|machine| machine.id == machine_id)
98        })
99        .collect())
100}
101
102/// Works out what rolling back `selector` restores. Read-only.
103pub fn prepare(
104    store: &Store<'_>,
105    machine_id: &str,
106    selector: &ApplySelector,
107) -> Result<RollbackPlan, CoreError> {
108    let applies = apply_commits(store, machine_id)?;
109    let index = match selector {
110        ApplySelector::Last => (!applies.is_empty()).then_some(0),
111        ApplySelector::Id(id) => applies.iter().position(|entry| {
112            entry
113                .trailers
114                .apply
115                .as_ref()
116                .is_some_and(|apply| apply.id.eq_ignore_ascii_case(id))
117        }),
118    };
119    let Some(index) = index else {
120        return Err(CoreError::new(
121            ErrorCode::NotFound,
122            match selector {
123                ApplySelector::Last => "this machine has no apply run to roll back".to_owned(),
124                ApplySelector::Id(id) => format!("no apply run {id:?} on this machine"),
125            },
126        ));
127    };
128    let run = &applies[index];
129    let restore_from = match applies.get(index + 1) {
130        Some(previous) => previous.id.clone(),
131        None => initial_commit(store, &run.id)?,
132    };
133    let files: Vec<String> = store
134        .changed_files(&restore_from, &run.id)?
135        .into_iter()
136        .filter(|file| desired_state_file(file, machine_id))
137        .collect();
138    let head = store.head()?;
139    let at_run = store.revision(&run.id)?;
140    let at_head = store.revision(&head)?;
141    let mut changed_since = Vec::new();
142    for file in &files {
143        if at_run.read_bytes(file)? != at_head.read_bytes(file)? {
144            changed_since.push(file.clone());
145        }
146    }
147    Ok(RollbackPlan {
148        apply_id: run.trailers.apply.as_ref().expect("filtered").id.clone(),
149        apply_commit: run.id.clone(),
150        restore_from,
151        files,
152        changed_since,
153        latest: index == 0,
154    })
155}
156
157/// Rolls back an apply run: tag, restore, apply, one commit. Fails with
158/// `confirmation_required` when [`RollbackPlan::needs_confirmation`] and
159/// `confirmed` is false.
160pub fn rollback(
161    store: &Store<'_>,
162    ax: &ApplyEnv<'_>,
163    selector: &ApplySelector,
164    confirmed: bool,
165) -> Result<RollbackReport, CoreError> {
166    let machine = Machine::load(ax.fs, &ax.home.state_dir())?.ok_or_else(|| {
167        CoreError::new(
168            ErrorCode::NotFound,
169            "this machine has no apply run to roll back",
170        )
171    })?;
172    let plan = prepare(store, &machine.id, selector)?;
173    if plan.needs_confirmation() && !confirmed {
174        return Err(CoreError::new(
175            ErrorCode::ConfirmationRequired,
176            format!(
177                "later commits changed {} since apply {}; confirm to roll back over them",
178                plan.changed_since.join(", "),
179                plan.apply_id
180            ),
181        ));
182    }
183    let tag = store.create_auto_tag("pre-rollback")?;
184
185    let mut operation = Operation::new(
186        "apply.rollback",
187        format!("rollback: apply {}", plan.apply_id),
188    );
189    for entity in trailer_entities(&plan.files) {
190        operation = operation.entity(entity);
191    }
192    let request = ApplyRequest {
193        options: PlanOptions::default(),
194        trigger: ApplyTrigger::Rollback,
195    };
196    let committed = store.transaction(operation, |tx| {
197        let source = tx.store().revision(&plan.restore_from)?;
198        let mut contents = Vec::with_capacity(plan.files.len());
199        for file in &plan.files {
200            contents.push((file.clone(), source.read_bytes(file)?));
201        }
202        drop(source);
203        for (file, content) in contents {
204            match content {
205                Some(bytes) => tx.write(&file, bytes)?,
206                None => tx.remove(&file)?,
207            }
208        }
209        apply_in(tx, ax, &request)
210    })?;
211    // The rollback is committed: a run result that cannot be read only
212    // leaves the note out.
213    let unavailable_originals =
214        backup::removed_backups(ax.fs, &ax.home.state_dir(), &plan.apply_id).unwrap_or_default();
215    Ok(RollbackReport {
216        plan,
217        tag,
218        apply: committed.value,
219        commit: committed.commit,
220        unavailable_originals,
221    })
222}
223
224/// The root commit reached by first parents from `from`.
225pub(crate) fn initial_commit(store: &Store<'_>, from: &CommitId) -> Result<CommitId, CoreError> {
226    let mut current = from.clone();
227    while let Some(parent) = store.first_parent(&current)? {
228        current = parent;
229    }
230    Ok(current)
231}
232
233/// Desired state of this machine: everything but apply records and other
234/// machines' overlays.
235fn desired_state_file(file: &str, machine_id: &str) -> bool {
236    match file.strip_prefix("machines/") {
237        Some(name) => name == format!("{machine_id}.toml"),
238        None => true,
239    }
240}