1use 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#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum ApplySelector {
31 Last,
33 Id(String),
35}
36
37impl ApplySelector {
38 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#[derive(Debug, Clone)]
50pub struct RollbackPlan {
51 pub apply_id: String,
52 pub apply_commit: CommitId,
54 pub restore_from: CommitId,
56 pub files: Vec<String>,
58 pub changed_since: Vec<String>,
60 pub latest: bool,
62}
63
64impl RollbackPlan {
65 pub fn needs_confirmation(&self) -> bool {
68 !self.latest && !self.changed_since.is_empty()
69 }
70}
71
72#[derive(Debug)]
74pub struct RollbackReport {
75 pub plan: RollbackPlan,
76 pub tag: String,
78 pub apply: ApplyReport,
79 pub commit: Option<CommitId>,
80 pub unavailable_originals: Vec<PathBuf>,
84}
85
86pub 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
102pub 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
157pub 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 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
224pub(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(¤t)? {
228 current = parent;
229 }
230 Ok(current)
231}
232
233fn 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}