phoebus_os/installer-rs/crates/phoebus-core/src/transaction.rs
Phoebus dedaa4bc48 fix: defects found by the VM install journey
- chooser: keep the plain Portage install atom and record the version
  separately. emerge rejects a bare versioned atom (app-misc/hello-2.12.3), so
  resolve/split now produce app-misc/hello + version 2.12.3.
- effects: parse emerge --unmerge --pretend output (it does not use the
  [ebuild] form), so sys remove has a concrete plan instead of being refused as
  unestablished.
- action: reject unknown fields on internally tagged unit variants
  (deny_unknown_fields does not cover them), closing a fail-closed gap.
- transaction: fsync the log so a completed outcome survives power loss and is
  not later read as an interrupted operation.
- serial-driver: import re at module level (do_boot used it unqualified).
2026-09-23 21:40:42 -07:00

293 lines
9.8 KiB
Rust

//! A user-queryable transaction log for assistant and `sys` actions.
//!
//! Snapshot history records recovery points; this records *what was run and
//! whether it succeeded*, including failures, so a later session can explain
//! what changed.
use std::path::Path;
use serde::{Deserialize, Serialize};
use crate::error::{CoreError, Result};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct TransactionRecord {
/// A stable id, assigned when the transaction begins. A record that never
/// gets a terminal result is an interrupted operation, not a success.
pub id: u64,
pub created_unix: u64,
/// Where the request came from: `sys` or `assistant`.
pub origin: String,
/// A short human-readable summary.
pub summary: String,
/// The validated typed actions that were attempted, rendered.
pub actions: Vec<String>,
/// `ok` or a failure description.
pub result: String,
/// The recovery point protecting the change, when one was made.
pub snapshot: Option<String>,
/// The reviewed plan digest, when effects were resolved.
pub digest: Option<String>,
/// Per-action outcomes in execution order: what completed, what failed and
/// what was never attempted (because an earlier action aborted the plan).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub outcomes: Vec<TransactionOutcome>,
}
/// The status of one action within a recorded transaction.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ActionStatus {
Completed,
Failed,
Unattempted,
}
/// One action's outcome. `detail` carries the failure reason for `failed`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct TransactionOutcome {
pub action: String,
pub status: ActionStatus,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub detail: Option<String>,
}
impl TransactionOutcome {
pub fn completed(action: impl Into<String>) -> Self {
Self {
action: action.into(),
status: ActionStatus::Completed,
detail: None,
}
}
pub fn failed(action: impl Into<String>, detail: impl Into<String>) -> Self {
Self {
action: action.into(),
status: ActionStatus::Failed,
detail: Some(detail.into()),
}
}
pub fn unattempted(action: impl Into<String>) -> Self {
Self {
action: action.into(),
status: ActionStatus::Unattempted,
detail: None,
}
}
}
impl Default for TransactionRecord {
fn default() -> Self {
Self {
id: 0,
created_unix: 0,
origin: String::new(),
summary: String::new(),
actions: Vec::new(),
result: "ok".into(),
snapshot: None,
digest: None,
outcomes: Vec::new(),
}
}
}
impl TransactionRecord {
/// `(completed, failed, unattempted)` counts for the recorded outcomes.
pub fn outcome_counts(&self) -> (usize, usize, usize) {
let mut completed = 0;
let mut failed = 0;
let mut unattempted = 0;
for outcome in &self.outcomes {
match outcome.status {
ActionStatus::Completed => completed += 1,
ActionStatus::Failed => failed += 1,
ActionStatus::Unattempted => unattempted += 1,
}
}
(completed, failed, unattempted)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct TransactionLog {
pub records: Vec<TransactionRecord>,
}
const MAX_RECORDS: usize = 500;
impl TransactionLog {
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))?;
if text.trim().is_empty() {
return Ok(Self::default());
}
Ok(toml::from_str(&text)?)
}
pub fn save(&self, path: &Path) -> Result<()> {
use std::io::Write;
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).map_err(|e| CoreError::io(parent, e))?;
}
let text = toml::to_string_pretty(self)?;
let mut file = std::fs::File::create(path).map_err(|e| CoreError::io(path, e))?;
file.write_all(text.as_bytes())
.map_err(|e| CoreError::io(path, e))?;
// Make the record durable: an operation's outcome (including a
// "finished" update to an "in progress" record) must survive a power
// loss, or the history would show a completed action as interrupted.
file.sync_all().map_err(|e| CoreError::io(path, e))?;
if let Some(parent) = path.parent() {
if let Ok(dir) = std::fs::File::open(parent) {
let _ = dir.sync_all();
}
}
Ok(())
}
/// Append a record, bounding the log so it cannot grow without limit.
pub fn append(&mut self, record: TransactionRecord) {
self.records.push(record);
if self.records.len() > MAX_RECORDS {
let overflow = self.records.len() - MAX_RECORDS;
self.records.drain(0..overflow);
}
}
pub fn render(&self) -> String {
if self.records.is_empty() {
return "no transactions recorded".to_string();
}
let mut out = String::new();
for r in &self.records {
out.push_str(&format!(
"{:<12} {:<10} {:<8} {}",
r.created_unix, r.origin, r.result, r.summary
));
if let Some(snap) = &r.snapshot {
out.push_str(&format!(" [snapshot {snap}]"));
}
if !r.outcomes.is_empty() {
let (done, failed, skipped) = r.outcome_counts();
out.push_str(&format!(
" [{done} completed, {failed} failed, {skipped} unattempted]"
));
}
out.push('\n');
for outcome in &r.outcomes {
out.push_str(&format!(" - {:?} {}", outcome.status, outcome.action));
if let Some(detail) = &outcome.detail {
out.push_str(&format!(": {detail}"));
}
out.push('\n');
}
}
out
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn roundtrip_and_render() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("transactions.toml");
let mut log = TransactionLog::default();
log.append(TransactionRecord {
id: 0,
created_unix: 10,
origin: "assistant".into(),
summary: "install vim".into(),
actions: vec!["install package app-editors/vim".into()],
result: "ok".into(),
snapshot: Some("@-x".into()),
digest: Some("abc".into()),
outcomes: Vec::new(),
});
log.save(&path).unwrap();
let loaded = TransactionLog::load(&path).unwrap();
assert_eq!(loaded, log);
assert!(loaded.render().contains("install vim"));
assert!(loaded.render().contains("@-x"));
}
#[test]
fn missing_and_corrupt_are_distinguished() {
let dir = tempfile::tempdir().unwrap();
assert!(TransactionLog::load(&dir.path().join("none.toml"))
.unwrap()
.records
.is_empty());
let path = dir.path().join("bad.toml");
std::fs::write(&path, "not = = toml [[[").unwrap();
assert!(TransactionLog::load(&path).is_err());
}
#[test]
fn outcomes_roundtrip_and_render() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("transactions.toml");
let mut log = TransactionLog::default();
log.append(TransactionRecord {
id: 0,
created_unix: 20,
origin: "assistant".into(),
summary: "install two".into(),
actions: vec!["install package a".into(), "install package b".into()],
result: "failed: boom".into(),
snapshot: Some("@-snap".into()),
digest: None,
outcomes: vec![
TransactionOutcome::completed("install package a"),
TransactionOutcome::failed("install package b", "boom"),
TransactionOutcome::unattempted("enable service c"),
],
});
log.save(&path).unwrap();
let loaded = TransactionLog::load(&path).unwrap();
assert_eq!(loaded, log);
assert_eq!(loaded.records[0].outcome_counts(), (1, 1, 1));
let text = loaded.render();
assert!(text.contains("1 completed, 1 failed, 1 unattempted"));
assert!(text.contains("Unattempted"));
}
#[test]
fn records_without_outcomes_still_load() {
// Backward compatibility: an older log has no `outcomes` key.
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("old.toml");
std::fs::write(
&path,
"[[records]]\ncreated_unix = 1\norigin = \"sys\"\nsummary = \"x\"\nresult = \"ok\"\n",
)
.unwrap();
let log = TransactionLog::load(&path).unwrap();
assert_eq!(log.records.len(), 1);
assert!(log.records[0].outcomes.is_empty());
assert_eq!(log.records[0].outcome_counts(), (0, 0, 0));
}
#[test]
fn log_is_bounded() {
let mut log = TransactionLog::default();
for i in 0..(MAX_RECORDS + 50) {
log.append(TransactionRecord {
created_unix: i as u64,
..Default::default()
});
}
assert_eq!(log.records.len(), MAX_RECORDS);
assert_eq!(log.records.first().unwrap().created_unix, 50);
}
}