use std::path::PathBuf;
use crate::apply::exec::{ApplyReport, ApplyRequest, apply_in};
use crate::apply::plan::PlanOptions;
use crate::apply::{ApplyEnv, backup};
use crate::error::{CoreError, ErrorCode};
use crate::model::applied::ApplyTrigger;
use crate::store::diff::trailer_entities;
use crate::store::{CommitId, LogEntry, LogFilter, Machine, Operation, Store};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ApplySelector {
Last,
Id(String),
}
impl ApplySelector {
pub fn parse(text: &str) -> Self {
if text == "last" {
Self::Last
} else {
Self::Id(text.to_owned())
}
}
}
#[derive(Debug, Clone)]
pub struct RollbackPlan {
pub apply_id: String,
pub apply_commit: CommitId,
pub restore_from: CommitId,
pub files: Vec<String>,
pub changed_since: Vec<String>,
pub latest: bool,
}
impl RollbackPlan {
pub fn needs_confirmation(&self) -> bool {
!self.latest && !self.changed_since.is_empty()
}
}
#[derive(Debug)]
pub struct RollbackReport {
pub plan: RollbackPlan,
pub tag: String,
pub apply: ApplyReport,
pub commit: Option<CommitId>,
pub unavailable_originals: Vec<PathBuf>,
}
pub fn apply_commits(store: &Store<'_>, machine_id: &str) -> Result<Vec<LogEntry>, CoreError> {
Ok(store
.log(&LogFilter::default())?
.into_iter()
.filter(|entry| {
entry.trailers.apply.is_some()
&& entry
.trailers
.machine
.as_ref()
.is_some_and(|machine| machine.id == machine_id)
})
.collect())
}
pub fn prepare(
store: &Store<'_>,
machine_id: &str,
selector: &ApplySelector,
) -> Result<RollbackPlan, CoreError> {
let applies = apply_commits(store, machine_id)?;
let index = match selector {
ApplySelector::Last => (!applies.is_empty()).then_some(0),
ApplySelector::Id(id) => applies.iter().position(|entry| {
entry
.trailers
.apply
.as_ref()
.is_some_and(|apply| apply.id.eq_ignore_ascii_case(id))
}),
};
let Some(index) = index else {
return Err(CoreError::new(
ErrorCode::NotFound,
match selector {
ApplySelector::Last => "this machine has no apply run to roll back".to_owned(),
ApplySelector::Id(id) => format!("no apply run {id:?} on this machine"),
},
));
};
let run = &applies[index];
let restore_from = match applies.get(index + 1) {
Some(previous) => previous.id.clone(),
None => initial_commit(store, &run.id)?,
};
let files: Vec<String> = store
.changed_files(&restore_from, &run.id)?
.into_iter()
.filter(|file| desired_state_file(file, machine_id))
.collect();
let head = store.head()?;
let at_run = store.revision(&run.id)?;
let at_head = store.revision(&head)?;
let mut changed_since = Vec::new();
for file in &files {
if at_run.read_bytes(file)? != at_head.read_bytes(file)? {
changed_since.push(file.clone());
}
}
Ok(RollbackPlan {
apply_id: run.trailers.apply.as_ref().expect("filtered").id.clone(),
apply_commit: run.id.clone(),
restore_from,
files,
changed_since,
latest: index == 0,
})
}
pub fn rollback(
store: &Store<'_>,
ax: &ApplyEnv<'_>,
selector: &ApplySelector,
confirmed: bool,
) -> Result<RollbackReport, CoreError> {
let machine = Machine::load(ax.fs, &ax.home.state_dir())?.ok_or_else(|| {
CoreError::new(
ErrorCode::NotFound,
"this machine has no apply run to roll back",
)
})?;
let plan = prepare(store, &machine.id, selector)?;
if plan.needs_confirmation() && !confirmed {
return Err(CoreError::new(
ErrorCode::ConfirmationRequired,
format!(
"later commits changed {} since apply {}; confirm to roll back over them",
plan.changed_since.join(", "),
plan.apply_id
),
));
}
let tag = store.create_auto_tag("pre-rollback")?;
let mut operation = Operation::new(
"apply.rollback",
format!("rollback: apply {}", plan.apply_id),
);
for entity in trailer_entities(&plan.files) {
operation = operation.entity(entity);
}
let request = ApplyRequest {
options: PlanOptions::default(),
trigger: ApplyTrigger::Rollback,
};
let committed = store.transaction(operation, |tx| {
let source = tx.store().revision(&plan.restore_from)?;
let mut contents = Vec::with_capacity(plan.files.len());
for file in &plan.files {
contents.push((file.clone(), source.read_bytes(file)?));
}
drop(source);
for (file, content) in contents {
match content {
Some(bytes) => tx.write(&file, bytes)?,
None => tx.remove(&file)?,
}
}
apply_in(tx, ax, &request)
})?;
let unavailable_originals =
backup::removed_backups(ax.fs, &ax.home.state_dir(), &plan.apply_id).unwrap_or_default();
Ok(RollbackReport {
plan,
tag,
apply: committed.value,
commit: committed.commit,
unavailable_originals,
})
}
pub(crate) fn initial_commit(store: &Store<'_>, from: &CommitId) -> Result<CommitId, CoreError> {
let mut current = from.clone();
while let Some(parent) = store.first_parent(¤t)? {
current = parent;
}
Ok(current)
}
fn desired_state_file(file: &str, machine_id: &str) -> bool {
match file.strip_prefix("machines/") {
Some(name) => name == format!("{machine_id}.toml"),
None => true,
}
}