274 lines
9 KiB
Rust
274 lines
9 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 {
|
|
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 {
|
|
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<()> {
|
|
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(())
|
|
}
|
|
|
|
/// 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 {
|
|
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 {
|
|
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);
|
|
}
|
|
}
|