Skip to main content

qualia_client_core/wellfair/
receipt.rs

1//! Typed policy receipts appended after durable WAL commits.
2
3use std::fs::{self, OpenOptions};
4use std::io::{BufRead, BufReader, Write};
5use std::path::{Path, PathBuf};
6
7use serde::{Deserialize, Serialize};
8
9use super::policy::DecisionResult;
10
11pub const RECEIPTS_FILE: &str = "wellfair/receipts.jsonl";
12pub const MAX_LIST: usize = 128;
13
14#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
15pub struct ReceiptRecord {
16    pub id: String,
17    pub timestamp_unix: u32,
18    pub qapp_id: String,
19    pub record_id: String,
20    pub decision: String,
21    pub obligations: Vec<String>,
22    pub checkpoint_hash: Option<String>,
23}
24
25pub struct ReceiptLog {
26    path: PathBuf,
27}
28
29impl ReceiptLog {
30    /// Opens.
31    pub fn open(storage_root: impl AsRef<Path>) -> std::io::Result<Self> {
32        let path = storage_root.as_ref().join(RECEIPTS_FILE);
33        if let Some(parent) = path.parent() {
34            fs::create_dir_all(parent)?;
35        }
36        if !path.exists() {
37            OpenOptions::new().create(true).write(true).open(&path)?;
38        }
39        Ok(Self { path })
40    }
41
42    /// Appends.
43    pub fn append(&self, record: &ReceiptRecord) -> std::io::Result<()> {
44        let line =
45            serde_json::to_string(record).map_err(|e| std::io::Error::other(e.to_string()))?;
46        let mut file = OpenOptions::new().append(true).open(&self.path)?;
47        writeln!(file, "{line}")?;
48        file.sync_all()?;
49        Ok(())
50    }
51
52    /// Lists recent entries.
53    pub fn list_recent(&self, limit: usize) -> std::io::Result<Vec<ReceiptRecord>> {
54        let file = fs::File::open(&self.path)?;
55        let reader = BufReader::new(file);
56        let mut records = Vec::new();
57        for line in reader.lines() {
58            let line = line?;
59            if line.trim().is_empty() {
60                continue;
61            }
62            if let Ok(record) = serde_json::from_str::<ReceiptRecord>(&line) {
63                records.push(record);
64            }
65        }
66        let keep = limit.min(MAX_LIST);
67        if records.len() > keep {
68            records.drain(0..records.len() - keep);
69        }
70        records.reverse();
71        Ok(records)
72    }
73}
74
75/// Receipt from a policy decision.
76pub fn receipt_from_decision(
77    qapp_id: &str,
78    record_id: &str,
79    timestamp_unix: u32,
80    decision: &DecisionResult,
81    checkpoint_hash: Option<[u8; 32]>,
82) -> ReceiptRecord {
83    let (decision_label, obligations) = match decision {
84        DecisionResult::Permit { obligations } => ("permit".to_string(), obligations.clone()),
85        DecisionResult::Deny { reasons } => ("deny".to_string(), reasons.clone()),
86        DecisionResult::Prompt { .. } => ("prompt".to_string(), vec![]),
87        DecisionResult::Suspend { required_approvals } => (
88            "suspend".to_string(),
89            vec![format!("approvals:{required_approvals}")],
90        ),
91    };
92    ReceiptRecord {
93        id: format!(
94            "rcpt-{timestamp_unix}-{}",
95            &record_id[record_id.len().saturating_sub(8)..]
96        ),
97        timestamp_unix,
98        qapp_id: qapp_id.to_string(),
99        record_id: record_id.to_string(),
100        decision: decision_label,
101        obligations,
102        checkpoint_hash: checkpoint_hash.map(hex::encode),
103    }
104}
105
106#[cfg(test)]
107mod tests {
108    use super::*;
109
110    #[test]
111    fn receipt_log_appends() {
112        let dir = tempfile::tempdir().unwrap();
113        let log = ReceiptLog::open(dir.path()).unwrap();
114        let record = receipt_from_decision(
115            "wellfair-health",
116            "urn:wellfair:weight:x",
117            100,
118            &DecisionResult::Permit {
119                obligations: vec!["emit_wal_receipt".into()],
120            },
121            None,
122        );
123        log.append(&record).unwrap();
124        assert_eq!(log.list_recent(5).unwrap().len(), 1);
125    }
126}