phoebus_os/installer-rs/crates/phoebus-core/src/snapshot.rs

139 lines
4.3 KiB
Rust

//! Btrfs snapshot naming and transaction history.
//!
//! This is the real foundation for rollback: snapshots are named
//! deterministically, recorded in a machine-readable history, and only
//! committed once the operation that produced them succeeds. Rollback itself
//! is intentionally not claimed here; see the executor's snapshot module.
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::error::{CoreError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SnapshotStatus {
Created,
Committed,
RolledBack,
Failed,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SnapshotRecord {
pub id: String,
pub created_unix: u64,
pub operation: String,
pub source_subvol: String,
pub snapshot_subvol: String,
pub status: SnapshotStatus,
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct SnapshotHistory {
pub records: Vec<SnapshotRecord>,
}
impl SnapshotHistory {
pub fn load(path: &Path) -> Result<Self> {
if !path.exists() {
return Ok(Self::default());
}
let text = std::fs::read_to_string(path).map_err(|e| CoreError::io(path, e))?;
let history: SnapshotHistory = toml::from_str(&text)?;
Ok(history)
}
pub fn save(&self, path: &Path) -> Result<()> {
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent, e))?;
}
std::fs::write(path, toml::to_string_pretty(self)?).map_err(|e| CoreError::io(path, e))?;
Ok(())
}
pub fn append(&mut self, record: SnapshotRecord) {
self.records.push(record);
}
pub fn latest(&self) -> Option<&SnapshotRecord> {
self.records.last()
}
}
/// A deterministic snapshot name: `<subvol>-<utc>-<operation>`.
pub fn snapshot_name(subvol: &str, unix_seconds: u64, operation: &str) -> String {
let slug: String = operation
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
let slug = slug.trim_matches('-').to_string();
format!("{subvol}-{}-{}", compact_utc(unix_seconds), slug)
}
/// `YYYYMMDDTHHMMSS` in UTC.
pub fn compact_utc(unix_seconds: u64) -> String {
let days = (unix_seconds / 86_400) as i64;
let rem = unix_seconds % 86_400;
let (y, m, d) = civil_from_days(days);
format!(
"{y:04}{m:02}{d:02}T{:02}{:02}{:02}",
rem / 3600,
(rem % 3600) / 60,
rem % 60
)
}
fn civil_from_days(z: i64) -> (i64, u32, u32) {
let z = z + 719_468;
let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
let doe = z - era * 146_097;
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
(if m <= 2 { y + 1 } else { y }, m, d)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names_are_deterministic_and_safe() {
let name = snapshot_name("@", 1_700_000_000, "sys update");
assert_eq!(name, "@-20231114T221320-sys-update");
assert!(!name.contains(' '));
assert!(!name.contains('/'));
}
#[test]
fn history_roundtrip() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("history.toml");
let mut history = SnapshotHistory::default();
history.append(SnapshotRecord {
id: "1".into(),
created_unix: 1_700_000_000,
operation: "sys update".into(),
source_subvol: "@".into(),
snapshot_subvol: "@-20231114T221320-sys-update".into(),
status: SnapshotStatus::Committed,
});
history.save(&path).unwrap();
let loaded = SnapshotHistory::load(&path).unwrap();
assert_eq!(loaded, history);
assert_eq!(loaded.latest().unwrap().status, SnapshotStatus::Committed);
}
#[test]
fn missing_history_is_empty() {
let dir = tempfile::tempdir().unwrap();
let history = SnapshotHistory::load(&dir.path().join("nope.toml")).unwrap();
assert!(history.records.is_empty());
}
}