diff --git a/crates/ledger-gui/src/attention.rs b/crates/ledger-gui/src/attention.rs index ea0b1741..148228f0 100644 --- a/crates/ledger-gui/src/attention.rs +++ b/crates/ledger-gui/src/attention.rs @@ -89,7 +89,7 @@ impl ledger_package::PackageBooks for View<'_> { } fn journal_seq(&self) -> u64 { - self.0.journal.len() as u64 + self.0.head_seq } fn journal(&self) -> Result, StoreError> { diff --git a/crates/ledger-gui/src/books.rs b/crates/ledger-gui/src/books.rs index badf7e37..2399bfc2 100644 --- a/crates/ledger-gui/src/books.rs +++ b/crates/ledger-gui/src/books.rs @@ -274,7 +274,20 @@ pub struct Books { pub settings: BooksSettings, pub data_dir: PathBuf, pub attachments: Vec, + /// The committed journal: the lines that are facts of the books (those + /// outside any call and those of calls that closed `ok`), the frame + /// lines left out. Every fact the viewer derives from the journal + /// (an entry's events and origin, an asset's trail, a party's events) + /// comes from here, never from [`Books::history`]: ids are handed out + /// again after a failed call, so a dead line would be pinned on + /// whatever takes the id next (ledger_store::calls). pub journal: Vec, + /// Every line of the journal, in order (seq = index + 1), and each + /// line's standing: for the journal page, which shows history and + /// says of a line that did not count that it did not. + pub history: Vec<(JournalLine, ledger_store::calls::Standing)>, + /// The seq of the journal's last line. + pub head_seq: u64, pub head: String, pub today: NaiveDate, pub loaded_at: chrono::DateTime, @@ -605,7 +618,14 @@ impl Books { ) -> Result { let ledger = snap.ledger().clone(); let attachments = snap.attachments(None).map_err(|e| e.to_string())?; - let journal = snap.journal().to_vec(); + let journal = snap.committed_journal().map_err(|e| e.to_string())?; + let history: Vec<_> = snap + .journal() + .iter() + .cloned() + .zip(snap.journal_standings().map_err(|e| e.to_string())?) + .collect(); + let head_seq = snap.journal_seq(); // The server's own rule, so the viewer flags exactly what the // server would refuse: the books' settings. let policy = ledger_config::codec::receipt_policy(ledger.settings()); @@ -676,7 +696,7 @@ impl Books { let statements = snap.statements(None).map_err(|e| e.to_string())?; let reconciliations = snap.reconciliations(None).map_err(|e| e.to_string())?; let extractions = snap.extractions().map_err(|e| e.to_string())?; - let fresh_from_seq = prev_seq.unwrap_or(journal.len() as u64); + let fresh_from_seq = prev_seq.unwrap_or(head_seq); let mut fresh = HashSet::new(); let closings = ledger.closing_entry_ids(); let mut entries = Vec::new(); @@ -817,6 +837,8 @@ impl Books { data_dir: snap.data_dir().to_path_buf(), attachments, journal, + history, + head_seq, head: snap.head_hash().to_string(), today, loaded_at: chrono::Utc::now(), @@ -864,7 +886,7 @@ impl Books { } pub fn seq(&self) -> u64 { - self.journal.len() as u64 + self.head_seq } pub fn entry(&self, id: EntryId) -> Option<&EntryInfo> { diff --git a/crates/ledger-gui/src/pages/journal.rs b/crates/ledger-gui/src/pages/journal.rs index 2bb8d345..a2ddbf0c 100644 --- a/crates/ledger-gui/src/pages/journal.rs +++ b/crates/ledger-gui/src/pages/journal.rs @@ -1270,6 +1270,24 @@ pub fn describe(b: &Books, line: &JournalLine) -> Option { } } +/// A journal line's event for the journal page: the sentence the books +/// give it when it counts; for a line of a call that did not count, its +/// plain description from the journal's own words and the note that it did +/// not count, never a sentence built from the books' present state (ids +/// are handed out again after a failed call, so "Posted #42" would name +/// whatever took 42 next), and no link. +pub fn event_for(b: &Books, line: &JournalLine, standing: ledger_store::calls::Standing) -> Event { + match standing.note() { + None => describe_any(b, line), + Some(note) => Event { + icon: icon::WARNING, + text: format!("{} ({note})", ledger_store::describe::describe(line)), + route: None, + also: None, + }, + } +} + /// Like [`describe`], but every event gets a sentence. pub fn describe_any(b: &Books, line: &JournalLine) -> Event { if let Some(e) = describe(b, line) { @@ -1342,7 +1360,7 @@ pub fn describe_any(b: &Books, line: &JournalLine) -> Event { pub fn show(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_>) { if let Some(seq) = selected - && let Some(line) = b.journal.get(seq.saturating_sub(1) as usize) + && let Some((line, standing)) = b.history.get(seq.saturating_sub(1) as usize) { super::split( ui, @@ -1350,7 +1368,7 @@ pub fn show(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_> 480.0, shell, |ui, shell| list(ui, b, selected, shell), - |ui, shell| detail(ui, b, line, shell), + |ui, shell| detail(ui, b, line, *standing, shell), ); } else { list(ui, b, None, shell); @@ -1365,7 +1383,7 @@ fn list(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_>) { "Journal", &format!( "Every change to the books, in order: {} events, each hash-chained to the one before. Nothing is ever edited or deleted; corrections are new events.", - b.journal.len() + b.history.len() ), ); let st = &mut shell.state.journal; @@ -1381,11 +1399,11 @@ fn list(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_>) { let q = st.query.to_lowercase(); let hide = st.hide_steps; let rows: Vec<(&JournalLine, Event)> = b - .journal + .history .iter() .rev() - .filter(|l| !(hide && describe(b, l).is_none())) - .map(|l| (l, describe_any(b, l))) + .filter(|(l, st)| !(hide && st.counts() && describe(b, l).is_none())) + .map(|(l, st)| (l, event_for(b, l, *st))) .filter(|(l, e)| { q.is_empty() || e.text.to_lowercase().contains(&q) || l.line_type.contains(&q) }) @@ -1461,9 +1479,15 @@ fn list(ui: &mut Ui, b: &Books, selected: Option, shell: &mut Shell<'_>) { }); } -fn detail(ui: &mut Ui, b: &Books, line: &JournalLine, shell: &mut Shell<'_>) { +fn detail( + ui: &mut Ui, + b: &Books, + line: &JournalLine, + standing: ledger_store::calls::Standing, + shell: &mut Shell<'_>, +) { let p = pal(ui.ctx()); - let ev = describe_any(b, line); + let ev = event_for(b, line, standing); egui::ScrollArea::vertical() .id_salt("event_detail") .show(ui, |ui| { @@ -1485,6 +1509,9 @@ fn detail(ui: &mut Ui, b: &Books, line: &JournalLine, shell: &mut Shell<'_>) { ui.add(egui::Label::new(RichText::new(v).font(theme::regular(12.5))).wrap()); }); }; + if let Some(note) = standing.note() { + fact(ui, "Counts", note); + } fact(ui, "Type", &line.line_type); fact(ui, "Recorded", &fmt::timestamp(&line.ts)); fact(ui, "Previous", &line.prev); diff --git a/crates/ledger-gui/tests/view_model.rs b/crates/ledger-gui/tests/view_model.rs index c72801d7..bda7f7c7 100644 --- a/crates/ledger-gui/tests/view_model.rs +++ b/crates/ledger-gui/tests/view_model.rs @@ -986,3 +986,117 @@ fn the_viewer_holds_a_numbered_invoice_as_the_store_does() { assert_eq!(shown.terms.as_ref().unwrap().describe(), "2/10 net 30"); assert_eq!(shown.lines[0].quantity, Some(Decimal::new(3, 0))); } + +/// A call that failed after writing lines, followed by a call that takes +/// the ids it handed out again (nothing it wrote counted): the viewer's +/// books, the package feed that attention reads, and the history all say +/// the dead lines are not facts, and nothing of the dead call is pinned on +/// what took its ids (WB-format-12). +#[test] +fn a_failed_calls_lines_are_not_facts_when_its_ids_are_used_again() { + use ledger_store::calls::{CallEnd, CallId, Standing}; + let (d, mut s) = store_at("failed-call"); + let today = NaiveDate::from_ymd_opt(2026, 5, 20).unwrap(); + let cash = s + .add_account("1000", "Checking", AccountType::Asset, None, false) + .unwrap(); + let cap = s + .add_account("3000", "Capital", AccountType::Equity, None, false) + .unwrap(); + let id = |key: &str, tool: &str| CallId { + token: "t".into(), + tool: tool.into(), + key: key.into(), + args: "a".repeat(64), + }; + let lines = |amount: i64| { + vec![DocumentLine { + description: "x".into(), + amount: Decimal::new(amount, 2), + class_id: None, + account: None, + quantity: None, + unit_price: None, + }] + }; + let before = s.journal_seq(); + // A failed books.create_bill: a vendor, a bill, an entry (id 1). + s.begin_call(id("key-dead-0001", "books.create_bill")) + .unwrap(); + let dead_vendor = s.add_vendor("Dead Vendor").unwrap(); + s.create_bill(dead_vendor, today, today + Days::new(30), lines(5_000)) + .unwrap(); + s.close_call(CallEnd::Failed("the call failed after its lines")) + .unwrap(); + let dead_end = s.journal_seq(); + assert!(dead_end > before + 3); + // A manual entry, which takes entry id 1 again, and a vendor, which + // takes party id 1 again. + let e = s.create_entry(today, "Opening deposit").unwrap(); + assert_eq!(e, 1, "the failed call's entry id is handed out again"); + let m = Money::new(Decimal::new(100_000, 2), Currency::USD); + s.add_line(e, cash, Side::Debit, m).unwrap(); + s.add_line(e, cap, Side::Credit, m).unwrap(); + s.post_entry(e).unwrap(); + let live_vendor = s.add_vendor("Real Vendor").unwrap(); + assert_eq!(live_vendor, dead_vendor); + drop(s); + let source = Source { + data_dir: d.join("books-data"), + today: Some(today), + }; + let b = data::load_once(&source).unwrap(); + // The entry is a manual one: not a "Bill", which is what the dead + // bill.created line (for entry 1) would have made of it. + let entry = b.entry(e).unwrap(); + assert_eq!(entry.origin, "Journal entry"); + assert!( + entry + .events + .iter() + .all(|&i| !(before + 1..=dead_end).contains(&b.journal[i].seq)), + "an entry's events include a dead line" + ); + // No fact the viewer derives holds a dead line: the committed journal + // has none of them, and none of the frame. + assert!( + b.journal + .iter() + .all(|l| !(before + 1..=dead_end).contains(&l.seq) && !l.line_type.starts_with("call.")) + ); + // The party that took the id again has none of the dead vendor's events. + let party = &b.parties[&live_vendor]; + assert!( + party + .events + .iter() + .all(|&i| !(before + 1..=dead_end).contains(&b.journal[i].seq)) + ); + // The package feed attention reads is the same committed journal. + let snap = ledger_store::Snapshot::load(&d.join("books-data")).unwrap(); + let fed = ledger_package::PackageBooks::journal(&snap).unwrap(); + assert_eq!(fed.len(), b.journal.len()); + assert!( + fed.iter() + .all(|l| !(before + 1..=dead_end).contains(&l.seq)) + ); + let store = Store::open(&d.join("books-data")).unwrap(); + let fed = ledger_package::PackageBooks::journal(&store).unwrap(); + assert_eq!(fed.len(), b.journal.len()); + // The viewer's seq is the journal's head, frame lines counted. + assert_eq!(b.seq(), b.history.len() as u64); + // History shows every line, and says of the dead ones in words that + // they did not count; the viewer never names a dead line by the live + // entry that took its id. + let dead: Vec<_> = b + .history + .iter() + .filter(|(_, st)| *st == Standing::Failed) + .collect(); + assert!(dead.len() >= 3); + for (line, st) in dead { + let ev = ledger_gui::pages::journal::event_for(&b, line, *st); + assert!(ev.text.contains("not counted"), "{}", ev.text); + assert!(ev.route.is_none()); + } +} diff --git a/crates/ledger-package/src/books.rs b/crates/ledger-package/src/books.rs index d35e7bf0..c3dcc5a9 100644 --- a/crates/ledger-package/src/books.rs +++ b/crates/ledger-package/src/books.rs @@ -9,7 +9,7 @@ //! INVARIANTS: //! 1. Every method only reads. //! 2. A Store and a Snapshot of the same journal answer every method -//! alike: the same ledger, settings, journal, journal seq, +//! alike: the same ledger, settings, committed journal, journal seq, //! attachments (withdrawn ones included), bytes, statements, and //! reconciliations, and the same entry links once the filing entry //! is added (a store lists it in `links_of`; a snapshot only lists @@ -39,8 +39,12 @@ pub trait PackageBooks { /// package reflects. fn journal_seq(&self) -> u64; - /// Every journal line, in order: what an entry's origin and its events - /// are read from. + /// The committed journal, in order: what an entry's origin and its + /// events are read from. Only the lines that are facts of the books + /// (ledger_store::calls::committed): the lines of a call that failed or + /// never finished are not here, because ids are handed out again after + /// a failed call and a reader that took them would pin dead lines on + /// whatever takes the id next (WB-format-12). fn journal(&self) -> Result, StoreError>; /// Every attachment (receipts and documents), withdrawn ones @@ -83,9 +87,10 @@ impl PackageBooks for Store { } fn journal(&self) -> Result, StoreError> { - ledger_store::journal::read_and_verify_journal( + let lines = ledger_store::journal::read_and_verify_journal( &Store::data_dir(self).join(ledger_store::JOURNAL_FILE), - ) + )?; + ledger_store::calls::committed(&lines) } fn all_attachments(&self) -> Result, StoreError> { @@ -134,7 +139,7 @@ impl PackageBooks for Snapshot { } fn journal(&self) -> Result, StoreError> { - Ok(Snapshot::journal(self).to_vec()) + Snapshot::committed_journal(self) } fn all_attachments(&self) -> Result, StoreError> { diff --git a/crates/ledger-store/src/calls.rs b/crates/ledger-store/src/calls.rs index e8882bc1..97c20115 100644 --- a/crates/ledger-store/src/calls.rs +++ b/crates/ledger-store/src/calls.rs @@ -1,21 +1,33 @@ //! Calls: every write a tool makes is one transaction that happens once //! (plan P15 2a, D-88, D-89). //! -//! A call that writes frames its journal lines with two line types, and -//! a call that wrote nothing is just a closing line: +//! A call that writes journal lines frames them with two line types; a +//! call that wrote none leaves nothing in the journal at all: //! //! * `call.begun { tool, token, key, args }`, written lazily, just before //! the call's first line; //! * `call.closed { tool, token, key, args, outcome, first_seq, last_seq, -//! answer | error }`, written when the call is over. `outcome` is `ok` -//! (the answer the caller was given is `answer`, kept as text so a -//! repeat returns it byte for byte), `failed` (the call got as far as -//! writing lines and then failed: `error` says how), or `unfinished` -//! (written by the next open of books whose last call never closed). +//! answer | answer_sha256 + answer_bytes | error }`, written when the +//! call is over. `outcome` is `ok` (the answer the caller was given is +//! `answer`, kept as text so a repeat returns it byte for byte; above +//! [`ANSWER_CAP`] bytes the closing line keeps `answer_sha256` and +//! `answer_bytes` instead, and a repeat is told in words that the call +//! was done), `failed` (the call got as far as writing lines and then +//! failed: `error` says how), or `unfinished` (written by the next open +//! of books whose last call never closed). +//! +//! `args` is a keyed digest of the call's arguments (HMAC-SHA256 under +//! the books' own call key, `keys/calls.key`, never journaled): the +//! arguments themselves, and any tax id in them, are not recoverable or +//! testable from the journal. //! //! The lines between a begin and its close count only if the close says //! `ok`: that is how a reader tells a complete call from an incomplete -//! one, and the one rule every replay uses ([`CallGate`]). The envelope +//! one, and the one rule every reader applies ([`CallGate`], [`standings`], +//! [`committed`]). Ids are handed out again after a failed call (nothing +//! it wrote counted), so a reader that takes the journal raw would pin the +//! dead lines of a failed call on whatever takes the id next: every reader +//! that derives a fact reads [`committed`]. The envelope //! `{seq, ts, type, payload, prev}` is untouched. //! //! ```text @@ -34,17 +46,28 @@ //! books declared the feature, and the owner's own acts: the format //! declaration, a repaired tail) apply as ever. //! 3. A close names the frame it ends: its `first_seq` is the begin -//! line's seq and its `last_seq` the line before it, or both are -//! absent when the call wrote no lines. A begin inside a frame, a -//! mismatched close, or an `unfinished` close with no frame is a -//! corrupt journal. +//! line's seq and its `last_seq` the line before it. A close with no +//! frame, a begin inside a frame, a mismatched close, or an +//! `unfinished` close with no frame is a corrupt journal. //! 4. The projection never holds a line of a call that did not commit: //! the call's SQLite changes live in one transaction that is released //! only after the `ok` closing line is on disk. -//! 5. The key table (token, key) -> answer is built from `ok` closing -//! lines alone, so a restart rebuilds it from the journal. +//! 5. The key table (token, key) -> call is built from `ok` closing +//! lines alone, so a restart rebuilds it from the journal. A call +//! that wrote no line has no closing line: its key and answer are +//! kept in memory for the life of the store only, in a table bounded +//! in count and bytes, and a repeat after a restart runs again (it +//! wrote nothing, so nothing is done twice). //! 6. Books that haven't declared `call_transactions` take no call: a //! begin is refused (FormatUpgradePending), journaling nothing. +//! 7. Every reader that derives a fact (an entry's origin, an asset's +//! trail, a party's events, an attention item, a preview of what +//! adopting would keep) reads [`committed`], never the raw lines; a +//! reader that shows history shows every line and says in words of +//! each line of a call that did not count that it did not ([`Standing`]). +//! 8. A closing line's answer is at most [`ANSWER_CAP`] bytes; above +//! that the line keeps the answer's SHA-256 and length, and a repeat +//! says in words that the call was done and writes nothing. //! SCENARIOS: //! 1. IF the process dies between a call's lines and its closing line: //! SHOULD, at the next open, apply none of them, write an @@ -53,11 +76,16 @@ //! close, roll its SQLite changes back, and replay the journal //! without its lines. //! 3. IF a call fails before writing a line: SHOULD journal nothing. +//! 4. IF a call's closing line is on disk but its SQLite changes can't +//! be committed: SHOULD say so (the call counts), heal from the +//! journal, and refuse more writes until it has. //! ``` -use std::collections::HashMap; +use std::collections::{HashMap, VecDeque}; +use std::path::Path; use serde_json::{Value, json}; +use sha2::{Digest, Sha256}; use super::{Store, apply_line_to_sqlite, get_str, get_u64}; use crate::error::StoreError; @@ -74,6 +102,21 @@ pub const MIN_KEY_LEN: usize = 8; /// A request key is at most this many characters. pub const MAX_KEY_LEN: usize = 128; +/// The longest answer (its JSON text, in bytes) a closing line keeps +/// whole: 4 KiB. Above it the line keeps the answer's SHA-256 and length +/// (INVARIANT 8). +pub const ANSWER_CAP: usize = 4096; + +/// The most calls that wrote no line whose key and answer are kept in +/// memory (INVARIANT 5); the oldest go first. +pub const SESSION_KEYS_MAX: usize = 512; +/// The most bytes of answers kept for them: 2 MiB. +pub const SESSION_BYTES_MAX: usize = 2 * 1024 * 1024; + +/// The file, in the books' `keys/` folder, holding the secret the +/// journal's argument digests are keyed with. +pub const CALLS_KEY_FILE: &str = "calls.key"; + /// Who made a call, what it is, and what it asked for. #[derive(Clone, Debug, PartialEq, Eq)] pub struct CallId { @@ -119,29 +162,99 @@ pub struct Closed { pub first_seq: Option, /// The seq of the call's last line, when it wrote lines. pub last_seq: Option, - /// The answer it gave (an `ok` call): JSON text. + /// The answer it gave (an `ok` call), when short enough to keep: + /// JSON text. pub answer: Option, + /// The SHA-256 of the answer, hex, when it was too long to keep. + pub answer_sha256: Option, + /// The length of that answer in bytes. + pub answer_bytes: Option, /// How it failed (a `failed` call). pub error: Option, } +/// What a repeat of a call that committed is answered with. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Replay { + /// The answer it gave, as JSON text, byte for byte. + Answer(String), + /// Its answer was too long to keep: what the closing line says of it. + Summary { + /// The seq of its begin line. + first_seq: u64, + /// The seq of its last line before the closing line. + last_seq: u64, + /// The seq of the closing line. + closed_seq: u64, + /// The SHA-256 of the answer it gave, hex. + answer_sha256: String, + /// The answer's length in bytes. + answer_bytes: u64, + }, +} + /// What the books kept of a call that committed. #[derive(Clone, Debug, PartialEq, Eq)] pub struct Recorded { /// The tool. pub tool: String, - /// The digest of its arguments, without the key. + /// The keyed digest of its arguments. pub args: String, - /// The answer it gave, as JSON text. - pub answer: String, - /// The seq of its closing line. - pub seq: u64, + /// What a repeat is answered with. + pub replay: Replay, +} + +/// What the table keeps of a call with lines: no answer (a repeat reads +/// it from the closing line), so the table's size is one small entry per +/// committed call, whatever the answers' sizes. +#[derive(Clone, Debug)] +struct Entry { + tool: String, + args: String, + /// The seq of the closing line. + seq: u64, +} + +/// The calls that wrote no line, kept for the life of the store: bounded +/// by count and by bytes of answers, oldest first out (INVARIANT 5). +#[derive(Clone, Debug, Default)] +struct Session { + by: HashMap<(String, String), (String, String, String)>, + order: VecDeque<(String, String)>, + bytes: usize, +} + +impl Session { + fn note(&mut self, id: &CallId, answer: &str) { + if answer.len() > ANSWER_CAP { + // Not kept: a repeat of a call that wrote nothing just runs + // again. + return; + } + let k = (id.token.clone(), id.key.clone()); + if self.by.contains_key(&k) { + return; + } + self.bytes += answer.len(); + self.order.push_back(k.clone()); + self.by + .insert(k, (id.tool.clone(), id.args.clone(), answer.to_string())); + while self.order.len() > SESSION_KEYS_MAX || self.bytes > SESSION_BYTES_MAX { + let Some(old) = self.order.pop_front() else { + break; + }; + if let Some((_, _, a)) = self.by.remove(&old) { + self.bytes -= a.len(); + } + } + } } /// The keys of every call that committed, by (token, key). #[derive(Clone, Debug, Default)] pub struct Keys { - by: HashMap<(String, String), Recorded>, + by: HashMap<(String, String), Entry>, + session: Session, } impl Keys { @@ -159,21 +272,24 @@ impl Keys { } fn note(&mut self, closed: &Closed, seq: u64) { - let Some(answer) = closed.answer.clone() else { - return; - }; self.by .entry((closed.id.token.clone(), closed.id.key.clone())) - .or_insert(Recorded { + .or_insert(Entry { tool: closed.id.tool.clone(), args: closed.id.args.clone(), - answer, seq, }); } - fn get(&self, token: &str, key: &str) -> Option<&Recorded> { - self.by.get(&(token.to_string(), key.to_string())) + /// How many calls with lines the table knows (a test's question). + pub fn journaled(&self) -> usize { + self.by.len() + } + + /// How many calls that wrote nothing it holds, and the bytes of their + /// answers. + pub fn session_size(&self) -> (usize, usize) { + (self.session.order.len(), self.session.bytes) } } @@ -229,15 +345,34 @@ pub fn closed_of(line: &JournalLine) -> Result { .ok_or_else(|| corrupt(line, k)), }; let answer = text_of("answer")?; - if outcome == CallOutcome::Ok && answer.is_none() { - return Err(corrupt(line, "answer")); + let answer_sha256 = text_of("answer_sha256")?; + let answer_bytes = seq_of("answer_bytes")?; + if outcome == CallOutcome::Ok { + let kept_whole = answer.is_some() && answer_sha256.is_none() && answer_bytes.is_none(); + let kept_hash = answer.is_none() + && answer_bytes.is_some_and(|n| n > ANSWER_CAP as u64) + && answer_sha256 + .as_deref() + .is_some_and(|h| h.len() == 64 && h.bytes().all(|b| b.is_ascii_hexdigit())); + if !(kept_whole || kept_hash) { + return Err(corrupt(line, "answer")); + } + if answer.as_ref().is_some_and(|a| a.len() > ANSWER_CAP) { + return Err(corrupt(line, "answer (longer than the cap)")); + } + } + let (first_seq, last_seq) = (seq_of("first_seq")?, seq_of("last_seq")?); + if first_seq.is_none() || last_seq.is_none() { + return Err(corrupt(line, "first_seq and last_seq")); } Ok(Closed { id, outcome, - first_seq: seq_of("first_seq")?, - last_seq: seq_of("last_seq")?, + first_seq, + last_seq, answer, + answer_sha256, + answer_bytes, error: text_of("error")?, }) } @@ -246,21 +381,31 @@ fn begun_payload(id: &CallId) -> Value { json!({ "tool": id.tool, "token": id.token, "key": id.key, "args": id.args }) } +/// What a closing line says of the answer: the answer itself, or, above +/// [`ANSWER_CAP`], its hash and length. +enum Kept<'a> { + Answer(&'a str), + Nothing, +} + fn closed_payload( id: &CallId, outcome: CallOutcome, - range: Option<(u64, u64)>, - answer: Option<&str>, + range: (u64, u64), + answer: Kept<'_>, error: Option<&str>, ) -> Value { let mut p = begun_payload(id); p["outcome"] = json!(outcome.as_str()); - if let Some((first, last)) = range { - p["first_seq"] = json!(first); - p["last_seq"] = json!(last); - } - if let Some(a) = answer { - p["answer"] = json!(a); + p["first_seq"] = json!(range.0); + p["last_seq"] = json!(range.1); + if let Kept::Answer(a) = answer { + if a.len() <= ANSWER_CAP { + p["answer"] = json!(a); + } else { + p["answer_sha256"] = json!(hex::encode(Sha256::digest(a.as_bytes()))); + p["answer_bytes"] = json!(a.len()); + } } if let Some(e) = error { p["error"] = json!(e); @@ -320,13 +465,7 @@ impl CallGate { CLOSED => { let closed = closed_of(line)?; let Some(call) = self.pending.take() else { - if closed.first_seq.is_some() - || closed.last_seq.is_some() - || closed.outcome == CallOutcome::Unfinished - { - return Err(corrupt(line, "closes a call that never began")); - } - return Ok(vec![index]); + return Err(corrupt(line, "closes a call that never began")); }; if closed.id != call.id || closed.first_seq != Some(call.begun_seq) @@ -388,6 +527,153 @@ pub(crate) fn gate_all(lines: &[JournalLine]) -> Result<(Vec, CallGate), Ok((released, gate)) } +/// Whether a journal line counts, and if not, why (INVARIANT 7). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Standing { + /// It counts: outside any call, or inside one that closed `ok`. + Counts, + /// A `call.begun` or `call.closed` line: the frame, which says what + /// became of the lines between and is no fact of the books itself. + Frame, + /// Inside a call that closed `failed`: it did not count. + Failed, + /// Inside a call that closed `unfinished`: it did not count. + Unfinished, + /// Inside a call that has not closed yet: it does not count yet. + Pending, +} + +impl Standing { + /// Whether the line is a fact of the books. + pub fn counts(self) -> bool { + self == Self::Counts + } + + /// In words, why the line does not count; None for a line that + /// counts and for a frame line. + pub fn note(self) -> Option<&'static str> { + match self { + Self::Counts | Self::Frame => None, + Self::Failed => Some("not counted: the call that wrote it failed"), + Self::Unfinished => Some("not counted: the call that wrote it never finished"), + Self::Pending => Some("not counted yet: the call that wrote it is still running"), + } + } +} + +/// The standing of every line of `lines`, in order: the one question +/// every reader asks of the journal (INVARIANTS 1, 7). A journal that is +/// not a sound sequence of frames is corrupt. +pub fn standings(lines: &[JournalLine]) -> Result, StoreError> { + let mut gate = CallGate::default(); + let mut out = Vec::with_capacity(lines.len()); + let mut frame: Option = None; + for (i, line) in lines.iter().enumerate() { + gate.push(i, line)?; + match line.line_type.as_str() { + BEGUN => { + frame = Some(i); + out.push(Standing::Frame); + } + CLOSED => { + out.push(Standing::Frame); + if let Some(begun) = frame.take() { + let settled = match closed_of(line)?.outcome { + CallOutcome::Ok => Standing::Counts, + CallOutcome::Failed => Standing::Failed, + CallOutcome::Unfinished => Standing::Unfinished, + }; + for s in &mut out[begun + 1..i] { + *s = settled; + } + } + } + _ => out.push(if frame.is_some() { + Standing::Pending + } else { + Standing::Counts + }), + } + } + Ok(out) +} + +/// The committed journal: the lines that are facts of the books, in +/// order: those outside any call and those of calls that closed `ok`, +/// the frame lines themselves left out (INVARIANT 7). What every reader +/// that derives a fact from the journal's lines reads. +pub fn committed(lines: &[JournalLine]) -> Result, StoreError> { + let standing = standings(lines)?; + Ok(lines + .iter() + .zip(standing) + .filter(|(_, s)| s.counts()) + .map(|(l, _)| l.clone()) + .collect()) +} + +/// HMAC-SHA256 (RFC 2104) of `msg` under `key`, hex. +pub(crate) fn hmac_sha256_hex(key: &[u8], msg: &[u8]) -> String { + const BLOCK: usize = 64; + let mut k = [0u8; BLOCK]; + if key.len() > BLOCK { + k[..32].copy_from_slice(&Sha256::digest(key)); + } else { + k[..key.len()].copy_from_slice(key); + } + let mut inner = Sha256::new(); + inner.update(k.map(|b| b ^ 0x36)); + inner.update(msg); + let mut outer = Sha256::new(); + outer.update(k.map(|b| b ^ 0x5c)); + outer.update(inner.finalize()); + hex::encode(outer.finalize()) +} + +/// The secret a book's call arguments are keyed with: 32 random bytes in +/// `keys/calls.key` of its folder (mode 0600, the folder 0700), made on +/// first need and never written to the journal, a log or an answer. The +/// error names no path. +fn calls_key(data_dir: &Path) -> Result, StoreError> { + let unsure = |what: &str| { + StoreError::CallRefused(format!( + "the books' call key can't be {what}, so the call was not run and nothing was changed" + )) + }; + let file = data_dir.join(crate::root::KEYS_DIR).join(CALLS_KEY_FILE); + match std::fs::read_to_string(&file) { + Ok(text) => hex::decode(text.trim()) + .ok() + .filter(|b| b.len() == 32) + .ok_or_else(|| unsure("read: its file isn't a key")), + Err(e) if e.kind() == std::io::ErrorKind::NotFound => { + crate::root::private_book_folder(data_dir, crate::root::KEYS_DIR) + .map_err(|_| unsure("kept: the keys folder isn't usable"))?; + let mut key = [0u8; 32]; + getrandom::getrandom(&mut key).map_err(|_| unsure("made: no randomness"))?; + match crate::root::write_new_private_file(&file, hex::encode(key).as_bytes()) { + Ok(()) => Ok(key.to_vec()), + // Another process made it first: use theirs. + Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => calls_key(data_dir), + Err(_) => Err(unsure("kept: it can't be written")), + } + } + Err(_) => Err(unsure("read")), + } +} + +/// The keyed digest of a call's arguments: HMAC-SHA256 over their +/// canonical JSON, unmasked, under the books' call key. Two requests that +/// differ only in a tax id differ here; nothing in it lets anyone recover +/// or test a guess of one without the key, which is never journaled. +pub fn args_mac(data_dir: &Path, args: &Value) -> Result { + let key = calls_key(data_dir)?; + Ok(hmac_sha256_hex( + &key, + crate::journal::canonical_json(args).as_bytes(), + )) +} + /// The books' id: the one `store.created` carries (books made since /// `call_transactions`), else the one the format upgrade added to its /// `journal.format_set`. None for books that have had neither yet. @@ -443,10 +729,54 @@ impl Store { self.ensure_feature(CALL_TRANSACTIONS) } + /// The keyed digest of a call's arguments ([`args_mac`]), under this + /// book's call key. + pub fn args_mac(&self, args: &Value) -> Result { + args_mac(&self.data_dir, args) + } + /// What the books kept of the call that ran under this token and key, - /// if one committed. - pub fn recorded_call(&self, token: &str, key: &str) -> Option<&Recorded> { - self.keys.get(token, key) + /// if one committed: from the session's table for a call that wrote + /// nothing, else from the journal's closing line. + pub fn recorded_call(&self, token: &str, key: &str) -> Result, StoreError> { + let k = (token.to_string(), key.to_string()); + if let Some((tool, args, answer)) = self.keys.session.by.get(&k) { + return Ok(Some(Recorded { + tool: tool.clone(), + args: args.clone(), + replay: Replay::Answer(answer.clone()), + })); + } + let Some(entry) = self.keys.by.get(&k) else { + return Ok(None); + }; + // Read from the closing line: the table holds no answers. + let lines = crate::journal::read_and_verify_journal(self.journal.path())?; + let line = lines.iter().find(|l| l.seq == entry.seq).ok_or_else(|| { + StoreError::JournalCorrupt(format!("seq {}: no closing line", entry.seq)) + })?; + let closed = closed_of(line)?; + let replay = match closed.answer { + Some(answer) => Replay::Answer(answer), + None => Replay::Summary { + first_seq: closed.first_seq.unwrap_or_default(), + last_seq: closed.last_seq.unwrap_or_default(), + closed_seq: line.seq, + answer_sha256: closed.answer_sha256.unwrap_or_default(), + answer_bytes: closed.answer_bytes.unwrap_or_default(), + }, + }; + Ok(Some(Recorded { + tool: entry.tool.clone(), + args: entry.args.clone(), + replay, + })) + } + + /// The table's sizes: calls with lines, and the session's calls that + /// wrote none with the bytes of their answers. + pub fn call_table(&self) -> (usize, (usize, usize)) { + (self.keys.journaled(), self.keys.session_size()) } /// Whether a call is open. @@ -454,6 +784,12 @@ impl Store { self.call.is_some() } + /// Whether the open call has written a line (its begin line is on + /// disk). + pub fn call_has_lines(&self) -> bool { + self.call.as_ref().is_some_and(|c| c.begun.is_some()) + } + /// Open a call: from here every line this store journals belongs to /// it, until [`Self::close_call`]. Journals nothing yet (the begin /// line comes with the first line); the projection's changes are held @@ -505,46 +841,78 @@ impl Store { Ok(()) } - /// Close the open call. `Done`: journal its closing line with the - /// answer, and release the projection's transaction: the call - /// committed. `Failed`: if the call wrote lines, journal a `failed` - /// closing line, roll the projection back and rebuild the live ledger - /// without those lines; if it wrote none, journal nothing. + /// Close the open call. + /// + /// `Done`, with lines written: journal its closing line with the + /// answer (or, above [`ANSWER_CAP`], the answer's hash and length), + /// and release the projection's transaction: the call committed. With + /// none written: journal nothing, release the transaction, and keep + /// the key and answer in memory (INVARIANT 5). + /// + /// `Failed`: if the call wrote lines, journal a `failed` closing + /// line, roll the projection back and rebuild the live ledger without + /// those lines; if it wrote none, journal nothing. /// /// If the closing line cannot be written, the call has not committed /// (it will close `unfinished` at the next open), the store refuses - /// every further write, and the error is returned: the caller stops - /// taking requests. + /// every further write, and the error is returned. If it is on disk + /// but the projection can't be brought up to it, the call *has* + /// committed: the store heals from the journal where it can, and + /// where it can't refuses every further write and returns + /// [`StoreError::CallCommitted`] (SCENARIO 4). pub fn close_call(&mut self, end: CallEnd<'_>) -> Result<(), StoreError> { let call = self .call .take() .ok_or_else(|| StoreError::CallRefused("no call is open".into()))?; let range = call.begun.map(|first| (first, self.journal.head().0)); - match end { - CallEnd::Done(answer) => { - let payload = closed_payload(&call.id, CallOutcome::Ok, range, Some(answer), None); + match (end, range) { + (CallEnd::Done(answer), None) => { + self.conn.execute_batch("RELEASE call_tx")?; + self.keys.session.note(&call.id, answer); + Ok(()) + } + (CallEnd::Done(answer), Some(range)) => { + let payload = + closed_payload(&call.id, CallOutcome::Ok, range, Kept::Answer(answer), None); let line = self .journal .append(CLOSED, payload) .map_err(|e| self.dangle(e))?; - // The projection commits with the line: released only - // once the closing line is on disk (INVARIANT 4). - apply_line_to_sqlite(&self.conn, &line) - .and_then(|()| Ok(self.conn.execute_batch("RELEASE call_tx")?)) - .map_err(|e| self.dangle(e))?; + // The closing line is on disk: the call committed, whatever + // becomes of the projection (INVARIANT 4). let closed = closed_of(&line)?; self.keys.note(&closed, line.seq); + let applied = apply_line_to_sqlite(&self.conn, &line) + .and_then(|()| Ok(self.conn.execute_batch("RELEASE call_tx")?)); + if let Err(e) = applied { + // Roll back what the transaction held, then bring the + // projection up from the journal, as an open would. + let _ = self + .conn + .execute_batch("ROLLBACK TO call_tx; RELEASE call_tx"); + if self.reload().is_err() { + self.dangling = true; + return Err(StoreError::CallCommitted(format!( + "the call's closing line is saved, so it counts, but the books' working copy could not be brought up to it ({e}); it is rebuilt from the journal when the books are opened again" + ))); + } + } Ok(()) } - CallEnd::Failed(error) => { - if range.is_none() { - self.conn - .execute_batch("ROLLBACK TO call_tx; RELEASE call_tx")?; - return Ok(()); - } - let payload = - closed_payload(&call.id, CallOutcome::Failed, range, None, Some(error)); + (CallEnd::Failed(_), None) => { + self.conn + .execute_batch("ROLLBACK TO call_tx; RELEASE call_tx")?; + Ok(()) + } + (CallEnd::Failed(error), Some(range)) => { + let payload = closed_payload( + &call.id, + CallOutcome::Failed, + range, + Kept::Nothing, + Some(error), + ); self.journal .append(CLOSED, payload) .map_err(|e| self.dangle(e))?; @@ -574,7 +942,8 @@ impl Store { /// would build: the journal read through the gate, the ledger replayed /// from it, and the projection (rolled back to before the call) caught /// up with the lines that count. After a call failed with lines - /// written. + /// written, or when a committed call's projection could not be + /// released. fn reload(&mut self) -> Result<(), StoreError> { let lines = crate::journal::read_and_verify_journal(self.journal.path())?; let (released, _) = gate_all(&lines)?; @@ -593,8 +962,8 @@ impl Store { let payload = closed_payload( &u.id, CallOutcome::Unfinished, - Some((u.first_seq, u.last_seq)), - None, + (u.first_seq, u.last_seq), + Kept::Nothing, Some( "the call never finished: the books were closed or the program stopped before its closing line was written", ), @@ -604,3 +973,64 @@ impl Store { Ok(()) } } + +#[cfg(test)] +mod tests { + use super::*; + + /// RFC 4231, test cases 1 and 2 (and 6, a key longer than the block). + #[test] + fn hmac_sha256_matches_rfc_4231() { + assert_eq!( + hmac_sha256_hex(&[0x0b; 20], b"Hi There"), + "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7" + ); + assert_eq!( + hmac_sha256_hex(b"Jefe", b"what do ya want for nothing?"), + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843" + ); + assert_eq!( + hmac_sha256_hex( + &[0xaa; 131], + b"Test Using Larger Than Block-Size Key - Hash Key First" + ), + "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54" + ); + } + + /// Two requests that differ only in a tax id differ in their digests; + /// the digest holds neither, and is the same for the same request. + #[test] + fn args_mac_tells_tax_ids_apart_and_holds_none() { + let tmp = tempfile::tempdir().unwrap(); + let a = json!({"party": 1, "tin": "111-22-3333"}); + let b = json!({"party": 1, "tin": "111-22-3334"}); + let (ma, mb) = ( + args_mac(tmp.path(), &a).unwrap(), + args_mac(tmp.path(), &b).unwrap(), + ); + assert_ne!(ma, mb); + assert_eq!(ma, args_mac(tmp.path(), &a).unwrap()); + // Not the plain hash of the arguments: a guess can't be tested + // without the books' key. + assert_ne!( + ma, + hex::encode(Sha256::digest(journal_canonical(&a).as_bytes())) + ); + assert_eq!(ma.len(), 64); + // Another book has another key. + let other = tempfile::tempdir().unwrap(); + assert_ne!(ma, args_mac(other.path(), &a).unwrap()); + // The key is a file of its own, not the vault's. + assert!( + tmp.path() + .join(crate::root::KEYS_DIR) + .join(CALLS_KEY_FILE) + .is_file() + ); + } + + fn journal_canonical(v: &Value) -> String { + crate::journal::canonical_json(v) + } +} diff --git a/crates/ledger-store/src/describe.rs b/crates/ledger-store/src/describe.rs index 9f538c99..175366d9 100644 --- a/crates/ledger-store/src/describe.rs +++ b/crates/ledger-store/src/describe.rs @@ -43,6 +43,9 @@ pub struct Described { pub subjects: Vec, /// The entry it belongs to, if it is about one. pub entry_id: Option, + /// Whether the line counts (calls.rs): a line of a call that failed or + /// never finished is listed, and its summary says it did not count. + pub standing: crate::calls::Standing, } /// Which lines to list (INVARIANT 3). @@ -245,12 +248,29 @@ pub fn describe_line(line: &JournalLine) -> Described { summary: describe(line), subjects, entry_id, + standing: crate::calls::Standing::Counts, } } /// The lines `filter` asks for, described, in journal order (INVARIANT 3), -/// and whether more match after the last one returned. +/// and whether more match after the last one returned. Every line counts +/// (use [`history_standing`] where some may not). pub fn history(lines: &[JournalLine], filter: &HistoryFilter) -> (Vec, bool) { + history_standing( + lines, + &vec![crate::calls::Standing::Counts; lines.len()], + filter, + ) +} + +/// [`history`] with each line's standing (calls.rs INVARIANT 7): a line +/// of a call that failed, never finished or is still running is listed, +/// as history is, and its summary says in words that it does not count. +pub fn history_standing( + lines: &[JournalLine], + standing: &[crate::calls::Standing], + filter: &HistoryFilter, +) -> (Vec, bool) { let wanted = |l: &JournalLine| { l.seq > filter.after_seq && (filter.types.is_empty() @@ -268,12 +288,17 @@ pub fn history(lines: &[JournalLine], filter: &HistoryFilter) -> (Vec }; let mut out = Vec::new(); let mut more = false; - for l in lines.iter().filter(|l| wanted(l)) { + for (l, st) in lines.iter().zip(standing).filter(|(l, _)| wanted(l)) { if out.len() == filter.limit { more = true; break; } - out.push(describe_line(l)); + let mut d = describe_line(l); + d.standing = *st; + if let Some(note) = st.note() { + d.summary = format!("{} ({note})", d.summary); + } + out.push(d); } (out, more) } @@ -299,7 +324,8 @@ impl crate::Store { let (lines, _format) = crate::journal::read_journal_and_format( &self.data_dir().join(crate::store::JOURNAL_FILE), )?; - let (described, more) = history(&lines, filter); + let standing = crate::calls::standings(&lines)?; + let (described, more) = history_standing(&lines, &standing, filter); let tail_repairs = self .tail_repairs()? .into_iter() diff --git a/crates/ledger-store/src/error.rs b/crates/ledger-store/src/error.rs index b99ecc3f..a7f526b4 100644 --- a/crates/ledger-store/src/error.rs +++ b/crates/ledger-store/src/error.rs @@ -111,6 +111,12 @@ pub enum StoreError { #[error("{0}")] CallRefused(String), + /// A call's closing line is on disk, so the call committed and counts, + /// but the store could not bring its working copy up to it: the store + /// takes nothing more until the books are opened again, which does. + #[error("{0}")] + CallCommitted(String), + /// Replay produced different ids than the journal recorded. #[error("replay mismatch: {0}")] ReplayMismatch(String), diff --git a/crates/ledger-store/src/root.rs b/crates/ledger-store/src/root.rs index ca4347e8..19f81ef1 100644 --- a/crates/ledger-store/src/root.rs +++ b/crates/ledger-store/src/root.rs @@ -987,7 +987,11 @@ impl Root { head.0 ))); } - let keeps_settings = lines.iter().any(|l| l.line_type == "settings.set"); + // Facts of the books only: a failed call's settings line never counted + // (calls.rs INVARIANT 7). + let keeps_settings = crate::calls::committed(&lines)? + .iter() + .any(|l| l.line_type == "settings.set"); if !keeps_settings && options.settings.is_none() { return Err(RootError::Adopt( "these books keep no settings of their own yet: give their settings file \ @@ -1497,7 +1501,9 @@ impl Root { Ok(SourcePreview { head: head_of(&lines), currency: crate::store::journal_currency(&lines)?, - keeps_settings: lines.iter().any(|l| l.line_type == "settings.set"), + keeps_settings: crate::calls::committed(&lines)? + .iter() + .any(|l| l.line_type == "settings.set"), }) })() .map_err(|e| self.hide(e)) @@ -2290,6 +2296,19 @@ fn write_private_file(path: &Path, bytes: &[u8]) -> Result<(), RootError> { Ok(()) } +/// Write a new file, mode 0600 set explicitly, synced, as `io::Result` +/// (the call key, calls.rs): an existing file is `AlreadyExists`. +pub(crate) fn write_new_private_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> { + use std::io::Write; + let mut file = std::fs::OpenOptions::new() + .write(true) + .create_new(true) + .open(path)?; + set_mode(path, 0o600)?; + file.write_all(bytes)?; + file.sync_all() +} + /// Make a folder's entries durable (Unix; NTFS journals its own). fn sync_dir(path: &Path) -> Result<(), RootError> { #[cfg(unix)] diff --git a/crates/ledger-store/src/snapshot.rs b/crates/ledger-store/src/snapshot.rs index f150656b..c311b851 100644 --- a/crates/ledger-store/src/snapshot.rs +++ b/crates/ledger-store/src/snapshot.rs @@ -257,11 +257,28 @@ impl Snapshot { } /// Every journal line read so far, in order: the complete history, - /// with timestamps and hashes. + /// with timestamps and hashes, the lines of calls that failed or never + /// finished among them. For showing history only: a reader that + /// derives a fact reads [`Snapshot::committed_journal`] (calls.rs + /// INVARIANT 7), and labels each line here with + /// [`Snapshot::journal_standings`]. pub fn journal(&self) -> &[JournalLine] { &self.lines } + /// The standing of each line of [`Snapshot::journal`], in the same + /// order (calls.rs [`crate::calls::standings`]). + pub fn journal_standings(&self) -> Result, StoreError> { + crate::calls::standings(&self.lines) + } + + /// The committed journal: the lines that are facts of the books, the + /// frame lines left out ([`crate::calls::committed`]). What every + /// reader that derives facts from the journal reads. + pub fn committed_journal(&self) -> Result, StoreError> { + crate::calls::committed(&self.lines) + } + /// Sequence number of the last journal line read. pub fn journal_seq(&self) -> u64 { self.lines.len() as u64 diff --git a/crates/ledger-store/tests/calls.rs b/crates/ledger-store/tests/calls.rs index 54e46081..a56fef3c 100644 --- a/crates/ledger-store/tests/calls.rs +++ b/crates/ledger-store/tests/calls.rs @@ -12,7 +12,10 @@ use chrono::NaiveDate; use ledger_core::{AccountType, Currency, Ledger, Money, Side}; -use ledger_store::calls::{CallEnd, CallId, CallOutcome, begun_of, closed_of}; +use ledger_store::calls::{ + ANSWER_CAP, CallEnd, CallId, CallOutcome, Recorded, Replay, SESSION_KEYS_MAX, Standing, + begun_of, closed_of, +}; use ledger_store::{JOURNAL_FILE, JournalFormat, Snapshot, Store, StoreError}; use rust_decimal::Decimal; use serde_json::Value; @@ -35,6 +38,18 @@ fn id(key: &str) -> CallId { } } +/// What the store kept of a call, if anything. +fn kept(s: &Store, token: &str, key: &str) -> Option { + s.recorded_call(token, key).unwrap() +} + +fn answer_of(r: &Recorded) -> &str { + match &r.replay { + Replay::Answer(a) => a, + other => panic!("kept no whole answer: {other:?}"), + } +} + fn lines_of(dir: &Path) -> Vec { ledger_store::journal::read_and_verify_journal(&dir.join(JOURNAL_FILE)).unwrap() } @@ -85,39 +100,188 @@ fn a_call_is_framed_and_its_answer_kept_by_key() { assert_eq!(closed.first_seq, Some(lines[before].seq)); assert_eq!(closed.last_seq, Some(lines.last().unwrap().seq - 1)); assert_eq!(closed.answer.as_deref(), Some(r#"{"entry_id":1}"#)); - let kept = s.recorded_call("token-1", "key-aaaa-1").unwrap(); - assert_eq!(kept.answer, r#"{"entry_id":1}"#); - assert_eq!(kept.args, "a".repeat(64)); + let was = kept(&s, "token-1", "key-aaaa-1").unwrap(); + assert_eq!(answer_of(&was), r#"{"entry_id":1}"#); + assert_eq!(was.args, "a".repeat(64)); // Scoped to the token: another token has not used this key. - assert!(s.recorded_call("token-2", "key-aaaa-1").is_none()); + assert!(kept(&s, "token-2", "key-aaaa-1").is_none()); s.verify().unwrap(); // A restart rebuilds the table from the journal alone. drop(s); let s = Store::open(tmp.path()).unwrap(); assert_eq!( - s.recorded_call("token-1", "key-aaaa-1").unwrap().answer, + answer_of(&kept(&s, "token-1", "key-aaaa-1").unwrap()), r#"{"entry_id":1}"# ); s.verify().unwrap(); } #[test] -fn a_call_that_wrote_nothing_is_only_a_closing_line() { +fn a_call_that_wrote_nothing_leaves_no_line_and_is_remembered_for_the_session() { let tmp = tempfile::tempdir().unwrap(); let mut s = books(tmp.path()); let before = lines_of(tmp.path()).len(); s.begin_call(id("key-aaaa-2")).unwrap(); s.close_call(CallEnd::Done(r#"{"ok":true}"#)).unwrap(); - let lines = lines_of(tmp.path()); - assert_eq!(lines.len(), before + 1); - let closed = closed_of(&lines[before]).unwrap(); - assert_eq!((closed.first_seq, closed.last_seq), (None, None)); - assert!(s.recorded_call("token-1", "key-aaaa-2").is_some()); - // A failed call that wrote nothing leaves no line at all. + // No line at all: a call that wrote nothing has nothing to frame. + assert_eq!(lines_of(tmp.path()).len(), before); + // But a repeat within the session is answered as the first was. + assert_eq!( + answer_of(&kept(&s, "token-1", "key-aaaa-2").unwrap()), + r#"{"ok":true}"# + ); + // A failed call that wrote nothing leaves no line either, and frees its key. s.begin_call(id("key-aaaa-3")).unwrap(); s.close_call(CallEnd::Failed("refused")).unwrap(); - assert_eq!(lines_of(tmp.path()).len(), before + 1); - assert!(s.recorded_call("token-1", "key-aaaa-3").is_none()); + assert_eq!(lines_of(tmp.path()).len(), before); + assert!(kept(&s, "token-1", "key-aaaa-3").is_none()); + // After a restart the key is forgotten: the repeat runs again, which is + // harmless because the first wrote nothing. + drop(s); + let s = Store::open(tmp.path()).unwrap(); + assert!(kept(&s, "token-1", "key-aaaa-2").is_none()); + assert_eq!(lines_of(tmp.path()).len(), before); +} + +#[test] +fn the_sessions_key_table_is_bounded_in_count_and_in_bytes() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + for n in 0..SESSION_KEYS_MAX + 20 { + s.begin_call(id(&format!("key-bound-{n:05}"))).unwrap(); + s.close_call(CallEnd::Done(r#"{"ok":true}"#)).unwrap(); + } + let (_, (held, bytes)) = s.call_table(); + assert_eq!(held, SESSION_KEYS_MAX); + assert!(bytes <= SESSION_KEYS_MAX * 16); + // The oldest went first. + assert!(kept(&s, "token-1", "key-bound-00000").is_none()); + assert!( + kept( + &s, + "token-1", + &format!("key-bound-{:05}", SESSION_KEYS_MAX + 19) + ) + .is_some() + ); + // An answer above the cap is not kept for a call that wrote nothing. + s.begin_call(id("key-big-0001")).unwrap(); + s.close_call(CallEnd::Done(&"x".repeat(ANSWER_CAP + 1))) + .unwrap(); + assert!(kept(&s, "token-1", "key-big-0001").is_none()); +} + +#[test] +fn a_long_answer_is_kept_as_its_hash_and_a_repeat_is_told_in_words_what_was_done() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + let long = format!(r#"{{"text":"{}"}}"#, "y".repeat(ANSWER_CAP)); + s.begin_call(id("key-long-0001")).unwrap(); + draft(&mut s, "Big answer"); + s.close_call(CallEnd::Done(&long)).unwrap(); + let lines = lines_of(tmp.path()); + let last = lines.last().unwrap(); + // The line is bounded: no answer text, its hash and length instead. + assert!(last.payload.get("answer").is_none()); + let closed = closed_of(last).unwrap(); + assert_eq!(closed.answer_bytes, Some(long.len() as u64)); + assert_eq!(closed.answer_sha256.as_deref().map(str::len), Some(64)); + assert!(serde_json::to_string(&last.payload).unwrap().len() < ANSWER_CAP); + let expect = |s: &Store| match kept(s, "token-1", "key-long-0001").unwrap().replay { + Replay::Summary { + first_seq, + last_seq, + closed_seq, + answer_sha256, + answer_bytes, + } => { + assert_eq!(first_seq, closed.first_seq.unwrap()); + assert_eq!(last_seq, closed.last_seq.unwrap()); + assert_eq!(closed_seq, last.seq); + assert_eq!(Some(answer_sha256), closed.answer_sha256.clone()); + assert_eq!(answer_bytes, long.len() as u64); + } + other => panic!("expected a summary: {other:?}"), + }; + expect(&s); + // After a restart the same. + drop(s); + let s = Store::open(tmp.path()).unwrap(); + expect(&s); + s.verify().unwrap(); + // A whole answer at the cap is kept whole. + let mut s = s; + let at_cap = "z".repeat(ANSWER_CAP); + s.begin_call(id("key-long-0002")).unwrap(); + draft(&mut s, "At the cap"); + s.close_call(CallEnd::Done(&at_cap)).unwrap(); + assert_eq!( + answer_of(&kept(&s, "token-1", "key-long-0002").unwrap()), + at_cap + ); +} + +#[test] +fn the_committed_journal_leaves_out_the_lines_of_a_call_that_failed() { + let tmp = tempfile::tempdir().unwrap(); + let mut s = books(tmp.path()); + // A failed call that wrote a draft: it took entry id 1 ... + s.begin_call(id("key-fail-0001")).unwrap(); + draft(&mut s, "Dead"); + s.close_call(CallEnd::Failed("it failed")).unwrap(); + // ... which a later call hands out again. + s.begin_call(id("key-fail-0002")).unwrap(); + draft(&mut s, "Alive"); + s.close_call(CallEnd::Done("{}")).unwrap(); + drop(s); + let lines = lines_of(tmp.path()); + let standing = ledger_store::calls::standings(&lines).unwrap(); + let of = |ty: &str, n: usize| { + lines + .iter() + .zip(&standing) + .filter(|(l, _)| l.line_type == ty) + .nth(n) + .map(|(_, s)| *s) + .unwrap() + }; + assert_eq!(of("entry.created", 0), Standing::Failed); + assert_eq!(of("entry.created", 1), Standing::Counts); + assert_eq!(of("call.begun", 0), Standing::Frame); + let committed = ledger_store::calls::committed(&lines).unwrap(); + // Both calls reused the same entry id; only the second's lines count. + let created: Vec<_> = committed + .iter() + .filter(|l| l.line_type == "entry.created") + .map(|l| l.payload["description"].as_str().unwrap().to_string()) + .collect(); + assert_eq!(created, ["Alive"]); + assert!(committed.iter().all(|l| !l.line_type.starts_with("call."))); + // The history lists every line, and says of the dead ones that they did not count. + let h = Store::open(tmp.path()) + .unwrap() + .journal_history(&ledger_store::describe::HistoryFilter { + limit: 200, + ..Default::default() + }) + .unwrap(); + let dead: Vec<_> = h + .lines + .iter() + .filter(|d| d.standing == Standing::Failed) + .collect(); + assert_eq!(dead.len(), 3); + assert!(dead.iter().all(|d| d.summary.contains("not counted"))); + assert!( + h.lines + .iter() + .filter(|d| d.standing == Standing::Counts) + .all(|d| !d.summary.contains("not counted")) + ); + // A snapshot reads the same. + let snap = Snapshot::load(tmp.path()).unwrap(); + assert_eq!(snap.committed_journal().unwrap().len(), committed.len()); + assert!(snap.journal().len() > committed.len()); } #[test] @@ -140,7 +304,7 @@ fn a_failed_call_is_on_the_record_and_builds_nothing() { assert_eq!(closed.error.as_deref(), Some("it went wrong")); assert!(lines.iter().any(|l| l.line_type == "entry.created")); // A failed key is free again: nothing happened under it. - assert!(s.recorded_call("token-1", "key-aaaa-4").is_none()); + assert!(kept(&s, "token-1", "key-aaaa-4").is_none()); // Books go on: the next call's ids do not collide with the failed one's. s.begin_call(id("key-aaaa-5")).unwrap(); draft(&mut s, "Whole"); @@ -194,7 +358,7 @@ fn a_crash_at_each_point_of_a_call_leaves_the_whole_call_or_none_of_it() { let reopened = Store::open(tmp.path()).unwrap(); same_books(reopened.ledger(), &committed); reopened.verify().unwrap(); - assert!(reopened.recorded_call("token-1", "key-crash-01").is_none()); + assert!(kept(&reopened, "token-1", "key-crash-01").is_none()); let types = types_of(tmp.path()); if k == 0 { // It had written nothing: there is nothing to close. @@ -427,7 +591,7 @@ fn a_call_that_rebuilds_the_projection_still_commits() { s.rebuild().unwrap(); s.close_call(CallEnd::Done("{}")).unwrap(); s.verify().unwrap(); - assert!(s.recorded_call("token-1", "key-heal-0001").is_some()); + assert!(kept(&s, "token-1", "key-heal-0001").is_some()); drop(s); let s = Store::open(tmp.path()).unwrap(); s.verify().unwrap();