Merge branch 't3/transactional-mcp-writes': every write through the tools is one transaction, exactly once (P15 T1, D-88, D-89)
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
38647e2143
61 files changed
+5801
-339
No files matched your search
@@ -60,6 +60,8 @@ pub const NOT_FIGURES: &[&str] = &[
|
||||
"store.created",
|
||||
"journal.format_set",
|
||||
"journal.tail_repaired",
|
||||
"call.begun",
|
||||
"call.closed",
|
||||
"attachment.linked",
|
||||
"attachment.unlinked",
|
||||
"attachment.withdrawn",
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -43,6 +43,9 @@ pub struct Described {
|
||||
pub subjects: Vec<String>,
|
||||
/// The entry it belongs to, if it is about one.
|
||||
pub entry_id: Option<u64>,
|
||||
/// 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).
|
||||
@@ -204,6 +207,15 @@ pub fn describe(line: &JournalLine) -> String {
|
||||
if let Some(d) = p.get("date").and_then(Value::as_str) {
|
||||
parts.push(d.to_string());
|
||||
}
|
||||
// A call's frame: which tool, and how it ended; never the key, the
|
||||
// arguments or the answer.
|
||||
if ty.starts_with("call.") {
|
||||
for k in ["tool", "outcome"] {
|
||||
if let Some(t) = p.get(k).and_then(Value::as_str) {
|
||||
parts.push(quote(t));
|
||||
}
|
||||
}
|
||||
}
|
||||
// Settings: which keys, never their values.
|
||||
if ty == "settings.set"
|
||||
&& let Some(changes) = p.get("changes").and_then(Value::as_array)
|
||||
@@ -236,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<Described>, 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<Described>, bool) {
|
||||
let wanted = |l: &JournalLine| {
|
||||
l.seq > filter.after_seq
|
||||
&& (filter.types.is_empty()
|
||||
@@ -259,12 +288,17 @@ pub fn history(lines: &[JournalLine], filter: &HistoryFilter) -> (Vec<Described>
|
||||
};
|
||||
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)
|
||||
}
|
||||
@@ -290,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()
|
||||
|
||||
@@ -106,6 +106,17 @@ pub enum StoreError {
|
||||
need: String,
|
||||
},
|
||||
|
||||
/// A call (plan P15 2a) was begun or closed when it can't be: one is
|
||||
/// already open, none is, or an earlier call could not be finished.
|
||||
#[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),
|
||||
@@ -185,13 +196,22 @@ pub const FORMAT_UPGRADE_PENDING: &str = "format_upgrade_pending";
|
||||
/// that nothing was changed, that only the owner can give the go-ahead
|
||||
/// (and where), and that the rest still works.
|
||||
fn format_upgrade_text(need: &str) -> String {
|
||||
// D-89: books that haven't declared call_transactions take no writes
|
||||
// at all, so for them the old promise ("everything that needs nothing
|
||||
// new works") is not made.
|
||||
let until = if need == format!("the journal feature {}", crate::format::CALL_TRANSACTIONS) {
|
||||
"Until then these books can be read as ever, but nothing can be written to them: \
|
||||
every write is one transaction that happens exactly once, and books written by an \
|
||||
older version can't keep that until they are upgraded"
|
||||
} else {
|
||||
"Until then everything that needs nothing new works as before"
|
||||
};
|
||||
format!(
|
||||
"{FORMAT_UPGRADE_PENDING}: this needs {need}, and these books are still in the journal \
|
||||
format an older version of wanderbooks wrote: they are waiting for the owner's \
|
||||
go-ahead to upgrade to this version's format. Nothing was changed. Only the owner can \
|
||||
give it, with the owner passphrase: in the app (it asks when it opens the books) or \
|
||||
with `wanderbooks books upgrade ID` at a terminal; no tool can. Until then everything \
|
||||
that needs nothing new works as before"
|
||||
with `wanderbooks books upgrade ID` at a terminal; no tool can. {until}"
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,7 @@ pub const KNOWN_FEATURES: &[&str] = &[
|
||||
DRAFTS_V2,
|
||||
SOURCE_REVISIONS,
|
||||
AUDITS,
|
||||
CALL_TRANSACTIONS,
|
||||
];
|
||||
|
||||
/// Feature: `period.closed` closes to members with `"rounding":
|
||||
@@ -256,6 +257,17 @@ pub const SOURCE_REVISIONS: &str = "source_revisions";
|
||||
/// (BS-format-1, BS-ledger-13).
|
||||
pub const AUDITS: &str = "audits";
|
||||
|
||||
/// Feature: `call_transactions` (plan P15 2a, D-88, D-89): every write a
|
||||
/// tool makes is one transaction. A call's lines are framed by
|
||||
/// `call.begun` and `call.closed`; the lines between them count only when
|
||||
/// the closing line says `ok`, and a call that never closed, or closed
|
||||
/// `failed`, builds no state. An older version doesn't know the two line
|
||||
/// types and would refuse them as unknown, but a version that skipped
|
||||
/// them would replay every line of a half-done or failed call as if it
|
||||
/// were whole; it stops at the declaration instead (BS-format-1). The
|
||||
/// books also take no tool write until they declare it (D-89).
|
||||
pub const CALL_TRANSACTIONS: &str = "call_transactions";
|
||||
|
||||
/// The line type that declares the journal format.
|
||||
pub const FORMAT_SET: &str = "journal.format_set";
|
||||
|
||||
@@ -284,6 +296,8 @@ pub const EVENT_TYPES: &[&str] = &[
|
||||
"audit.run",
|
||||
"bill.created",
|
||||
"bill.paid",
|
||||
"call.begun",
|
||||
"call.closed",
|
||||
"class.added",
|
||||
"convention.retired",
|
||||
"convention.set",
|
||||
@@ -1101,6 +1115,48 @@ mod tests {
|
||||
assert_eq!(up.adds(), vec!["the journal feature audits"]);
|
||||
}
|
||||
|
||||
/// The version before D-88 (every feature but `call_transactions`)
|
||||
/// stops at the declaration as newer: it would refuse a call's frame
|
||||
/// as an unknown type, or, skipping the frame, replay every line of a
|
||||
/// call that failed or never closed as if it were whole. Books that
|
||||
/// declared every earlier feature still wait for it, and take no tool
|
||||
/// write until they have it (D-89).
|
||||
#[test]
|
||||
fn call_transactions_is_its_own_feature() {
|
||||
assert!(KNOWN_FEATURES.contains(&CALL_TRANSACTIONS));
|
||||
let before: Vec<&str> = KNOWN_FEATURES
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|f| *f != CALL_TRANSACTIONS)
|
||||
.collect();
|
||||
let l = line(
|
||||
FORMAT_SET,
|
||||
json!({"format": 2, "features": [AUDITS, CALL_TRANSACTIONS]}),
|
||||
);
|
||||
match declared_knowing(&l, &before) {
|
||||
Err(StoreError::NewerJournal { need, .. }) => {
|
||||
assert_eq!(need, "journal features call_transactions")
|
||||
}
|
||||
other => panic!("expected NewerJournal, got {other:?}"),
|
||||
}
|
||||
let older = JournalFormat {
|
||||
format: 2,
|
||||
features: before.iter().map(|f| f.to_string()).collect(),
|
||||
};
|
||||
let refused = older.require_feature(CALL_TRANSACTIONS);
|
||||
assert!(matches!(
|
||||
refused,
|
||||
Err(StoreError::FormatUpgradePending { .. })
|
||||
));
|
||||
// The refusal tells the owner what is true of these books: no
|
||||
// write at all, not "everything else works".
|
||||
let words = refused.unwrap_err().to_string();
|
||||
assert!(words.contains("nothing can be written"), "{words}");
|
||||
assert!(words.contains("wanderbooks books upgrade"), "{words}");
|
||||
let up = older.upgrade().expect("waits for it");
|
||||
assert_eq!(up.adds(), vec!["the journal feature call_transactions"]);
|
||||
}
|
||||
|
||||
/// The version before K-U5 (every feature but `schedule_minor_unit`)
|
||||
/// stops at the declaration as newer, so it never reads a ¥33,333
|
||||
/// month under the cent rule (and refuses, or posts ¥33,333.33 where
|
||||
|
||||
@@ -53,6 +53,7 @@ pub use format::{FormatUpgrade, JournalFormat, SUPPORTED_JOURNAL_FORMAT};
|
||||
pub use journal::{GENESIS_PREV, JournalLine, JournalWriter};
|
||||
pub use snapshot::{DiskCheck, Snapshot};
|
||||
pub use store::audit;
|
||||
pub use store::calls;
|
||||
pub use store::{
|
||||
Attachment, BillPreview, DepreciationRun, DisposalPreview, EntryRow, EventRow, Extraction,
|
||||
ExtractionStatus, InvoicePreview, JOURNAL_FILE, LEGACY_DB_FILE, LOCK_FILE, MAX_RECURRING_RUN,
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -74,6 +74,10 @@ pub struct Snapshot {
|
||||
head: String,
|
||||
/// The journal format in force (the format gate's record).
|
||||
format: JournalFormat,
|
||||
/// Which lines count (calls.rs): the lines of a call wait here until
|
||||
/// its closing line is read, and a call that failed or never closed
|
||||
/// is never applied.
|
||||
gate: crate::calls::CallGate,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
@@ -95,6 +99,7 @@ impl Snapshot {
|
||||
offset: 0,
|
||||
head: GENESIS_PREV.to_string(),
|
||||
format: JournalFormat::default(),
|
||||
gate: crate::calls::CallGate::default(),
|
||||
};
|
||||
snap.read_new()?;
|
||||
Ok(snap)
|
||||
@@ -209,10 +214,17 @@ impl Snapshot {
|
||||
self.ledger = Ledger::new(self.base_currency);
|
||||
}
|
||||
self.format.admit(&line)?;
|
||||
replay_line_into_ledger(&mut self.ledger, &line, self.base_currency)?;
|
||||
apply_line_to_sqlite(&self.conn, &line)?;
|
||||
self.head = hash;
|
||||
// Only what the call gate releases is applied (calls.rs): a
|
||||
// call's lines wait for its closing line.
|
||||
let index = self.lines.len();
|
||||
let released = self.gate.push(index, &line)?;
|
||||
self.lines.push(line);
|
||||
for i in released {
|
||||
let line = &self.lines[i];
|
||||
replay_line_into_ledger(&mut self.ledger, line, self.base_currency)?;
|
||||
apply_line_to_sqlite(&self.conn, line)?;
|
||||
}
|
||||
self.head = hash;
|
||||
self.offset += len;
|
||||
}
|
||||
Ok(added)
|
||||
@@ -234,17 +246,39 @@ impl Snapshot {
|
||||
&self.format
|
||||
}
|
||||
|
||||
/// The books' id, if they have one ([`crate::calls::books_id_of`]).
|
||||
pub fn books_id(&self) -> Option<String> {
|
||||
crate::calls::books_id_of(&self.lines)
|
||||
}
|
||||
|
||||
/// The data directory.
|
||||
pub fn data_dir(&self) -> &Path {
|
||||
&self.data_dir
|
||||
}
|
||||
|
||||
/// 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<Vec<crate::calls::Standing>, 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<Vec<JournalLine>, 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
|
||||
|
||||
@@ -54,6 +54,9 @@ use std::path::{Path, PathBuf};
|
||||
#[path = "audit.rs"]
|
||||
pub mod audit;
|
||||
|
||||
#[path = "calls.rs"]
|
||||
pub mod calls;
|
||||
|
||||
/// File names inside the data directory.
|
||||
pub const JOURNAL_FILE: &str = "journal.jsonl";
|
||||
|
||||
@@ -493,6 +496,16 @@ pub struct Store {
|
||||
base_currency: Currency,
|
||||
/// The journal format in force (the format gate's record).
|
||||
format: JournalFormat,
|
||||
/// The call open now, if any (calls.rs): every line journaled while it
|
||||
/// is open belongs to it.
|
||||
call: Option<calls::ActiveCall>,
|
||||
/// The keys of every call that committed (calls.rs).
|
||||
keys: calls::Keys,
|
||||
/// The books' id (calls::books_id_of), if they have one.
|
||||
books_id: Option<String>,
|
||||
/// A call could not be finished: no write is taken until the books
|
||||
/// are opened again (calls.rs, close_call).
|
||||
dangling: bool,
|
||||
}
|
||||
|
||||
/// One filing of bytes into the blob store and journal.
|
||||
@@ -591,11 +604,20 @@ impl Store {
|
||||
ledger: Ledger::new(base_currency),
|
||||
base_currency,
|
||||
format: JournalFormat::default(),
|
||||
call: None,
|
||||
keys: calls::Keys::default(),
|
||||
books_id: None,
|
||||
dangling: false,
|
||||
};
|
||||
let line = store.journal.append(
|
||||
"store.created",
|
||||
json!({ "base_currency": base_currency.code() }),
|
||||
)?;
|
||||
// Books that take calls are born with their id; older books are
|
||||
// given one at their format upgrade (declare_journal_format).
|
||||
let mut created = json!({ "base_currency": base_currency.code() });
|
||||
if format.has_feature(crate::format::CALL_TRANSACTIONS) {
|
||||
let id = calls::new_books_id()?;
|
||||
created["books_id"] = json!(id);
|
||||
store.books_id = Some(id);
|
||||
}
|
||||
let line = store.journal.append("store.created", created)?;
|
||||
apply_line_to_sqlite(&store.conn, &line)?;
|
||||
if *format != JournalFormat::default() {
|
||||
let features: Vec<&str> = format.features.iter().map(String::as_str).collect();
|
||||
@@ -667,11 +689,16 @@ impl Store {
|
||||
// Every complete line replayed, in memory, before anything on disk
|
||||
// changes (SCENARIO 3): a line the books can't apply refuses the
|
||||
// open with the journal and the database as they were.
|
||||
// Through the call gate (calls.rs): only the lines of calls that
|
||||
// committed, and every line outside a call, build the books.
|
||||
let (released, gate) = calls::gate_all(&lines)?;
|
||||
let mut ledger = Ledger::new(base_currency);
|
||||
for line in &lines {
|
||||
for &i in &released {
|
||||
crate::cancel::check()?;
|
||||
replay_line_into_ledger(&mut ledger, line, base_currency)?;
|
||||
replay_line_into_ledger(&mut ledger, &lines[i], base_currency)?;
|
||||
}
|
||||
let keys = calls::Keys::from_lines(&lines)?;
|
||||
let books_id = calls::books_id_of(&lines);
|
||||
// Only then is an append cut off mid-line (never acknowledged) set
|
||||
// aside, and journaled below.
|
||||
let torn = if complete < raw.len() {
|
||||
@@ -691,6 +718,8 @@ impl Store {
|
||||
Some("failed integrity_check".to_string())
|
||||
} else if let Some(other) = schema_of(&db_path).filter(|v| *v != schema) {
|
||||
Some(format!("holds schema {other}, not this version's {schema}"))
|
||||
} else if Self::db_applied_seq(&db_path).is_some_and(|n| gate.is_uncommitted(n)) {
|
||||
Some("holds lines of a call that never committed".to_string())
|
||||
} else {
|
||||
match Self::db_currency(&db_path) {
|
||||
Some(c) if c == base_currency => None,
|
||||
@@ -733,8 +762,23 @@ impl Store {
|
||||
ledger,
|
||||
base_currency,
|
||||
format,
|
||||
call: None,
|
||||
keys,
|
||||
books_id,
|
||||
dangling: false,
|
||||
};
|
||||
store.catch_up(&lines)?;
|
||||
store.catch_up(&lines, &released)?;
|
||||
// A call that never closed (calls.rs, SCENARIO 1): on the record
|
||||
// before anything else is written, so the next call's lines are
|
||||
// never inside its frame.
|
||||
if let Some(u) = gate.unfinished() {
|
||||
store.close_unfinished(&u)?;
|
||||
eprintln!(
|
||||
"wanderbooks: the last call to the books ({}) never finished; none of its {} lines count, and it is closed as unfinished in the journal",
|
||||
u.id.tool,
|
||||
u.last_seq - u.first_seq
|
||||
);
|
||||
}
|
||||
if let Some(t) = torn {
|
||||
// On the record, so the repair is part of the audit trail.
|
||||
let line = store.append_journal(
|
||||
@@ -755,6 +799,20 @@ impl Store {
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
/// The last journal line an existing database says it applied.
|
||||
fn db_applied_seq(db_path: &Path) -> Option<u64> {
|
||||
let conn = Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
|
||||
.ok()?;
|
||||
let seq: String = conn
|
||||
.query_row(
|
||||
"SELECT value FROM meta WHERE key='last_applied_seq'",
|
||||
[],
|
||||
|r| r.get(0),
|
||||
)
|
||||
.ok()?;
|
||||
seq.parse().ok()
|
||||
}
|
||||
|
||||
/// The base currency an existing database records, if it can say.
|
||||
fn db_currency(db_path: &Path) -> Option<Currency> {
|
||||
let conn = Connection::open_with_flags(db_path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
|
||||
@@ -832,7 +890,7 @@ impl Store {
|
||||
/// Catch the projection up: apply to SQLite every line past
|
||||
/// `last_applied_seq` (the ledger is already the replay of every line,
|
||||
/// done in memory by [`Store::open`] before anything changed).
|
||||
fn catch_up(&mut self, lines: &[JournalLine]) -> Result<(), StoreError> {
|
||||
fn catch_up(&mut self, lines: &[JournalLine], released: &[usize]) -> Result<(), StoreError> {
|
||||
let last_applied: u64 = self
|
||||
.conn
|
||||
.query_row(
|
||||
@@ -845,7 +903,13 @@ impl Store {
|
||||
.unwrap_or(0);
|
||||
// The ledger is already their replay (Store::open): only the
|
||||
// projection is caught up here.
|
||||
for line in lines.iter().filter(|l| l.seq > last_applied) {
|
||||
// Only the lines that count (calls.rs): a call that didn't commit
|
||||
// never reaches the projection.
|
||||
for line in released
|
||||
.iter()
|
||||
.map(|&i| &lines[i])
|
||||
.filter(|l| l.seq > last_applied)
|
||||
{
|
||||
crate::cancel::check()?;
|
||||
apply_line_to_sqlite(&self.conn, line)?;
|
||||
}
|
||||
@@ -927,9 +991,23 @@ impl Store {
|
||||
format: u32,
|
||||
features: &[&str],
|
||||
) -> Result<(), StoreError> {
|
||||
let payload = self.format.declaration(format, features)?;
|
||||
let mut payload = self.format.declaration(format, features)?;
|
||||
// Older books get their id with the declaration that gives them
|
||||
// call_transactions (calls.rs; plan 6a): new books had one at
|
||||
// creation.
|
||||
let new_id =
|
||||
if self.books_id.is_none() && features.contains(&crate::format::CALL_TRANSACTIONS) {
|
||||
let id = calls::new_books_id()?;
|
||||
payload["books_id"] = json!(id);
|
||||
Some(id)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let line = self.append_journal(crate::format::FORMAT_SET, payload)?;
|
||||
self.format = crate::format::declared(&line)?;
|
||||
if new_id.is_some() {
|
||||
self.books_id = new_id;
|
||||
}
|
||||
apply_line_to_sqlite(&self.conn, &line)?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -1327,6 +1405,8 @@ impl Store {
|
||||
line_type: &str,
|
||||
payload: Value,
|
||||
) -> Result<JournalLine, StoreError> {
|
||||
// The first line of a call opens its frame (calls.rs).
|
||||
self.begin_frame()?;
|
||||
let line = self.journal.append(line_type, payload)?;
|
||||
// The command that posts the entry runs after its line is
|
||||
// journaled: tell the ledger which line that is (plan P4).
|
||||
@@ -6273,10 +6353,11 @@ impl Store {
|
||||
/// ```
|
||||
pub fn verify(&self) -> Result<(), StoreError> {
|
||||
let lines = read_and_verify_journal(self.journal.path())?;
|
||||
let (released, _) = calls::gate_all(&lines)?;
|
||||
let mut replayed = Ledger::new(self.base_currency);
|
||||
for line in &lines {
|
||||
for &i in &released {
|
||||
crate::cancel::check()?;
|
||||
replay_line_into_ledger(&mut replayed, line, self.base_currency)?;
|
||||
replay_line_into_ledger(&mut replayed, &lines[i], self.base_currency)?;
|
||||
}
|
||||
crate::cancel::check()?;
|
||||
let a = reports::snapshot(&replayed).map_err(StoreError::Ledger)?;
|
||||
@@ -6474,14 +6555,22 @@ impl Store {
|
||||
Self::write_meta(&self.conn, "base_currency", self.base_currency.code())?;
|
||||
Self::write_meta(&self.conn, "last_applied_seq", "0")?;
|
||||
let lines = read_and_verify_journal(self.journal.path())?;
|
||||
for line in &lines {
|
||||
let (released, _) = calls::gate_all(&lines)?;
|
||||
for &i in &released {
|
||||
crate::cancel::check()?;
|
||||
apply_line_to_sqlite(&self.conn, line)?;
|
||||
apply_line_to_sqlite(&self.conn, &lines[i])?;
|
||||
}
|
||||
self.ledger = Ledger::new(self.base_currency);
|
||||
for line in &lines {
|
||||
for &i in &released {
|
||||
crate::cancel::check()?;
|
||||
replay_line_into_ledger(&mut self.ledger, line, self.base_currency)?;
|
||||
replay_line_into_ledger(&mut self.ledger, &lines[i], self.base_currency)?;
|
||||
}
|
||||
// A call open now (the verification that heals is itself a call)
|
||||
// keeps its projection transaction, on the new connection
|
||||
// (calls.rs). It has written no line a rebuild would lose: it
|
||||
// reads and rebuilds, nothing more.
|
||||
if self.call.is_some() {
|
||||
self.conn.execute_batch("SAVEPOINT call_tx")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -7348,6 +7437,10 @@ fn replay_line(
|
||||
));
|
||||
}
|
||||
}
|
||||
// A call's frame (calls.rs): the gate decides which lines inside
|
||||
// it reach here; the frame itself changes nothing.
|
||||
"call.begun" => {}
|
||||
"call.closed" => {}
|
||||
"account.added" => {
|
||||
let want = get_u64(p, "id")?;
|
||||
let account_type: AccountType = serde_json::from_value(p["account_type"].clone())?;
|
||||
@@ -8394,6 +8487,10 @@ fn apply_line_rows(conn: &Connection, line: &JournalLine) -> Result<(), StoreErr
|
||||
let p = &line.payload;
|
||||
match line.line_type.as_str() {
|
||||
"store.created" | "journal.tail_repaired" | "journal.format_set" => {}
|
||||
// A call's frame (calls.rs): the replay gate decides which lines
|
||||
// inside it count; the frame itself changes nothing.
|
||||
"call.begun" => {}
|
||||
"call.closed" => {}
|
||||
"account.added" => {
|
||||
conn.execute(
|
||||
"INSERT INTO accounts(id, code, name, type, parent, placeholder, currency) VALUES (?,?,?,?,?,?,?)",
|
||||
@@ -9388,8 +9485,10 @@ fn file_name_of(path: &Path) -> String {
|
||||
pub(crate) fn fresh_projection(lines: &[JournalLine]) -> Result<Connection, StoreError> {
|
||||
let conn = Connection::open_in_memory()?;
|
||||
Store::migrate(&conn)?;
|
||||
for line in lines {
|
||||
apply_line_to_sqlite(&conn, line)?;
|
||||
// Only the lines that count (calls.rs).
|
||||
let (released, _) = calls::gate_all(lines)?;
|
||||
for &i in &released {
|
||||
apply_line_to_sqlite(&conn, &lines[i])?;
|
||||
}
|
||||
Ok(conn)
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user