merge: P15 A1, the server opens and closes one book while it runs
The books server could only open every book at start and close them all at exit. The app is becoming one window with a tab per open company (D-77, D-78), so a company must be reachable exactly while its tab is open. The server now opens and closes one book on request, refuses calls to a closed book in words an agent can relay, and lists who is connected. Four independent reviews shaped it. After a close is answered nothing in the server can write to that book; a call either ran and is journaled or was refused, cut or stopped and left nothing; a close ends within a stated bound; closing one book never stops another's work; and nothing is ever deleted in a backup folder the owner chose. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
commit
a19473b282
35 files changed
+11097
-434
No files matched your search
@@ -323,6 +323,23 @@ fn cpa_package_refuses_without_a_counted_audit_unless_a_reason_is_given() {
|
|||||||
before["decisions"].as_array().unwrap().len() + 1
|
before["decisions"].as_array().unwrap().len() + 1
|
||||||
);
|
);
|
||||||
assert!(after.to_string().contains("without a counted audit"));
|
assert!(after.to_string().contains("without a counted audit"));
|
||||||
|
// A refusal that comes after the reason (an open draft, with no reason of
|
||||||
|
// its own) journals nothing: no decision stands for a package that was
|
||||||
|
// never made.
|
||||||
|
let open = post(&mut w, "2026-03-25", "Still open", "3.00");
|
||||||
|
let held_off = export(
|
||||||
|
&mut w,
|
||||||
|
json!({"without_audit_reason": "the CPA asked for it early"}),
|
||||||
|
);
|
||||||
|
let err: Value = serde_json::from_str(&answer_of(&held_off).unwrap_err()).unwrap();
|
||||||
|
assert_eq!(err["code"], "open_drafts", "{err}");
|
||||||
|
let still = answer_of(&w.call("books.decisions", json!({}))).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
still["decisions"].as_array().unwrap().len(),
|
||||||
|
after["decisions"].as_array().unwrap().len(),
|
||||||
|
"a decision was journaled for a package that was refused"
|
||||||
|
);
|
||||||
|
confirm_post(&mut w, open);
|
||||||
// An audit alone does not open it; nor one attested below the bar.
|
// An audit alone does not open it; nor one attested below the bar.
|
||||||
answer_of(&w.call(
|
answer_of(&w.call(
|
||||||
"books.create_period",
|
"books.create_period",
|
||||||
|
|||||||
File diff suppressed because it is too large.
Load diff
@@ -182,9 +182,25 @@ impl Server {
|
|||||||
Self::start_in(home, home.dir.path(), &[])
|
Self::start_in(home, home.dir.path(), &[])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// [`Server::start`], with these arguments after the root (`--open`).
|
||||||
|
pub fn start_with(home: &Home, args: &[&str]) -> Self {
|
||||||
|
Self::spawn(home, home.dir.path(), &[], args)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Server::start`], with `env` beside the home's own and these
|
||||||
|
/// arguments after the root (a PATH with a stand-in git first, a
|
||||||
|
/// shortened timer).
|
||||||
|
pub fn start_full(home: &Home, env: &[(&str, &Path)], args: &[&str]) -> Self {
|
||||||
|
Self::spawn(home, home.dir.path(), env, args)
|
||||||
|
}
|
||||||
|
|
||||||
/// [`Server::start`], in the folder `cwd`, with `env` beside the
|
/// [`Server::start`], in the folder `cwd`, with `env` beside the
|
||||||
/// home's own (INVARIANT 1).
|
/// home's own (INVARIANT 1).
|
||||||
pub fn start_in(home: &Home, cwd: &Path, env: &[(&str, &Path)]) -> Self {
|
pub fn start_in(home: &Home, cwd: &Path, env: &[(&str, &Path)]) -> Self {
|
||||||
|
Self::spawn(home, cwd, env, &[])
|
||||||
|
}
|
||||||
|
|
||||||
|
fn spawn(home: &Home, cwd: &Path, env: &[(&str, &Path)], args: &[&str]) -> Self {
|
||||||
let log = std::fs::OpenOptions::new()
|
let log = std::fs::OpenOptions::new()
|
||||||
.create(true)
|
.create(true)
|
||||||
.append(true)
|
.append(true)
|
||||||
@@ -195,6 +211,7 @@ impl Server {
|
|||||||
.arg("server")
|
.arg("server")
|
||||||
.arg("--root")
|
.arg("--root")
|
||||||
.arg(home.root())
|
.arg(home.root())
|
||||||
|
.args(args)
|
||||||
.current_dir(cwd);
|
.current_dir(cwd);
|
||||||
clean_env(&mut command, home.dir.path());
|
clean_env(&mut command, home.dir.path());
|
||||||
let mut child = command
|
let mut child = command
|
||||||
@@ -342,6 +359,16 @@ impl Wire {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The MCP session this wire opened (after `initialize`).
|
||||||
|
pub fn session(&self) -> Option<&str> {
|
||||||
|
self.session.as_deref()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The protocol version this session negotiated.
|
||||||
|
pub fn version(&self) -> Option<&str> {
|
||||||
|
self.version.as_deref()
|
||||||
|
}
|
||||||
|
|
||||||
/// The token this session sends.
|
/// The token this session sends.
|
||||||
pub fn token(&self) -> Option<&str> {
|
pub fn token(&self) -> Option<&str> {
|
||||||
self.token.as_deref()
|
self.token.as_deref()
|
||||||
|
|||||||
@@ -333,6 +333,40 @@ fn cpa_package_refuses_open_draft() {
|
|||||||
assert!(journal.contains("the CPA wants it before the receipt comes"));
|
assert!(journal.contains("the CPA wants it before the receipt comes"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A package the build will refuse is refused before any decision is
|
||||||
|
/// journaled (tools/reports.rs INVARIANT 4): the books name a member whose
|
||||||
|
/// capital account isn't in the chart, so the build can never succeed, and
|
||||||
|
/// an override (the reason for an open draft) must not leave "was exported"
|
||||||
|
/// on record, once or on a retry, with no package. The journal does not move.
|
||||||
|
#[test]
|
||||||
|
fn a_package_the_build_refuses_journals_no_decision_even_with_a_reason() {
|
||||||
|
let settings = format!(
|
||||||
|
"{SETTINGS}[[company.members]]\nname = \"Mo\"\nshare = \"100%\"\ncapital_account = \"3999\"\n"
|
||||||
|
);
|
||||||
|
let books = Books::with("p4-cpa-refused", "USD", Some(&settings));
|
||||||
|
let mut w = books.session("p4");
|
||||||
|
chart(&mut w);
|
||||||
|
draft(&mut w, "2026-03-10", "Open", "40.00");
|
||||||
|
let mut args = json!({"as_of": "2026-03-31", "cash_accounts": ["1000"]});
|
||||||
|
args["allow_open_drafts"] = json!({"reason": "the CPA wants it before the receipt comes"});
|
||||||
|
let before = books.journal().len();
|
||||||
|
for _ in 0..2 {
|
||||||
|
let why = answer_of(&w.call("books.export_cpa_package", args.clone()))
|
||||||
|
.expect_err("the build refuses an unknown capital account");
|
||||||
|
assert!(why.contains("unknown capital account 3999"), "{why}");
|
||||||
|
assert_eq!(
|
||||||
|
books.journal().len(),
|
||||||
|
before,
|
||||||
|
"a decision was journaled for a package that was refused"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
assert!(
|
||||||
|
!String::from_utf8(books.journal())
|
||||||
|
.unwrap()
|
||||||
|
.contains("decision.recorded")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/// D-50: a confirm takes the preview it was shown; without it, or after a
|
/// D-50: a confirm takes the preview it was shown; without it, or after a
|
||||||
/// changed argument or a write by another session, it is refused with
|
/// changed argument or a write by another session, it is refused with
|
||||||
/// `stale_preview` before anything is written.
|
/// `stale_preview` before anything is written.
|
||||||
|
|||||||
@@ -474,10 +474,18 @@ fn books_usage(prog: &str) {
|
|||||||
eprintln!(" {prog} back-up ID [--new-disk]");
|
eprintln!(" {prog} back-up ID [--new-disk]");
|
||||||
eprintln!(" {prog} upgrade ID");
|
eprintln!(" {prog} upgrade ID");
|
||||||
eprintln!(" {prog} extract BOOK ATTACHMENT");
|
eprintln!(" {prog} extract BOOK ATTACHMENT");
|
||||||
|
eprintln!(" {prog} open ID");
|
||||||
|
eprintln!(" {prog} close ID");
|
||||||
eprintln!(
|
eprintln!(
|
||||||
" {prog} put-aside ID DATA-DIR [--vault DIR --vault-key FILE] [PATH...] [--yes]"
|
" {prog} put-aside ID DATA-DIR [--vault DIR --vault-key FILE] [PATH...] [--yes]"
|
||||||
);
|
);
|
||||||
eprintln!(" list the books, and whether each is open");
|
eprintln!(" list the books, and whether each is open or closed");
|
||||||
|
eprintln!(
|
||||||
|
" open open one closed book while the server runs, checked as at its start (agents can reach it from then)"
|
||||||
|
);
|
||||||
|
eprintln!(
|
||||||
|
" close close one book while the server runs: its running calls finish, its sessions end, it is backed up and let go; the others keep serving"
|
||||||
|
);
|
||||||
eprintln!(" create start new, empty books (base currency USD unless given)");
|
eprintln!(" create start new, empty books (base currency USD unless given)");
|
||||||
eprintln!(" adopt copy existing books in, verified; the original is left as it was");
|
eprintln!(" adopt copy existing books in, verified; the original is left as it was");
|
||||||
eprintln!(
|
eprintln!(
|
||||||
@@ -604,6 +612,18 @@ pub fn books(
|
|||||||
};
|
};
|
||||||
return put_aside(&common, book, old, yes);
|
return put_aside(&common, book, old, yes);
|
||||||
}
|
}
|
||||||
|
["open", book] => with_server(
|
||||||
|
&common,
|
||||||
|
Request::OpenBook {
|
||||||
|
id: (*book).to_string(),
|
||||||
|
},
|
||||||
|
),
|
||||||
|
["close", book] => with_server(
|
||||||
|
&common,
|
||||||
|
Request::CloseBook {
|
||||||
|
id: (*book).to_string(),
|
||||||
|
},
|
||||||
|
),
|
||||||
["back-up", book] => {
|
["back-up", book] => {
|
||||||
return match back_up_now(&common, book, new_disk) {
|
return match back_up_now(&common, book, new_disk) {
|
||||||
Ok(lines) => {
|
Ok(lines) => {
|
||||||
@@ -666,6 +686,53 @@ pub fn books(
|
|||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
Ok(Response::OpenBook { id, outcome }) => match outcome {
|
||||||
|
admin::OpenOutcome::Opened => {
|
||||||
|
println!("Opened the books \"{id}\": agents can reach them now.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
admin::OpenOutcome::AlreadyOpen => {
|
||||||
|
println!("The books \"{id}\" are open already.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
admin::OpenOutcome::NoSuchBook => {
|
||||||
|
eprintln!(
|
||||||
|
"error: there are no books called \"{id}\": `wanderbooks books list` lists them"
|
||||||
|
);
|
||||||
|
Err(exit(1))
|
||||||
|
}
|
||||||
|
admin::OpenOutcome::CouldNotOpen(why) => {
|
||||||
|
eprintln!("error: the books \"{id}\" couldn't be opened: {why}");
|
||||||
|
Err(exit(1))
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Ok(Response::CloseBook { id, outcome }) => match outcome {
|
||||||
|
admin::CloseOutcome::Closed => {
|
||||||
|
println!(
|
||||||
|
"Closed the books \"{id}\": nothing is running on them, their sessions ended, and they are let go."
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
admin::CloseOutcome::ClosedBackupIncomplete(why) => {
|
||||||
|
println!(
|
||||||
|
"Closed the books \"{id}\": nothing is running on them, their sessions ended, and they are let go."
|
||||||
|
);
|
||||||
|
eprintln!(
|
||||||
|
"warning: their last backup wasn't whole: {why}. What they hold since the last good backup isn't backed up."
|
||||||
|
);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
admin::CloseOutcome::WasNotOpen => {
|
||||||
|
println!("The books \"{id}\" weren't open.");
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
admin::CloseOutcome::NoSuchBook => {
|
||||||
|
eprintln!(
|
||||||
|
"error: there are no books called \"{id}\": `wanderbooks books list` lists them"
|
||||||
|
);
|
||||||
|
Err(exit(1))
|
||||||
|
}
|
||||||
|
},
|
||||||
Ok(Response::Refused(why)) | Err(why) => {
|
Ok(Response::Refused(why)) | Err(why) => {
|
||||||
eprintln!("error: {why}");
|
eprintln!("error: {why}");
|
||||||
Err(exit(1))
|
Err(exit(1))
|
||||||
@@ -679,6 +746,12 @@ pub fn books(
|
|||||||
|
|
||||||
/// One book, as `books list` and `doctor` show it.
|
/// One book, as `books list` and `doctor` show it.
|
||||||
fn book_line(b: &admin::BookStatus) -> String {
|
fn book_line(b: &admin::BookStatus) -> String {
|
||||||
|
if b.closed {
|
||||||
|
return format!(
|
||||||
|
"{} closed (`wanderbooks books open {}` opens it)",
|
||||||
|
b.id, b.id
|
||||||
|
);
|
||||||
|
}
|
||||||
match (&b.problem, &b.format_upgrade) {
|
match (&b.problem, &b.format_upgrade) {
|
||||||
(Some(why), _) => format!("{} didn't open: {why}", b.id),
|
(Some(why), _) => format!("{} didn't open: {why}", b.id),
|
||||||
(None, Some(_)) => format!(
|
(None, Some(_)) => format!(
|
||||||
@@ -689,6 +762,54 @@ fn book_line(b: &admin::BookStatus) -> String {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `doctor`'s lines for who is connected to each open book: the token's
|
||||||
|
/// name, the client and agent as they said, when it connected, the calls
|
||||||
|
/// running and the last call.
|
||||||
|
fn session_lines(open: &[admin::BookSessions]) -> Vec<String> {
|
||||||
|
let mut lines = Vec::new();
|
||||||
|
if open.iter().all(|b| b.sessions.is_empty()) {
|
||||||
|
lines.push("Assistants connected: none.".to_string());
|
||||||
|
return lines;
|
||||||
|
}
|
||||||
|
lines.push("Assistants connected:".to_string());
|
||||||
|
for b in open {
|
||||||
|
if b.sessions.is_empty() {
|
||||||
|
lines.push(format!(" {}: none", b.book));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
lines.push(format!(" {}:", b.book));
|
||||||
|
for s in &b.sessions {
|
||||||
|
let client = match (&s.client_name, &s.client_version) {
|
||||||
|
(Some(n), Some(v)) => format!("{n} {v}"),
|
||||||
|
(Some(n), None) => n.clone(),
|
||||||
|
_ => "a client that hasn't said who it is".to_string(),
|
||||||
|
};
|
||||||
|
let mut line = format!(" token {:?}, {client}", s.token);
|
||||||
|
if let Some(a) = &s.agent {
|
||||||
|
let said: Vec<&str> = [&a.model, &a.reasoning_effort, &a.harness]
|
||||||
|
.into_iter()
|
||||||
|
.filter_map(|v| v.as_deref())
|
||||||
|
.collect();
|
||||||
|
if !said.is_empty() {
|
||||||
|
line.push_str(&format!(" (says: {})", said.join(", ")));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
line.push_str(&format!(", connected {}", s.connected_at));
|
||||||
|
line.push_str(&match s.running {
|
||||||
|
0 => ", no call running".to_string(),
|
||||||
|
1 => ", 1 call running".to_string(),
|
||||||
|
n => format!(", {n} calls running"),
|
||||||
|
});
|
||||||
|
match &s.last {
|
||||||
|
Some(l) => line.push_str(&format!(", last {} ({}) at {}", l.tool, l.outcome, l.at)),
|
||||||
|
None => line.push_str(", no call yet"),
|
||||||
|
}
|
||||||
|
lines.push(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
lines
|
||||||
|
}
|
||||||
|
|
||||||
/// The projection database a book uses, and the other schemas' files
|
/// The projection database a book uses, and the other schemas' files
|
||||||
/// beside it (left as they are for the versions that wrote them, never
|
/// beside it (left as they are for the versions that wrote them, never
|
||||||
/// deleted), as `doctor` says them; None when it didn't open.
|
/// deleted), as `doctor` says them; None when it didn't open.
|
||||||
@@ -2499,6 +2620,18 @@ pub fn doctor(
|
|||||||
Ok(admin::Response::Refused(why)) => println!("Agents' tokens: {why}"),
|
Ok(admin::Response::Refused(why)) => println!("Agents' tokens: {why}"),
|
||||||
Ok(_) | Err(_) => {}
|
Ok(_) | Err(_) => {}
|
||||||
}
|
}
|
||||||
|
// Who is connected to each open book, and what it is doing.
|
||||||
|
match admin::call_within(&socket, Request::Sessions, Some(DOCTOR_WAIT)) {
|
||||||
|
Ok(admin::Response::Sessions(open)) => {
|
||||||
|
for line in session_lines(&open) {
|
||||||
|
println!("{line}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(admin::Response::Refused(why)) => {
|
||||||
|
println!("Assistants connected: {why}")
|
||||||
|
}
|
||||||
|
Ok(_) | Err(_) => {}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
println!("The books are opening (the books server isn't ready yet).");
|
println!("The books are opening (the books server isn't ready yet).");
|
||||||
@@ -3516,6 +3649,7 @@ mod tests {
|
|||||||
|problem: Option<&str>, waiting: Option<admin::FormatWaiting>| admin::BookStatus {
|
|problem: Option<&str>, waiting: Option<admin::FormatWaiting>| admin::BookStatus {
|
||||||
id: "acme".into(),
|
id: "acme".into(),
|
||||||
open: problem.is_none(),
|
open: problem.is_none(),
|
||||||
|
closed: false,
|
||||||
problem: problem.map(str::to_string),
|
problem: problem.map(str::to_string),
|
||||||
format_upgrade: waiting,
|
format_upgrade: waiting,
|
||||||
database: None,
|
database: None,
|
||||||
@@ -3558,6 +3692,78 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `doctor` says who is connected to each open book: the token's name,
|
||||||
|
/// the client and what the agent said, when, the calls running, the
|
||||||
|
/// last call; and that none is when none is.
|
||||||
|
#[test]
|
||||||
|
fn doctor_says_who_is_connected() {
|
||||||
|
let none = [admin::BookSessions {
|
||||||
|
book: "acme".into(),
|
||||||
|
sessions: Vec::new(),
|
||||||
|
}];
|
||||||
|
assert_eq!(session_lines(&none), ["Assistants connected: none."]);
|
||||||
|
let open = [
|
||||||
|
admin::BookSessions {
|
||||||
|
book: "acme".into(),
|
||||||
|
sessions: vec![
|
||||||
|
admin::SessionInfo {
|
||||||
|
token: "agent".into(),
|
||||||
|
client_name: Some("claude-code".into()),
|
||||||
|
client_version: Some("2.1".into()),
|
||||||
|
agent: Some(admin::SessionAgent {
|
||||||
|
model: Some("m-1".into()),
|
||||||
|
reasoning_effort: None,
|
||||||
|
harness: Some("h-1".into()),
|
||||||
|
}),
|
||||||
|
connected_at: "2026-11-20T10:00:00Z".into(),
|
||||||
|
running: 2,
|
||||||
|
last: Some(admin::LastCall {
|
||||||
|
tool: "books.chart".into(),
|
||||||
|
outcome: "ok".into(),
|
||||||
|
at: "2026-11-20T10:01:00Z".into(),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
admin::SessionInfo {
|
||||||
|
token: "web".into(),
|
||||||
|
client_name: None,
|
||||||
|
client_version: None,
|
||||||
|
agent: None,
|
||||||
|
connected_at: "2026-11-20T10:02:00Z".into(),
|
||||||
|
running: 0,
|
||||||
|
last: None,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
admin::BookSessions {
|
||||||
|
book: "beta".into(),
|
||||||
|
sessions: Vec::new(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
assert_eq!(
|
||||||
|
session_lines(&open),
|
||||||
|
[
|
||||||
|
"Assistants connected:",
|
||||||
|
" acme:",
|
||||||
|
" token \"agent\", claude-code 2.1 (says: m-1, h-1), connected 2026-11-20T10:00:00Z, 2 calls running, last books.chart (ok) at 2026-11-20T10:01:00Z",
|
||||||
|
" token \"web\", a client that hasn't said who it is, connected 2026-11-20T10:02:00Z, no call running, no call yet",
|
||||||
|
" beta: none",
|
||||||
|
]
|
||||||
|
);
|
||||||
|
let closed = admin::BookStatus {
|
||||||
|
id: "acme".into(),
|
||||||
|
open: false,
|
||||||
|
closed: true,
|
||||||
|
problem: None,
|
||||||
|
format_upgrade: None,
|
||||||
|
database: None,
|
||||||
|
other_databases: Vec::new(),
|
||||||
|
};
|
||||||
|
assert_eq!(
|
||||||
|
book_line(&closed),
|
||||||
|
"acme closed (`wanderbooks books open acme` opens it)"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/// `doctor` names the database file a book uses, and any other
|
/// `doctor` names the database file a book uses, and any other
|
||||||
/// schema's beside it as left alone; nothing for books that didn't
|
/// schema's beside it as left alone; nothing for books that didn't
|
||||||
/// open.
|
/// open.
|
||||||
@@ -3566,6 +3772,7 @@ mod tests {
|
|||||||
let mut b = admin::BookStatus {
|
let mut b = admin::BookStatus {
|
||||||
id: "acme".into(),
|
id: "acme".into(),
|
||||||
open: true,
|
open: true,
|
||||||
|
closed: false,
|
||||||
problem: None,
|
problem: None,
|
||||||
format_upgrade: None,
|
format_upgrade: None,
|
||||||
database: Some("wanderbooks.v13.db".into()),
|
database: Some("wanderbooks.v13.db".into()),
|
||||||
|
|||||||
@@ -21,6 +21,14 @@
|
|||||||
//! 4. A record's head is the journal's head after the call's own last
|
//! 4. A record's head is the journal's head after the call's own last
|
||||||
//! write (taken under the store's lock as it lets go), whatever the
|
//! write (taken under the store's lock as it lets go), whatever the
|
||||||
//! call answered; none for a call that wrote nothing.
|
//! call answered; none for a call that wrote nothing.
|
||||||
|
//! 5. A record is written only while the book is open: the log is closed
|
||||||
|
//! (ledger_store::access INVARIANT 4) when the book is let go, so a
|
||||||
|
//! refusal still being written when it was (its client gone, its
|
||||||
|
//! session ended) is refused, unwritten, and never lands in the log of
|
||||||
|
//! the book opened again. A refusal at the door is written by a task
|
||||||
|
//! that keeps the request's place inside the book's door (local.rs
|
||||||
|
//! INVARIANT 13). A call that ran is written inside its counted run,
|
||||||
|
//! before its answer goes: it is always on record.
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use ledger_store::access::{Access, AccessLog, Client, Outcome, Principal, digest};
|
use ledger_store::access::{Access, AccessLog, Client, Outcome, Principal, digest};
|
||||||
@@ -61,6 +69,17 @@ pub fn caller(context: &RequestContext<RoleServer>) -> Option<Caller> {
|
|||||||
.cloned()
|
.cloned()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The MCP session a request belongs to (its `mcp-session-id`), as the
|
||||||
|
/// door left the request's parts in `extensions`; None for a request that
|
||||||
|
/// came another way.
|
||||||
|
pub(crate) fn session_of(extensions: &rmcp::model::Extensions) -> Option<String> {
|
||||||
|
extensions
|
||||||
|
.get::<axum::http::request::Parts>()
|
||||||
|
.and_then(|parts| parts.headers.get(crate::local::SESSION_HEADER))
|
||||||
|
.and_then(|v| v.to_str().ok())
|
||||||
|
.map(str::to_string)
|
||||||
|
}
|
||||||
|
|
||||||
/// The client program, as it named itself at `initialize`.
|
/// The client program, as it named itself at `initialize`.
|
||||||
fn client(context: &RequestContext<RoleServer>) -> Option<Client> {
|
fn client(context: &RequestContext<RoleServer>) -> Option<Client> {
|
||||||
context.peer.peer_info().map(|info| Client {
|
context.peer.peer_info().map(|info| Client {
|
||||||
@@ -87,6 +106,12 @@ pub(crate) struct Call {
|
|||||||
subject: String,
|
subject: String,
|
||||||
args_digest: Option<String>,
|
args_digest: Option<String>,
|
||||||
agent: Option<ledger_store::access::Agent>,
|
agent: Option<ledger_store::access::Agent>,
|
||||||
|
/// The book's board of live sessions, and the session this call is
|
||||||
|
/// in: it counts as running there until the call ends, and is what
|
||||||
|
/// the session last did once recorded (sessions.rs).
|
||||||
|
board: Arc<crate::sessions::Board>,
|
||||||
|
session: Option<String>,
|
||||||
|
_live: Option<Arc<crate::sessions::Live>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Why a call wasn't run, for its record and its answer.
|
/// Why a call wasn't run, for its record and its answer.
|
||||||
@@ -95,8 +120,13 @@ pub(crate) const UNAUTHORIZED: &str = "unauthorized";
|
|||||||
pub(crate) const INSUFFICIENT_SCOPE: &str = "insufficient_scope";
|
pub(crate) const INSUFFICIENT_SCOPE: &str = "insufficient_scope";
|
||||||
/// The books were closing.
|
/// The books were closing.
|
||||||
pub(crate) const CLOSING: &str = "closing";
|
pub(crate) const CLOSING: &str = "closing";
|
||||||
|
/// A close cut the request while its body was still arriving.
|
||||||
|
pub(crate) const CUT: &str = "cut_by_close";
|
||||||
/// The server had stopped.
|
/// The server had stopped.
|
||||||
pub(crate) const STOPPED: &str = "stopped";
|
pub(crate) const STOPPED: &str = "stopped";
|
||||||
|
/// A call that was running when a close began, stopped by it: it answered
|
||||||
|
/// that it was stopped, and nothing it was doing is recorded as done.
|
||||||
|
pub(crate) const STOPPED_BY_CLOSE: &str = "stopped_by_close";
|
||||||
/// A file's bytes or text came as an argument (D-46).
|
/// A file's bytes or text came as an argument (D-46).
|
||||||
pub(crate) const INLINE_FILE: &str = "inline_file";
|
pub(crate) const INLINE_FILE: &str = "inline_file";
|
||||||
|
|
||||||
@@ -113,11 +143,16 @@ impl Call {
|
|||||||
/// close beginning meanwhile waits for it.
|
/// close beginning meanwhile waits for it.
|
||||||
pub(crate) fn new(
|
pub(crate) fn new(
|
||||||
log: &Arc<AccessLog>,
|
log: &Arc<AccessLog>,
|
||||||
|
board: &Arc<crate::sessions::Board>,
|
||||||
context: &RequestContext<RoleServer>,
|
context: &RequestContext<RoleServer>,
|
||||||
action: &'static str,
|
action: &'static str,
|
||||||
subject: &str,
|
subject: &str,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
|
let session = session_of(&context.extensions);
|
||||||
Self {
|
Self {
|
||||||
|
board: board.clone(),
|
||||||
|
_live: session.as_deref().map(|sid| Arc::new(board.begin(sid))),
|
||||||
|
session,
|
||||||
log: log.clone(),
|
log: log.clone(),
|
||||||
caller: caller(context),
|
caller: caller(context),
|
||||||
client: client(context),
|
client: client(context),
|
||||||
@@ -187,7 +222,19 @@ impl Call {
|
|||||||
agent: self.agent.clone(),
|
agent: self.agent.clone(),
|
||||||
};
|
};
|
||||||
match self.log.record(&access) {
|
match self.log.record(&access) {
|
||||||
Ok(_) => Ok(()),
|
Ok(_) => {
|
||||||
|
if let Some(sid) = &self.session {
|
||||||
|
self.board.finished(
|
||||||
|
sid,
|
||||||
|
&access.subject,
|
||||||
|
&access.result,
|
||||||
|
access.client.as_ref(),
|
||||||
|
access.agent.as_ref(),
|
||||||
|
chrono::Utc::now().timestamp(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!("wanderbooks server: an access record couldn't be written: {e}");
|
eprintln!("wanderbooks server: an access record couldn't be written: {e}");
|
||||||
Err(())
|
Err(())
|
||||||
|
|||||||
@@ -8,7 +8,8 @@
|
|||||||
//! the data root itself: the server, its sole writer, does it.
|
//! the data root itself: the server, its sole writer, does it.
|
||||||
//! SOURCE: plan/served.md 3.1 (the CLI "talks to run/admin.sock ... it can
|
//! SOURCE: plan/served.md 3.1 (the CLI "talks to run/admin.sock ... it can
|
||||||
//! create or adopt books"), 5.5 (adoption), 3.9 (protocol versions
|
//! create or adopt books"), 5.5 (adoption), 3.9 (protocol versions
|
||||||
//! N and N-1).
|
//! N and N-1); plan/p15-app-and-relay.md 3.1 (open and close one
|
||||||
|
//! book at run time; who is connected), D-77, D-78.
|
||||||
//! INVARIANTS:
|
//! INVARIANTS:
|
||||||
//! 1. One request per connection, one JSON line each way, at most
|
//! 1. One request per connection, one JSON line each way, at most
|
||||||
//! MAX_LINE bytes; anything else is refused with a plain reason.
|
//! MAX_LINE bytes; anything else is refused with a plain reason.
|
||||||
@@ -30,6 +31,19 @@
|
|||||||
//! 7. A format upgrade is asked with the owner passphrase, which the
|
//! 7. A format upgrade is asked with the owner passphrase, which the
|
||||||
//! server checks before anything is done (plan 3.9, D-39); no answer
|
//! server checks before anything is done (plan 3.9, D-39); no answer
|
||||||
//! carries it, and Debug never shows it.
|
//! carries it, and Debug never shows it.
|
||||||
|
//! 8. Opening and closing ONE book (`open_book`, `close_book`) are
|
||||||
|
//! admin requests (plan/p15-app-and-relay.md 3.1; D-77, D-78): each
|
||||||
|
//! answers what happened in a word (opened, already open, closed,
|
||||||
|
//! was not open, no such book, could not open with why), and a book
|
||||||
|
//! that is closed is listed as closed, which is not a problem. A
|
||||||
|
//! close is answered only when the books are let go and nothing of
|
||||||
|
//! this process's can write to them; its last backup (a bounded
|
||||||
|
//! step) that wasn't whole is said, in `closed_backup_incomplete`
|
||||||
|
//! with why, never as a plain `closed`.
|
||||||
|
//! 9. `sessions` says, for each open book, who is connected: a token's
|
||||||
|
//! NAME (never its text, nor its hash), what the client and the agent
|
||||||
|
//! said of themselves, when it connected, how many of its calls are
|
||||||
|
//! running, and its last call. A session that ended is not listed.
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
@@ -174,6 +188,22 @@ pub enum Request {
|
|||||||
/// The attachment to read.
|
/// The attachment to read.
|
||||||
attachment_id: u64,
|
attachment_id: u64,
|
||||||
},
|
},
|
||||||
|
/// Open one book that is not open (INVARIANT 8): checked and verified
|
||||||
|
/// exactly as at the server's start.
|
||||||
|
OpenBook {
|
||||||
|
/// The books.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// Close one book while the server runs (INVARIANT 8): new calls on it
|
||||||
|
/// are refused from the moment this begins, the calls running on it
|
||||||
|
/// finish, its sessions end, and it is let go of as at the server's
|
||||||
|
/// close (a last backup, its writer lock released).
|
||||||
|
CloseBook {
|
||||||
|
/// The books.
|
||||||
|
id: String,
|
||||||
|
},
|
||||||
|
/// Who is connected to each open book (INVARIANT 9).
|
||||||
|
Sessions,
|
||||||
/// End a token.
|
/// End a token.
|
||||||
TokenRevoke {
|
TokenRevoke {
|
||||||
/// Its books.
|
/// Its books.
|
||||||
@@ -298,6 +328,11 @@ pub struct BookStatus {
|
|||||||
pub id: String,
|
pub id: String,
|
||||||
/// Whether it is open and served.
|
/// Whether it is open and served.
|
||||||
pub open: bool,
|
pub open: bool,
|
||||||
|
/// Whether it was closed (at the server's start, or by `close_book`):
|
||||||
|
/// not open, and no problem. A book that failed to open is not closed:
|
||||||
|
/// it has a `problem`.
|
||||||
|
#[serde(default)]
|
||||||
|
pub closed: bool,
|
||||||
/// Why it couldn't be opened, if it couldn't.
|
/// Why it couldn't be opened, if it couldn't.
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
pub problem: Option<String>,
|
pub problem: Option<String>,
|
||||||
@@ -314,6 +349,99 @@ pub struct BookStatus {
|
|||||||
pub other_databases: Vec<String>,
|
pub other_databases: Vec<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What `open_book` came to.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum OpenOutcome {
|
||||||
|
/// It was closed (or had failed to open) and is open now.
|
||||||
|
Opened,
|
||||||
|
/// It was open already: nothing was done.
|
||||||
|
AlreadyOpen,
|
||||||
|
/// There are no such books in the data root.
|
||||||
|
NoSuchBook,
|
||||||
|
/// It could not be opened, and why (it stays listed, with this
|
||||||
|
/// `problem`).
|
||||||
|
CouldNotOpen(String),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What `close_book` came to.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
#[serde(rename_all = "snake_case")]
|
||||||
|
pub enum CloseOutcome {
|
||||||
|
/// It was open and is closed now: no call on it is running, its
|
||||||
|
/// sessions ended, and another process could open it.
|
||||||
|
Closed,
|
||||||
|
/// It was open and is closed as `Closed` says, but its last backup
|
||||||
|
/// wasn't whole (a target that couldn't be reached, git that failed, or
|
||||||
|
/// a backup stopped after its time): why, in words. The books on disk
|
||||||
|
/// are whole; what they hold since the last good backup is not backed
|
||||||
|
/// up.
|
||||||
|
ClosedBackupIncomplete(String),
|
||||||
|
/// It was not open (closed already, or it never opened): nothing was
|
||||||
|
/// done.
|
||||||
|
WasNotOpen,
|
||||||
|
/// There are no such books in the data root.
|
||||||
|
NoSuchBook,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What an agent said about itself (`books.start`'s `agent`): asserted,
|
||||||
|
/// never checked.
|
||||||
|
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct SessionAgent {
|
||||||
|
/// The model's name.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub model: Option<String>,
|
||||||
|
/// The reasoning effort it ran at.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub reasoning_effort: Option<String>,
|
||||||
|
/// The program driving it.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub harness: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A session's last call.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct LastCall {
|
||||||
|
/// The tool (or the resource's address).
|
||||||
|
pub tool: String,
|
||||||
|
/// "ok", "error", or "refused: CODE".
|
||||||
|
pub outcome: String,
|
||||||
|
/// When it finished (UTC, RFC 3339).
|
||||||
|
pub at: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One live MCP session (INVARIANT 9).
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct SessionInfo {
|
||||||
|
/// The NAME of the token it was opened with: never the token.
|
||||||
|
pub token: String,
|
||||||
|
/// The client program's name, as it said at `initialize`.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub client_name: Option<String>,
|
||||||
|
/// Its version.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub client_version: Option<String>,
|
||||||
|
/// What the agent said about itself, if it has.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub agent: Option<SessionAgent>,
|
||||||
|
/// When it connected (UTC, RFC 3339).
|
||||||
|
pub connected_at: String,
|
||||||
|
/// Calls of it running now.
|
||||||
|
pub running: u32,
|
||||||
|
/// The last call it made, if it has made one.
|
||||||
|
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||||
|
pub last: Option<LastCall>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An open book's live sessions.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct BookSessions {
|
||||||
|
/// The books.
|
||||||
|
pub book: String,
|
||||||
|
/// Its live sessions, the longest connected first.
|
||||||
|
pub sessions: Vec<SessionInfo>,
|
||||||
|
}
|
||||||
|
|
||||||
/// A setting an adoption would move in.
|
/// A setting an adoption would move in.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct SettingChange {
|
pub struct SettingChange {
|
||||||
@@ -486,6 +614,22 @@ pub enum Response {
|
|||||||
},
|
},
|
||||||
/// A format upgrade made (or none needed).
|
/// A format upgrade made (or none needed).
|
||||||
FormatUpgraded(FormatUpgraded),
|
FormatUpgraded(FormatUpgraded),
|
||||||
|
/// What `open_book` came to.
|
||||||
|
OpenBook {
|
||||||
|
/// The books.
|
||||||
|
id: String,
|
||||||
|
/// What happened.
|
||||||
|
outcome: OpenOutcome,
|
||||||
|
},
|
||||||
|
/// What `close_book` came to.
|
||||||
|
CloseBook {
|
||||||
|
/// The books.
|
||||||
|
id: String,
|
||||||
|
/// What happened.
|
||||||
|
outcome: CloseOutcome,
|
||||||
|
},
|
||||||
|
/// Who is connected, for each open book (INVARIANT 9).
|
||||||
|
Sessions(Vec<BookSessions>),
|
||||||
/// An attachment's text read and journaled (plan P6 step 2).
|
/// An attachment's text read and journaled (plan P6 step 2).
|
||||||
Extracted {
|
Extracted {
|
||||||
/// The attachment.
|
/// The attachment.
|
||||||
@@ -536,7 +680,10 @@ pub fn call_within(
|
|||||||
let not_sent = |why: String| CallError::NotSent(why);
|
let not_sent = |why: String| CallError::NotSent(why);
|
||||||
// A list changes nothing: its only question is whether it answered.
|
// A list changes nothing: its only question is whether it answered.
|
||||||
let look = match request {
|
let look = match request {
|
||||||
Request::List | Request::TokenList | Request::TokenCheck { .. } => None,
|
Request::List | Request::TokenList | Request::TokenCheck { .. } | Request::Sessions => None,
|
||||||
|
Request::OpenBook { .. } | Request::CloseBook { .. } => {
|
||||||
|
Some("`wanderbooks books list` says whether the books are open")
|
||||||
|
}
|
||||||
Request::Create { .. } | Request::Adopt { .. } | Request::Restore { .. } => {
|
Request::Create { .. } | Request::Adopt { .. } | Request::Restore { .. } => {
|
||||||
Some("`wanderbooks books list` shows the books there are")
|
Some("`wanderbooks books list` shows the books there are")
|
||||||
}
|
}
|
||||||
@@ -699,6 +846,7 @@ mod tests {
|
|||||||
for r in [
|
for r in [
|
||||||
Response::Books(vec![
|
Response::Books(vec![
|
||||||
BookStatus {
|
BookStatus {
|
||||||
|
closed: false,
|
||||||
id: "acme".into(),
|
id: "acme".into(),
|
||||||
open: false,
|
open: false,
|
||||||
problem: Some("damaged".into()),
|
problem: Some("damaged".into()),
|
||||||
@@ -707,6 +855,7 @@ mod tests {
|
|||||||
other_databases: Vec::new(),
|
other_databases: Vec::new(),
|
||||||
},
|
},
|
||||||
BookStatus {
|
BookStatus {
|
||||||
|
closed: false,
|
||||||
id: "beta".into(),
|
id: "beta".into(),
|
||||||
open: true,
|
open: true,
|
||||||
problem: None,
|
problem: None,
|
||||||
|
|||||||
+411
-23
@@ -48,16 +48,96 @@
|
|||||||
//! exactly as they are (journal, stored files, vault and keys), all
|
//! exactly as they are (journal, stored files, vault and keys), all
|
||||||
//! under the store's lock, so nothing is written in between; a backup
|
//! under the store's lock, so nothing is written in between; a backup
|
||||||
//! that can't be made or proven upgrades nothing. Both are records.
|
//! that can't be made or proven upgrades nothing. Both are records.
|
||||||
|
//! 10. These backups can be shut (`shut`), once, for good: git is stopped
|
||||||
|
//! (every command running, with all it started) and none starts; the
|
||||||
|
//! call waits for every step that was under way to END (each step's
|
||||||
|
//! count rides in its own blocking task, so it is not lost when the
|
||||||
|
//! future that began it is dropped, as a close's 60 s bound drops
|
||||||
|
//! one), and for the run or drill holding the books' turn; then the
|
||||||
|
//! backup record is closed under its own lock. After `shut` returns,
|
||||||
|
//! this holder (a timer's, a request's, any clone from before) runs
|
||||||
|
//! nothing, spawns no process, and writes nothing, whatever the books
|
||||||
|
//! are doing: not in this process's later opening of the same books,
|
||||||
|
//! whose own backups are another object with another record handle.
|
||||||
|
//! 11. A close is not held by a step it doesn't wait for. When a close
|
||||||
|
//! begins (`hurry`, before its last backup), these stop at their next
|
||||||
|
//! look: a drill, a format upgrade that has not yet reached its final
|
||||||
|
//! look, and a backup a call or a timer asked for (`run_with` for any
|
||||||
|
//! `why` but `close`), looking between git commands and phases, once
|
||||||
|
//! per journal line, file or 64 KiB chunk (ledger_store::backup
|
||||||
|
//! INVARIANT 6), and between targets. A drill's scratch clone is
|
||||||
|
//! removed and nothing is said of its target (neither a pass nor a
|
||||||
|
//! failure: it is due again when the books next open). A run stopped
|
||||||
|
//! this way records `stopped` (what it was doing: `commit` or `push`)
|
||||||
|
//! and no result of its own for the step it didn't finish: a commit it
|
||||||
|
//! had made stands in the archive and is recorded as made, a target it
|
||||||
|
//! hadn't pushed to is said nothing of, and its caller is told it was
|
||||||
|
//! stopped because the books are closing (tools/backup.rs, which marks
|
||||||
|
//! the call's access record `stopped_by_close`). The one thing a stop is
|
||||||
|
//! a failure for is a lock git left in the owner's folder (INVARIANT 12).
|
||||||
|
//! An upgrade is reported not done, the books unchanged, and its backup
|
||||||
|
//! (a commit it made on the way) recorded, if the close's stop reaches
|
||||||
|
//! it before its final look, which is made once everything it needs is
|
||||||
|
//! proven and just before the `journal.format_set` line is appended: a
|
||||||
|
//! stop is honoured up to that look. One that arrives between it and the
|
||||||
|
//! append does not undo the upgrade: the line is appended, the database's
|
||||||
|
//! row is written and the upgrade is recorded as made (safe: the books
|
||||||
|
//! are in this version's format and proven backed up, and the close that
|
||||||
|
//! asked for the stop is waiting for the books lock). The last backup of
|
||||||
|
//! the close, and the stop `shut` makes of what is left of it, are not
|
||||||
|
//! hurried: only `shut` stops them. The close's whole bound is the sum
|
||||||
|
//! written in the books server's INVARIANT 10 (local.rs).
|
||||||
|
//! 12. A lock file a stopped git left is dealt with by the step that
|
||||||
|
//! stopped it (ledger_store::backup INVARIANT 5) and recorded: a
|
||||||
|
//! record `lock_removed` (the archive's own, made by the git just
|
||||||
|
//! stopped) or `lock_left`, with `repo` (`archive`, `folder` or
|
||||||
|
//! `repository`), `lock` (a path in that repository), `why`, and for a
|
||||||
|
//! lock left in the owner's folder, `path`, its whole path. Git is sent
|
||||||
|
//! SIGTERM first and removes its own locks, so these records are the
|
||||||
|
//! rare case. A lock left in the owner's folder is never removed by
|
||||||
|
//! this program: it marks that target's backup failed, in a `push`
|
||||||
|
//! record whose error names the files and says to remove them only when
|
||||||
|
//! nothing else is using the backup folder; that error is the target's
|
||||||
|
//! `last_error` in `books.backup` and in the server's backup status, and
|
||||||
|
//! what a close that couldn't finish its last backup says. (A run whose
|
||||||
|
//! future was dropped at its bound has that record written by `shut`.)
|
||||||
|
//! The archive's locks found when the books open are dealt with the
|
||||||
|
//! same way (the store is open, and its lock is ours): only those older
|
||||||
|
//! than ten minutes are removed. A close is not answered before these
|
||||||
|
//! are recorded, the backup record being closed after them.
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::server::SharedStore;
|
use crate::server::SharedStore;
|
||||||
use ledger_store::backup::{self, BackupError, Git, Target};
|
use ledger_store::backup::{self, BackupError, Git, LockNotes, Target};
|
||||||
use ledger_store::chain::ChainLog;
|
use ledger_store::chain::ChainLog;
|
||||||
use serde::Serialize;
|
use serde::Serialize;
|
||||||
use serde_json::{Map, Value, json};
|
use serde_json::{Map, Value, json};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
|
||||||
use std::sync::{Arc, Mutex};
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
/// What a call is told when these backups were shut (INVARIANT 10).
|
||||||
|
pub const SHUT: &str = "the books were closed: nothing was backed up";
|
||||||
|
|
||||||
|
/// Blocking steps of the backups under way (INVARIANT 10).
|
||||||
|
#[derive(Default)]
|
||||||
|
struct Busy {
|
||||||
|
steps: AtomicUsize,
|
||||||
|
ended: tokio::sync::Notify,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One step under way, counted until it is dropped: it rides in the
|
||||||
|
/// step's own blocking task, so it ends with the work, not with whatever
|
||||||
|
/// was waiting for it.
|
||||||
|
struct Step(Arc<Busy>);
|
||||||
|
|
||||||
|
impl Drop for Step {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.0.steps.fetch_sub(1, Ordering::SeqCst);
|
||||||
|
self.0.ended.notify_waiters();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The book's backup record, in its `ops/`.
|
/// The book's backup record, in its `ops/`.
|
||||||
pub const LOG_FILE: &str = "backup.jsonl";
|
pub const LOG_FILE: &str = "backup.jsonl";
|
||||||
/// The record's genesis text.
|
/// The record's genesis text.
|
||||||
@@ -71,6 +151,9 @@ pub const RETRY_AFTER: std::time::Duration = std::time::Duration::from_secs(15 *
|
|||||||
/// The most of an error kept.
|
/// The most of an error kept.
|
||||||
const ERROR_MAX: usize = 500;
|
const ERROR_MAX: usize = 500;
|
||||||
|
|
||||||
|
/// The test knob that holds a stoppable call as it begins ([`Backups::set_hold`]).
|
||||||
|
type CallHold = Arc<dyn Fn(&str) + Send + Sync>;
|
||||||
|
|
||||||
/// A book's backups.
|
/// A book's backups.
|
||||||
pub struct Backups {
|
pub struct Backups {
|
||||||
book: String,
|
book: String,
|
||||||
@@ -79,6 +162,30 @@ pub struct Backups {
|
|||||||
log: Mutex<ChainLog>,
|
log: Mutex<ChainLog>,
|
||||||
/// One run at a time.
|
/// One run at a time.
|
||||||
running: tokio::sync::Mutex<()>,
|
running: tokio::sync::Mutex<()>,
|
||||||
|
/// Set by `shut` (INVARIANT 10): git stops, nothing starts.
|
||||||
|
shut: Arc<AtomicBool>,
|
||||||
|
/// The blocking steps under way.
|
||||||
|
busy: Arc<Busy>,
|
||||||
|
/// Set when a close begins, before its last backup (INVARIANT 11): the
|
||||||
|
/// steps a close doesn't wait for (a drill, a format upgrade not yet
|
||||||
|
/// journaled, a backup a call or a timer asked for) stop, and `shut`
|
||||||
|
/// sets it too. It is the book's store's flag (`SharedStore::hurry`), so
|
||||||
|
/// the book's calls that can run long see it too. The close's own last
|
||||||
|
/// backup is stopped by `shut` alone, so it can run.
|
||||||
|
hurry: Arc<AtomicBool>,
|
||||||
|
/// The lock files a stopped git left, as they were dealt with
|
||||||
|
/// (ledger_store::backup INVARIANT 5), until they are recorded.
|
||||||
|
locks: LockNotes,
|
||||||
|
/// A test knob (`--slow-steps`): how long a drill or a format upgrade
|
||||||
|
/// waits, in milliseconds, at each phase, giving up when hurried.
|
||||||
|
slow_ms: AtomicU64,
|
||||||
|
/// Phases that began their wait (the test knob), for a test to see
|
||||||
|
/// that a step is inside one.
|
||||||
|
paused: Arc<AtomicUsize>,
|
||||||
|
/// A test knob (`--timer-hold`): told the name of a call that can be
|
||||||
|
/// stopped by a close as it begins (`books.verify`, ...); it may wait,
|
||||||
|
/// and gives up when the close begins (`hurry`). Nothing without it.
|
||||||
|
hold: Mutex<Option<CallHold>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// What a format upgrade did ([`Backups::upgrade_format`]).
|
/// What a format upgrade did ([`Backups::upgrade_format`]).
|
||||||
@@ -250,16 +357,31 @@ impl Backups {
|
|||||||
}
|
}
|
||||||
Err(e) => return Err(format!("its backup record can't be used: {e}")),
|
Err(e) => return Err(format!("its backup record can't be used: {e}")),
|
||||||
};
|
};
|
||||||
|
let hurry = store.hurry_flag();
|
||||||
let me = Self {
|
let me = Self {
|
||||||
book: book.to_string(),
|
book: book.to_string(),
|
||||||
dir: dir.to_path_buf(),
|
dir: dir.to_path_buf(),
|
||||||
store,
|
store,
|
||||||
log: Mutex::new(log),
|
log: Mutex::new(log),
|
||||||
running: tokio::sync::Mutex::new(()),
|
running: tokio::sync::Mutex::new(()),
|
||||||
|
shut: Arc::default(),
|
||||||
|
busy: Arc::default(),
|
||||||
|
hurry,
|
||||||
|
locks: LockNotes::default(),
|
||||||
|
slow_ms: AtomicU64::new(0),
|
||||||
|
paused: Arc::default(),
|
||||||
|
hold: Mutex::new(None),
|
||||||
};
|
};
|
||||||
for fields in carried {
|
for fields in carried {
|
||||||
me.record(fields);
|
me.record(fields);
|
||||||
}
|
}
|
||||||
|
// The store is open, so its lock is ours: no other wanderbooks
|
||||||
|
// process runs git on this archive, and none of this process's does
|
||||||
|
// yet. A lock in it older than ten minutes is a dead git's; a
|
||||||
|
// younger one is left (store INVARIANT 5a).
|
||||||
|
for note in backup::clear_archive_locks(dir) {
|
||||||
|
me.record_lock(¬e);
|
||||||
|
}
|
||||||
// Books just restored: whose they were (INVARIANTS 6, 7).
|
// Books just restored: whose they were (INVARIANTS 6, 7).
|
||||||
let marker = ledger_store::ops::ops_dir(dir).join(ledger_store::root::RESTORED_FROM);
|
let marker = ledger_store::ops::ops_dir(dir).join(ledger_store::root::RESTORED_FROM);
|
||||||
if let Ok(origin) = std::fs::read_to_string(&marker) {
|
if let Ok(origin) = std::fs::read_to_string(&marker) {
|
||||||
@@ -284,11 +406,182 @@ impl Backups {
|
|||||||
*e = hide(e, &self.dir);
|
*e = hide(e, &self.dir);
|
||||||
}
|
}
|
||||||
let mut log = self.log.lock().unwrap_or_else(|e| e.into_inner());
|
let mut log = self.log.lock().unwrap_or_else(|e| e.into_inner());
|
||||||
if let Err(e) = log.append(map) {
|
match log.append(map) {
|
||||||
eprintln!("wanderbooks server: the books' backup record couldn't be written: {e}");
|
Ok(_) | Err(ledger_store::chain::ChainError::Closed) => {}
|
||||||
|
Err(e) => {
|
||||||
|
eprintln!("wanderbooks server: the books' backup record couldn't be written: {e}");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Whether these backups were shut (INVARIANT 10).
|
||||||
|
fn is_shut(&self) -> bool {
|
||||||
|
self.shut.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A step begins: counted before the shut flag is looked at, and
|
||||||
|
/// `shut` sets the flag before it looks at the count, so a step either
|
||||||
|
/// sees them shut or is waited for, never neither (INVARIANT 10).
|
||||||
|
fn begin(&self) -> Result<Step, String> {
|
||||||
|
self.busy.steps.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let step = Step(self.busy.clone());
|
||||||
|
if self.is_shut() {
|
||||||
|
return Err(SHUT.to_string());
|
||||||
|
}
|
||||||
|
Ok(step)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// git, stopped by `shut`: the close's own last backup (INVARIANT 10).
|
||||||
|
fn git(&self) -> Result<Git, BackupError> {
|
||||||
|
Ok(Git::find()?
|
||||||
|
.with_cancel(self.shut.clone())
|
||||||
|
.with_lock_notes(self.locks.clone()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// git for a backup a call or a timer asked for: stopped as soon as a
|
||||||
|
/// close begins (INVARIANT 11), so it can't hold the close.
|
||||||
|
fn git_for(&self, why: &str) -> Result<Git, BackupError> {
|
||||||
|
if why == "close" {
|
||||||
|
self.git()
|
||||||
|
} else {
|
||||||
|
Ok(Git::find()?
|
||||||
|
.with_cancel(self.hurry.clone())
|
||||||
|
.with_lock_notes(self.locks.clone()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// git for a step a close hurries (a drill, a format upgrade): stopped
|
||||||
|
/// as soon as the close begins (INVARIANT 11).
|
||||||
|
fn hurried_git(&self) -> Result<Git, BackupError> {
|
||||||
|
let git = Git::find()?
|
||||||
|
.with_cancel(self.hurry.clone())
|
||||||
|
.with_lock_notes(self.locks.clone());
|
||||||
|
let ms = self.slow_ms.load(Ordering::SeqCst);
|
||||||
|
if ms == 0 {
|
||||||
|
return Ok(git);
|
||||||
|
}
|
||||||
|
let (hurry, paused) = (self.hurry.clone(), self.paused.clone());
|
||||||
|
Ok(git.with_phase_watch(Arc::new(move |phase: &str| {
|
||||||
|
// From the second phase on (the first is the clone, before
|
||||||
|
// there is anything of the step's own to see).
|
||||||
|
if phase == "clone" {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
paused.fetch_add(1, Ordering::SeqCst);
|
||||||
|
let by = std::time::Instant::now() + std::time::Duration::from_millis(ms);
|
||||||
|
while std::time::Instant::now() < by && !hurry.load(Ordering::SeqCst) {
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||||
|
}
|
||||||
|
})))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Make each phase of a drill or format upgrade wait `by` (a test
|
||||||
|
/// knob: a book large enough for these to take long).
|
||||||
|
pub(crate) fn slow_steps(&self, by: std::time::Duration) {
|
||||||
|
self.slow_ms.store(by.as_millis() as u64, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Install the test knob that holds a stoppable call as it begins.
|
||||||
|
pub(crate) fn set_hold(&self, hold: CallHold) {
|
||||||
|
*self.hold.lock().unwrap_or_else(|e| e.into_inner()) = Some(hold);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A call that a close can stop has begun (the test knob's seam).
|
||||||
|
pub(crate) fn hold(&self, call: &str) {
|
||||||
|
let hold = self.hold.lock().unwrap_or_else(|e| e.into_inner()).clone();
|
||||||
|
if let Some(hold) = hold {
|
||||||
|
hold(call);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// How many waits of the test knob have begun.
|
||||||
|
#[cfg(test)]
|
||||||
|
pub(crate) fn pauses_begun(&self) -> usize {
|
||||||
|
self.paused.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A close begins (INVARIANT 11): the steps it doesn't wait for stop at
|
||||||
|
/// their next look. The close's last backup, and what `shut` stops, are
|
||||||
|
/// not affected until `shut`.
|
||||||
|
pub fn hurry(&self) {
|
||||||
|
self.hurry.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hurried(&self) -> bool {
|
||||||
|
self.hurry.load(Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A lock a stopped git left, as it was dealt with: a record of the
|
||||||
|
/// backup (INVARIANT 12).
|
||||||
|
fn record_lock(&self, note: &backup::LockNote) {
|
||||||
|
let mut fields = json!({
|
||||||
|
"kind": if note.removed { "lock_removed" } else { "lock_left" },
|
||||||
|
"repo": note.repo, "lock": note.lock, "why": note.why,
|
||||||
|
});
|
||||||
|
// A lock left in the owner's folder is named by its whole path.
|
||||||
|
if let (Some(path), Value::Object(map)) = (¬e.path, &mut fields) {
|
||||||
|
map.insert("path".into(), json!(path));
|
||||||
|
}
|
||||||
|
self.record(fields);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Record the locks dealt with since the last look; the notes.
|
||||||
|
fn note_locks(&self) -> Vec<backup::LockNote> {
|
||||||
|
let notes = self.locks.take();
|
||||||
|
for note in ¬es {
|
||||||
|
self.record_lock(note);
|
||||||
|
}
|
||||||
|
notes
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shut these backups for good (INVARIANT 10): git stopped, every step
|
||||||
|
/// ended, the record closed. Call it after the last backup the books
|
||||||
|
/// will have, and before the books' store is let go.
|
||||||
|
pub async fn shut(&self) -> Vec<String> {
|
||||||
|
self.shut.store(true, Ordering::SeqCst);
|
||||||
|
self.hurry.store(true, Ordering::SeqCst);
|
||||||
|
// The run or drill holding the books' turn ends (its git was just
|
||||||
|
// stopped), and none begins after.
|
||||||
|
let _turn = self.running.lock().await;
|
||||||
|
loop {
|
||||||
|
let ended = self.busy.ended.notified();
|
||||||
|
if self.busy.steps.load(Ordering::SeqCst) == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
ended.await;
|
||||||
|
}
|
||||||
|
let notes = self.note_locks();
|
||||||
|
// A run whose future was dropped at its bound (a close's last
|
||||||
|
// backup) never recorded its push: a lock its stopped git left in the
|
||||||
|
// owner's folder is that target's failure all the same, named, in the
|
||||||
|
// standing the owner reads (ledger_store::backup INVARIANT 5b). Locks
|
||||||
|
// a run took in hand itself were recorded by it, and aren't here.
|
||||||
|
let left: Vec<&backup::LockNote> = notes
|
||||||
|
.iter()
|
||||||
|
.filter(|n| !n.removed && n.path.is_some())
|
||||||
|
.collect();
|
||||||
|
let mut said = Vec::new();
|
||||||
|
if !left.is_empty() {
|
||||||
|
for n in self.named().await {
|
||||||
|
let paths: Vec<&str> = left
|
||||||
|
.iter()
|
||||||
|
.filter(|l| l.repo == n.target.kind())
|
||||||
|
.filter_map(|l| l.path.as_deref())
|
||||||
|
.collect();
|
||||||
|
if !paths.is_empty() {
|
||||||
|
let error = BackupError::LockLeft(paths.join(", ")).to_string();
|
||||||
|
self.record(
|
||||||
|
json!({"kind": "push", "why": "close", "target": n.target.kind(),
|
||||||
|
"at": n.at, "key": n.key, "ok": false, "error": error}),
|
||||||
|
);
|
||||||
|
said.push(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.log.lock().unwrap_or_else(|e| e.into_inner()).close();
|
||||||
|
said
|
||||||
|
}
|
||||||
|
|
||||||
fn records(&self) -> Vec<Map<String, Value>> {
|
fn records(&self) -> Vec<Map<String, Value>> {
|
||||||
ledger_store::chain::read(
|
ledger_store::chain::read(
|
||||||
&ledger_store::ops::ops_dir(&self.dir).join(LOG_FILE),
|
&ledger_store::ops::ops_dir(&self.dir).join(LOG_FILE),
|
||||||
@@ -328,12 +621,6 @@ impl Backups {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Wait for any run or drill to end, and start none while the guard
|
|
||||||
/// lives: books being replaced by a restore push nothing more.
|
|
||||||
pub async fn pause(&self) -> tokio::sync::MutexGuard<'_, ()> {
|
|
||||||
self.running.lock().await
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The books' head now.
|
/// The books' head now.
|
||||||
pub async fn head(&self) -> Option<(u64, String)> {
|
pub async fn head(&self) -> Option<(u64, String)> {
|
||||||
let store = self.store.clone();
|
let store = self.store.clone();
|
||||||
@@ -354,12 +641,29 @@ impl Backups {
|
|||||||
/// says it is a new disk).
|
/// says it is a new disk).
|
||||||
pub async fn run_with(&self, why: &str, new_disk: bool) -> Result<Status, String> {
|
pub async fn run_with(&self, why: &str, new_disk: bool) -> Result<Status, String> {
|
||||||
let _one = self.running.lock().await;
|
let _one = self.running.lock().await;
|
||||||
|
// Books let go of (closed, or replaced by a restore) push nothing
|
||||||
|
// more, and leave no record of a run that never began.
|
||||||
|
if self.is_shut() {
|
||||||
|
return Err(SHUT.to_string());
|
||||||
|
}
|
||||||
|
if self.store.is_stopped() {
|
||||||
|
return Err(crate::server::STOPPED.to_string());
|
||||||
|
}
|
||||||
|
// A run a call or a timer asked for is stopped by a close
|
||||||
|
// (INVARIANT 11); the close's own last backup is not.
|
||||||
|
let stoppable = why != "close";
|
||||||
|
if stoppable && self.hurried() {
|
||||||
|
return Err(self.stopped_words(None));
|
||||||
|
}
|
||||||
if self.named().await.is_empty() {
|
if self.named().await.is_empty() {
|
||||||
return Ok(self.status().await);
|
return Ok(self.status().await);
|
||||||
}
|
}
|
||||||
|
let step = self.begin()?;
|
||||||
let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone());
|
let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone());
|
||||||
|
let git = self.git_for(why);
|
||||||
let made = tokio::task::spawn_blocking(move || {
|
let made = tokio::task::spawn_blocking(move || {
|
||||||
let git = Git::find()?;
|
let _step = step;
|
||||||
|
let git = git?;
|
||||||
// The stored files first, outside the lock: they never change.
|
// The stored files first, outside the lock: they never change.
|
||||||
// Only a head start (a file being written can trip it): the
|
// Only a head start (a file being written can trip it): the
|
||||||
// commit stages them all again.
|
// commit stages them all again.
|
||||||
@@ -375,12 +679,26 @@ impl Backups {
|
|||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap_or(Err(BackupError::Damaged("the backup stopped".into())));
|
.unwrap_or(Err(BackupError::Damaged("the backup stopped".into())));
|
||||||
|
let _ = self.note_locks();
|
||||||
let (made, named, head) = match made {
|
let (made, named, head) = match made {
|
||||||
Ok(m) => m,
|
Ok(m) => m,
|
||||||
|
// Stopped by a close: neither a success nor a failure of the
|
||||||
|
// backup, so nothing is said of any target (INVARIANT 11); what
|
||||||
|
// was committed before it stands in the archive, and the close
|
||||||
|
// makes its own last backup.
|
||||||
|
Err(BackupError::Cancelled(_)) if stoppable => {
|
||||||
|
self.record(json!({"kind": "stopped", "why": why, "during": "commit"}));
|
||||||
|
return Err(self.stopped_words(None));
|
||||||
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
let lock_left = matches!(e, BackupError::LockLeft(_));
|
||||||
let e = hide(&e.to_string(), &self.dir);
|
let e = hide(&e.to_string(), &self.dir);
|
||||||
self.record(json!({"kind": "commit", "why": why, "ok": false, "error": e}));
|
self.record(json!({"kind": "commit", "why": why, "ok": false, "error": e}));
|
||||||
return Err(e);
|
return Err(if stoppable && self.hurried() && lock_left {
|
||||||
|
self.stopped_words(Some(&e))
|
||||||
|
} else {
|
||||||
|
e
|
||||||
|
});
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
if let Some(m) = &made {
|
if let Some(m) = &made {
|
||||||
@@ -398,30 +716,62 @@ impl Backups {
|
|||||||
{
|
{
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if stoppable && self.hurried() {
|
||||||
|
self.record(json!({"kind": "stopped", "why": why, "during": "push"}));
|
||||||
|
return Err(self.stopped_words(None));
|
||||||
|
}
|
||||||
// Its repository is made only where it never took a backup.
|
// Its repository is made only where it never took a backup.
|
||||||
let may_create = new_disk || !held_before(&n.key, &records);
|
let may_create = new_disk || !held_before(&n.key, &records);
|
||||||
|
let step = self.begin()?;
|
||||||
|
let git = self.git_for(why);
|
||||||
let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone());
|
let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone());
|
||||||
let pushed = tokio::task::spawn_blocking(move || {
|
let pushed = tokio::task::spawn_blocking(move || {
|
||||||
let git = Git::find()?;
|
let _step = step;
|
||||||
backup::push(&git, &dir, &book, &t, may_create)
|
backup::push(&git?, &dir, &book, &t, may_create)
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap_or(Err(BackupError::Damaged("the push stopped".into())));
|
.unwrap_or(Err(BackupError::Damaged("the push stopped".into())));
|
||||||
|
let _ = self.note_locks();
|
||||||
match pushed {
|
match pushed {
|
||||||
Ok(commit) => self.record(
|
Ok(commit) => self.record(
|
||||||
json!({"kind": "push", "why": why, "target": n.target.kind(),
|
json!({"kind": "push", "why": why, "target": n.target.kind(),
|
||||||
"at": n.at, "key": n.key, "ok": true, "commit": commit,
|
"at": n.at, "key": n.key, "ok": true, "commit": commit,
|
||||||
"head": {"seq": head.0, "hash": head.1}}),
|
"head": {"seq": head.0, "hash": head.1}}),
|
||||||
),
|
),
|
||||||
Err(e) => self.record(
|
// Stopped by a close: not a failure of the target, and not
|
||||||
json!({"kind": "push", "why": why, "target": n.target.kind(),
|
// a success: said once, of the run (INVARIANT 11).
|
||||||
"at": n.at, "key": n.key, "ok": false, "error": e.to_string()}),
|
Err(BackupError::Cancelled(_)) if stoppable => {
|
||||||
),
|
self.record(json!({"kind": "stopped", "why": why, "during": "push",
|
||||||
|
"target": n.target.kind(), "key": n.key}));
|
||||||
|
return Err(self.stopped_words(None));
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
let lock_left = matches!(e, BackupError::LockLeft(_));
|
||||||
|
self.record(
|
||||||
|
json!({"kind": "push", "why": why, "target": n.target.kind(),
|
||||||
|
"at": n.at, "key": n.key, "ok": false, "error": e.to_string()}),
|
||||||
|
);
|
||||||
|
// A stop that left a lock is a failure the owner must
|
||||||
|
// hear of, and the call is told both.
|
||||||
|
if stoppable && self.hurried() && lock_left {
|
||||||
|
return Err(self.stopped_words(Some(&hide(&e.to_string(), &self.dir))));
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok(self.status().await)
|
Ok(self.status().await)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What a run a close stopped answers: that it was stopped because the
|
||||||
|
/// books are closing (the call's access record says so), and, if it left
|
||||||
|
/// a lock in the owner's folder, that too.
|
||||||
|
fn stopped_words(&self, also: Option<&str>) -> String {
|
||||||
|
match also {
|
||||||
|
None => crate::server::STOPPED_BY_CLOSE_WORDS.to_string(),
|
||||||
|
Some(more) => format!("{} Also: {more}", crate::server::STOPPED_BY_CLOSE_WORDS),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// The format upgrade, after a verified local backup with the keys
|
/// The format upgrade, after a verified local backup with the keys
|
||||||
/// (plan/served.md 3.9, D-39; INVARIANT 9). The caller has the owner's
|
/// (plan/served.md 3.9, D-39; INVARIANT 9). The caller has the owner's
|
||||||
/// go-ahead (the passphrase, checked by the server).
|
/// go-ahead (the passphrase, checked by the server).
|
||||||
@@ -437,8 +787,16 @@ impl Backups {
|
|||||||
/// the targets take them at the next backup, the books having moved.
|
/// the targets take them at the next backup, the books having moved.
|
||||||
pub async fn upgrade_format(&self) -> Result<Upgraded, String> {
|
pub async fn upgrade_format(&self) -> Result<Upgraded, String> {
|
||||||
let _one = self.running.lock().await;
|
let _one = self.running.lock().await;
|
||||||
|
// Books let go of, between the request's start and now, upgrade
|
||||||
|
// nothing and leave no record (a failure written through this
|
||||||
|
// handle would land in the book's record after it was opened
|
||||||
|
// again): INVARIANT 10.
|
||||||
|
let step = self.begin()?;
|
||||||
let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone());
|
let (store, dir, book) = (self.store.clone(), self.dir.clone(), self.book.clone());
|
||||||
|
let git_for_upgrade = self.hurried_git();
|
||||||
|
let cancel = self.hurry.clone();
|
||||||
let done = tokio::task::spawn_blocking(move || {
|
let done = tokio::task::spawn_blocking(move || {
|
||||||
|
let _step = step;
|
||||||
// Books that wait for nothing are left as they are: not even
|
// Books that wait for nothing are left as they are: not even
|
||||||
// their archive is made or staged (asked again under the lock
|
// their archive is made or staged (asked again under the lock
|
||||||
// below; only an upgrade moves the format, one at a time).
|
// below; only an upgrade moves the format, one at a time).
|
||||||
@@ -454,7 +812,7 @@ impl Backups {
|
|||||||
Err(why) => return Err(UpgradeFailed::stopped(why)),
|
Err(why) => return Err(UpgradeFailed::stopped(why)),
|
||||||
}
|
}
|
||||||
// Stored files staged ahead, outside the lock (as a backup's).
|
// Stored files staged ahead, outside the lock (as a backup's).
|
||||||
let git = Git::find();
|
let git = git_for_upgrade;
|
||||||
if let Ok(git) = &git {
|
if let Ok(git) = &git {
|
||||||
let _ = backup::stage_blobs(git, &dir);
|
let _ = backup::stage_blobs(git, &dir);
|
||||||
}
|
}
|
||||||
@@ -483,6 +841,16 @@ impl Backups {
|
|||||||
})
|
})
|
||||||
.map_err(|e| UpgradeFailed::proof(made.clone(), e))?;
|
.map_err(|e| UpgradeFailed::proof(made.clone(), e))?;
|
||||||
let commit = proven.commit;
|
let commit = proven.commit;
|
||||||
|
// The last look for a close (INVARIANT 11): once the
|
||||||
|
// `journal.format_set` line is appended the upgrade
|
||||||
|
// finishes, which is quick; before it, it is stopped,
|
||||||
|
// the books unchanged.
|
||||||
|
if cancel.load(Ordering::SeqCst) {
|
||||||
|
return Err(UpgradeFailed {
|
||||||
|
made: made.clone(),
|
||||||
|
why: "the books are closing: nothing was upgraded".into(),
|
||||||
|
});
|
||||||
|
}
|
||||||
let upgrade = match s.upgrade_format() {
|
let upgrade = match s.upgrade_format() {
|
||||||
Ok(upgrade) => upgrade,
|
Ok(upgrade) => upgrade,
|
||||||
// Journaled, and what follows the line failed (its
|
// Journaled, and what follows the line failed (its
|
||||||
@@ -514,6 +882,7 @@ impl Backups {
|
|||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap_or_else(|_| Err(UpgradeFailed::stopped("the upgrade stopped".into())));
|
.unwrap_or_else(|_| Err(UpgradeFailed::stopped("the upgrade stopped".into())));
|
||||||
|
let _ = self.note_locks();
|
||||||
match done {
|
match done {
|
||||||
Ok(u) => {
|
Ok(u) => {
|
||||||
if let (Some(b), Some(up)) = (&u.backup, &u.upgrade) {
|
if let (Some(b), Some(up)) = (&u.backup, &u.upgrade) {
|
||||||
@@ -547,28 +916,42 @@ impl Backups {
|
|||||||
|
|
||||||
/// Whether a drill is due (INVARIANT 5).
|
/// Whether a drill is due (INVARIANT 5).
|
||||||
pub async fn drill_due(&self) -> bool {
|
pub async fn drill_due(&self) -> bool {
|
||||||
|
// Through the store first: books let go name no target, and their
|
||||||
|
// record isn't read for a timer.
|
||||||
|
let named = self.named().await;
|
||||||
|
if named.is_empty() || self.is_shut() {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
let records = self.records();
|
let records = self.records();
|
||||||
let now = chrono::Utc::now();
|
let now = chrono::Utc::now();
|
||||||
self.named()
|
named.iter().any(|n| drill_due(&n.key, &records, now))
|
||||||
.await
|
|
||||||
.iter()
|
|
||||||
.any(|n| drill_due(&n.key, &records, now))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Drill each target whose drill is due (INVARIANT 5), each recorded.
|
/// Drill each target whose drill is due (INVARIANT 5), each recorded.
|
||||||
pub async fn drill(&self) {
|
pub async fn drill(&self) {
|
||||||
let _one = self.running.lock().await;
|
let _one = self.running.lock().await;
|
||||||
|
if self.is_shut() || self.store.is_stopped() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
let records = self.records();
|
let records = self.records();
|
||||||
let now = chrono::Utc::now();
|
let now = chrono::Utc::now();
|
||||||
for n in self.named().await {
|
for n in self.named().await {
|
||||||
if paused(&n.key, &records) || !drill_due(&n.key, &records, now) {
|
if paused(&n.key, &records) || !drill_due(&n.key, &records, now) {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
if self.hurried() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Ok(step) = self.begin() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
let git = self.hurried_git();
|
||||||
let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone());
|
let (dir, book, t) = (self.dir.clone(), self.book.clone(), n.target.clone());
|
||||||
let drilled = tokio::task::spawn_blocking(move || {
|
let drilled = tokio::task::spawn_blocking(move || {
|
||||||
|
let _step = step;
|
||||||
let scratch = ledger_store::ops::ops_dir(&dir).join(format!("drill-{}", t.kind()));
|
let scratch = ledger_store::ops::ops_dir(&dir).join(format!("drill-{}", t.kind()));
|
||||||
let _ = std::fs::remove_dir_all(&scratch);
|
let _ = std::fs::remove_dir_all(&scratch);
|
||||||
let git = Git::find()?;
|
let git = git?;
|
||||||
backup::drill(
|
backup::drill(
|
||||||
&git,
|
&git,
|
||||||
&t,
|
&t,
|
||||||
@@ -579,7 +962,12 @@ impl Backups {
|
|||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.unwrap_or(Err(BackupError::Damaged("the drill stopped".into())));
|
.unwrap_or(Err(BackupError::Damaged("the drill stopped".into())));
|
||||||
|
let _ = self.note_locks();
|
||||||
match drilled {
|
match drilled {
|
||||||
|
// Stopped by a close (INVARIANT 11): neither a pass nor a
|
||||||
|
// failure, so nothing is said of the target; the drill is
|
||||||
|
// due again when the books next open.
|
||||||
|
Err(BackupError::Cancelled(_)) => {}
|
||||||
Ok(head) => {
|
Ok(head) => {
|
||||||
self.record(json!({"kind": "drill", "target": n.target.kind(),
|
self.record(json!({"kind": "drill", "target": n.target.kind(),
|
||||||
"at": n.at, "key": n.key, "ok": true, "head": {"seq": head.0, "hash": head.1}}))
|
"at": n.at, "key": n.key, "ok": true, "head": {"seq": head.0, "hash": head.1}}))
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ pub mod opening;
|
|||||||
mod policy;
|
mod policy;
|
||||||
pub mod scopes;
|
pub mod scopes;
|
||||||
mod server;
|
mod server;
|
||||||
|
mod sessions;
|
||||||
mod settings;
|
mod settings;
|
||||||
mod tin_files;
|
mod tin_files;
|
||||||
mod types;
|
mod types;
|
||||||
|
|||||||
+2345
-179
File diff suppressed because it is too large.
Load diff
@@ -28,22 +28,12 @@ impl FuzzDoor {
|
|||||||
let home = tempfile::tempdir().expect("a folder");
|
let home = tempfile::tempdir().expect("a folder");
|
||||||
let (root, _) =
|
let (root, _) =
|
||||||
Root::setup(home.path(), Some(&home.path().join("root")), None).expect("a data root");
|
Root::setup(home.path(), Some(&home.path().join("root")), None).expect("a data root");
|
||||||
let books = Arc::new(Books {
|
let books = Arc::new(Books::new(
|
||||||
root,
|
root,
|
||||||
held: RwLock::new(BTreeMap::new()),
|
BACKUP_QUIET,
|
||||||
sessions: CancellationToken::new(),
|
DRILL_FIRST,
|
||||||
closing: CancellationToken::new(),
|
Isolation::SameUser,
|
||||||
in_flight: AtomicUsize::new(0),
|
));
|
||||||
finished: tokio::sync::Notify::new(),
|
|
||||||
last_arrival: std::sync::atomic::AtomicU64::new(0),
|
|
||||||
started: Instant::now(),
|
|
||||||
principals: RwLock::new(Err(String::new())),
|
|
||||||
session_tokens: Mutex::new(BTreeMap::new()),
|
|
||||||
backup_quiet: BACKUP_QUIET,
|
|
||||||
drill_first: DRILL_FIRST,
|
|
||||||
restoring: Mutex::new(()),
|
|
||||||
isolation: Isolation::SameUser,
|
|
||||||
});
|
|
||||||
let loaded = books.load_principals();
|
let loaded = books.load_principals();
|
||||||
*books.principals.write().unwrap() = loaded;
|
*books.principals.write().unwrap() = loaded;
|
||||||
match books.admin(Request::Create {
|
match books.admin(Request::Create {
|
||||||
|
|||||||
@@ -74,6 +74,8 @@ pub struct BooksServer {
|
|||||||
exports: ledger_store::exports::Exports,
|
exports: ledger_store::exports::Exports,
|
||||||
/// The books' backups (backup.rs).
|
/// The books' backups (backup.rs).
|
||||||
backups: Arc<crate::backup::Backups>,
|
backups: Arc<crate::backup::Backups>,
|
||||||
|
/// Who is connected, and what each is doing (sessions.rs).
|
||||||
|
board: Arc<crate::sessions::Board>,
|
||||||
/// How these books are kept from agents (plan 3.8, P9a): what
|
/// How these books are kept from agents (plan 3.8, P9a): what
|
||||||
/// `books.start` reports.
|
/// `books.start` reports.
|
||||||
isolation: Isolation,
|
isolation: Isolation,
|
||||||
@@ -128,6 +130,8 @@ pub(crate) struct Served {
|
|||||||
pub(crate) uploads: ledger_store::uploads::Uploads,
|
pub(crate) uploads: ledger_store::uploads::Uploads,
|
||||||
pub(crate) exports: ledger_store::exports::Exports,
|
pub(crate) exports: ledger_store::exports::Exports,
|
||||||
pub(crate) backups: Arc<crate::backup::Backups>,
|
pub(crate) backups: Arc<crate::backup::Backups>,
|
||||||
|
/// Its live sessions' board (sessions.rs), read by the admin socket.
|
||||||
|
pub(crate) board: Arc<crate::sessions::Board>,
|
||||||
pub(crate) isolation: Isolation,
|
pub(crate) isolation: Isolation,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -178,6 +182,7 @@ impl Served {
|
|||||||
uploads,
|
uploads,
|
||||||
exports,
|
exports,
|
||||||
backups,
|
backups,
|
||||||
|
board: Arc::default(),
|
||||||
isolation,
|
isolation,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
@@ -208,6 +213,11 @@ pub struct SharedStore {
|
|||||||
stopped: std::sync::atomic::AtomicBool,
|
stopped: std::sync::atomic::AtomicBool,
|
||||||
/// Closing: no new request runs (INVARIANT 3).
|
/// Closing: no new request runs (INVARIANT 3).
|
||||||
closing: std::sync::atomic::AtomicBool,
|
closing: std::sync::atomic::AtomicBool,
|
||||||
|
/// A close of these books has begun (`hurry`): a call that can run
|
||||||
|
/// long (a verification, a backup asked for, a package of every stored
|
||||||
|
/// file) stops at its next look, answering that it was stopped. Shared
|
||||||
|
/// with the books' backups (backup.rs), whose git it stops.
|
||||||
|
hurry: Arc<std::sync::atomic::AtomicBool>,
|
||||||
/// Requests running (from before their blocking task to its end).
|
/// Requests running (from before their blocking task to its end).
|
||||||
running: std::sync::atomic::AtomicUsize,
|
running: std::sync::atomic::AtomicUsize,
|
||||||
/// Woken whenever one ends.
|
/// Woken whenever one ends.
|
||||||
@@ -305,6 +315,7 @@ impl SharedStore {
|
|||||||
store: tokio::sync::Mutex::new(Some(store)),
|
store: tokio::sync::Mutex::new(Some(store)),
|
||||||
stopped: std::sync::atomic::AtomicBool::new(false),
|
stopped: std::sync::atomic::AtomicBool::new(false),
|
||||||
closing: std::sync::atomic::AtomicBool::new(false),
|
closing: std::sync::atomic::AtomicBool::new(false),
|
||||||
|
hurry: Arc::default(),
|
||||||
running: std::sync::atomic::AtomicUsize::new(0),
|
running: std::sync::atomic::AtomicUsize::new(0),
|
||||||
ended: tokio::sync::Notify::new(),
|
ended: tokio::sync::Notify::new(),
|
||||||
})
|
})
|
||||||
@@ -329,6 +340,23 @@ impl SharedStore {
|
|||||||
self.closing.load(std::sync::atomic::Ordering::SeqCst)
|
self.closing.load(std::sync::atomic::Ordering::SeqCst)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A close of these books begins: every call and job that can run long
|
||||||
|
/// stops at its next look (local.rs INVARIANT 10).
|
||||||
|
pub fn hurry(&self) {
|
||||||
|
self.hurry.store(true, std::sync::atomic::Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a close of these books has begun.
|
||||||
|
pub fn hurried(&self) -> bool {
|
||||||
|
self.hurry.load(std::sync::atomic::Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The stop flag itself, for what looks at it from another thread or
|
||||||
|
/// hands it to git (ledger_store `cancel`, `Git::with_cancel`).
|
||||||
|
pub fn hurry_flag(&self) -> Arc<std::sync::atomic::AtomicBool> {
|
||||||
|
self.hurry.clone()
|
||||||
|
}
|
||||||
|
|
||||||
fn stopped(&self) -> bool {
|
fn stopped(&self) -> bool {
|
||||||
self.stopped.load(std::sync::atomic::Ordering::SeqCst)
|
self.stopped.load(std::sync::atomic::Ordering::SeqCst)
|
||||||
}
|
}
|
||||||
@@ -352,6 +380,18 @@ impl SharedStore {
|
|||||||
|
|
||||||
/// What every request gets after an internal error (SharedStore
|
/// What every request gets after an internal error (SharedStore
|
||||||
/// INVARIANT 2).
|
/// INVARIANT 2).
|
||||||
|
/// What a call that a close stopped is told (local.rs INVARIANT 10): it
|
||||||
|
/// was stopped, because the books are closing, and nothing it was doing
|
||||||
|
/// is recorded as done.
|
||||||
|
pub(crate) const STOPPED_BY_CLOSE_WORDS: &str = "this call was stopped because the books are closing: nothing it was doing is recorded as done. Open the books again, then ask again";
|
||||||
|
|
||||||
|
/// The words of a call a close stopped, and the mark that its access record
|
||||||
|
/// says so (`refused: stopped_by_close`): returned as the call's error.
|
||||||
|
pub(crate) fn stopped_by_close() -> String {
|
||||||
|
STOPPED_BY_CLOSE.with(|s| s.set(true));
|
||||||
|
STOPPED_BY_CLOSE_WORDS.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) const STOPPED: &str = "the books server stopped taking requests after an internal error, to protect the books: ask the human to restart the books server (the books are checked again when it starts)";
|
pub(crate) const STOPPED: &str = "the books server stopped taking requests after an internal error, to protect the books: ask the human to restart the books server (the books are checked again when it starts)";
|
||||||
|
|
||||||
/// The store, locked for one stretch of synchronous work. Not `Send`, so
|
/// The store, locked for one stretch of synchronous work. Not `Send`, so
|
||||||
@@ -547,6 +587,7 @@ impl BooksServer {
|
|||||||
uploads: served.uploads.clone(),
|
uploads: served.uploads.clone(),
|
||||||
exports: served.exports.clone(),
|
exports: served.exports.clone(),
|
||||||
backups: served.backups.clone(),
|
backups: served.backups.clone(),
|
||||||
|
board: served.board.clone(),
|
||||||
isolation: served.isolation,
|
isolation: served.isolation,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1379,6 +1420,9 @@ thread_local! {
|
|||||||
/// The journal's head after the last write made by the request
|
/// The journal's head after the last write made by the request
|
||||||
/// running on this thread (StoreGuard's drop), for its access record.
|
/// running on this thread (StoreGuard's drop), for its access record.
|
||||||
static WROTE: std::cell::RefCell<Option<(u64, String)>> = const { std::cell::RefCell::new(None) };
|
static WROTE: std::cell::RefCell<Option<(u64, String)>> = const { std::cell::RefCell::new(None) };
|
||||||
|
/// Whether the request running on this thread was stopped by a close
|
||||||
|
/// (`stopped_by_close`), for its access record.
|
||||||
|
static STOPPED_BY_CLOSE: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
|
||||||
/// Who the request running on this thread is, as `books.start` shows
|
/// Who the request running on this thread is, as `books.start` shows
|
||||||
/// it: `{principal, kind, scopes, client_id}`. The token's own facts
|
/// it: `{principal, kind, scopes, client_id}`. The token's own facts
|
||||||
/// and the client's name; set at the start of the request.
|
/// and the client's name; set at the start of the request.
|
||||||
@@ -1744,7 +1788,7 @@ impl ServerHandler for BooksServer {
|
|||||||
) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
|
) -> Result<rmcp::model::CallToolResponse, rmcp::ErrorData> {
|
||||||
use crate::access::{self, Call};
|
use crate::access::{self, Call};
|
||||||
use ledger_store::access::Outcome;
|
use ledger_store::access::Outcome;
|
||||||
let mut call = Call::new(&self.access, &context, "tool", &request.name);
|
let mut call = Call::new(&self.access, &self.board, &context, "tool", &request.name);
|
||||||
let outcome_of = |out: &Result<rmcp::model::CallToolResponse, rmcp::ErrorData>| match out {
|
let outcome_of = |out: &Result<rmcp::model::CallToolResponse, rmcp::ErrorData>| match out {
|
||||||
Ok(rmcp::model::CallToolResponse::Complete(r)) if r.is_error != Some(true) => {
|
Ok(rmcp::model::CallToolResponse::Complete(r)) if r.is_error != Some(true) => {
|
||||||
Outcome::Ok
|
Outcome::Ok
|
||||||
@@ -1837,6 +1881,7 @@ impl ServerHandler for BooksServer {
|
|||||||
let result = run_blocking(&self.store, move || {
|
let result = run_blocking(&self.store, move || {
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
WROTE.with(|w| w.borrow_mut().take());
|
WROTE.with(|w| w.borrow_mut().take());
|
||||||
|
STOPPED_BY_CLOSE.with(|s| s.set(false));
|
||||||
ARGS.with(|a| *a.borrow_mut() = request.arguments.clone());
|
ARGS.with(|a| *a.borrow_mut() = request.arguments.clone());
|
||||||
let caller = running_call
|
let caller = running_call
|
||||||
.caller()
|
.caller()
|
||||||
@@ -1889,7 +1934,14 @@ impl ServerHandler for BooksServer {
|
|||||||
let mut c = running_call;
|
let mut c = running_call;
|
||||||
c.digested(digest);
|
c.digested(digest);
|
||||||
c.with_agent(AGENT_NOTE.with(|a| a.borrow_mut().take()));
|
c.with_agent(AGENT_NOTE.with(|a| a.borrow_mut().take()));
|
||||||
let recorded = c.record_blocking(outcome_of(&out), wrote);
|
// A call a close stopped is on record as stopped, not as an
|
||||||
|
// answer it gave (local.rs INVARIANT 10).
|
||||||
|
let outcome = if STOPPED_BY_CLOSE.with(|s| s.replace(false)) {
|
||||||
|
Outcome::Refused(access::STOPPED_BY_CLOSE.into())
|
||||||
|
} else {
|
||||||
|
outcome_of(&out)
|
||||||
|
};
|
||||||
|
let recorded = c.record_blocking(outcome, wrote);
|
||||||
(out, recorded)
|
(out, recorded)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -1944,6 +1996,23 @@ impl ServerHandler for BooksServer {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The client has said who it is: the session's board (sessions.rs)
|
||||||
|
/// knows it before the session's first call.
|
||||||
|
async fn on_initialized(&self, context: rmcp::service::NotificationContext<RoleServer>) {
|
||||||
|
if let (Some(sid), Some(info)) = (
|
||||||
|
crate::access::session_of(&context.extensions),
|
||||||
|
context.peer.peer_info(),
|
||||||
|
) {
|
||||||
|
self.board.initialized(
|
||||||
|
&sid,
|
||||||
|
ledger_store::access::Client {
|
||||||
|
name: info.client_info.name.clone(),
|
||||||
|
version: info.client_info.version.clone(),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
fn get_info(&self) -> ServerConfig {
|
fn get_info(&self) -> ServerConfig {
|
||||||
// A client connecting after a settings change sees the change
|
// A client connecting after a settings change sees the change
|
||||||
// (never waiting for the books here; a request holding them syncs
|
// (never waiting for the books here; a request holding them syncs
|
||||||
@@ -2011,7 +2080,13 @@ impl ServerHandler for BooksServer {
|
|||||||
use ledger_store::access::Outcome;
|
use ledger_store::access::Outcome;
|
||||||
// Reading a resource is reading the books: books:read, recorded
|
// Reading a resource is reading the books: books:read, recorded
|
||||||
// (access.rs).
|
// (access.rs).
|
||||||
let call = Call::new(&self.access, &context, "resource", &request.uri);
|
let call = Call::new(
|
||||||
|
&self.access,
|
||||||
|
&self.board,
|
||||||
|
&context,
|
||||||
|
"resource",
|
||||||
|
&request.uri,
|
||||||
|
);
|
||||||
let result = self.resource(request, &call).await;
|
let result = self.resource(request, &call).await;
|
||||||
{
|
{
|
||||||
let outcome = match &result {
|
let outcome = match &result {
|
||||||
|
|||||||
@@ -1454,6 +1454,7 @@ fn an_access_record_that_cant_be_written_stops_the_books_and_says_so() {
|
|||||||
let (server, _books) = unwritable("unrecorded-refusal");
|
let (server, _books) = unwritable("unrecorded-refusal");
|
||||||
let call = crate::access::Call::new(
|
let call = crate::access::Call::new(
|
||||||
&server.access,
|
&server.access,
|
||||||
|
&server.board,
|
||||||
&context(&s.peer, Some(ALL)),
|
&context(&s.peer, Some(ALL)),
|
||||||
"tool",
|
"tool",
|
||||||
"books.chart",
|
"books.chart",
|
||||||
|
|||||||
@@ -0,0 +1,224 @@
|
|||||||
|
//! Who is connected to a book right now: the in-memory board of one
|
||||||
|
//! book's live MCP sessions (plan/p15-app-and-relay.md 3.1, D-77).
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! GOAL: the app can say, for each open book, which assistants are
|
||||||
|
//! connected and what each is doing, without reading the access log
|
||||||
|
//! back and without ever holding a token.
|
||||||
|
//! SOURCE: plan/p15-app-and-relay.md 3.1 (the sessions request: client name
|
||||||
|
//! and version, the token's name, in-flight calls, the last tool
|
||||||
|
//! and when); D-77 (the app is the host); D-78 (one tab per
|
||||||
|
//! company: a connection names its company).
|
||||||
|
//! INVARIANTS:
|
||||||
|
//! 1. The board holds what the client and the agent SAID of themselves
|
||||||
|
//! (asserted, never checked), each masked of any full TIN and cut to
|
||||||
|
//! the access log's own limit (ledger_store::access::asserted); never
|
||||||
|
//! a token, its text or its hash.
|
||||||
|
//! 2. A call is counted as running from the moment it is made until its
|
||||||
|
//! blocking work and its record are done, even if its client hung
|
||||||
|
//! up (the count rides in the call, as the store's own does).
|
||||||
|
//! 3. A session that ended is not listed: the board is read only for
|
||||||
|
//! the sessions the server still binds (local.rs `session_tokens`),
|
||||||
|
//! and a note for another is dropped.
|
||||||
|
//! 4. Nothing here is durable: a restarted server knows no session, as
|
||||||
|
//! its clients know theirs ended.
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use ledger_store::access::{Agent, Client, Outcome, asserted};
|
||||||
|
use std::collections::HashMap;
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
|
||||||
|
/// What one session has said and done.
|
||||||
|
#[derive(Clone, Debug, Default)]
|
||||||
|
pub(crate) struct Note {
|
||||||
|
/// The client program, as it named itself at `initialize`.
|
||||||
|
pub client: Option<Client>,
|
||||||
|
/// What the agent said about itself, the latest time it did.
|
||||||
|
pub agent: Option<Agent>,
|
||||||
|
/// Calls running now (INVARIANT 2).
|
||||||
|
pub running: usize,
|
||||||
|
/// The last call that finished: its tool (or resource), what came of
|
||||||
|
/// it, and when (seconds since the epoch, UTC).
|
||||||
|
pub last: Option<Last>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A call that finished.
|
||||||
|
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||||
|
pub(crate) struct Last {
|
||||||
|
/// The tool's name, or the resource's address.
|
||||||
|
pub subject: String,
|
||||||
|
/// What came of it.
|
||||||
|
pub outcome: Outcome,
|
||||||
|
/// When (seconds since the epoch, UTC).
|
||||||
|
pub at: i64,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One book's live sessions' notes, by MCP session id.
|
||||||
|
#[derive(Default)]
|
||||||
|
pub(crate) struct Board {
|
||||||
|
notes: Mutex<HashMap<String, Note>>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A call running (INVARIANT 2): counted while it lives.
|
||||||
|
pub(crate) struct Live {
|
||||||
|
board: Arc<Board>,
|
||||||
|
sid: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Live {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let mut notes = self.board.notes();
|
||||||
|
if let Some(note) = notes.get_mut(&self.sid) {
|
||||||
|
note.running = note.running.saturating_sub(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn client_of(client: Client) -> Client {
|
||||||
|
Client {
|
||||||
|
name: asserted(&client.name),
|
||||||
|
version: asserted(&client.version),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn agent_of(agent: Agent) -> Agent {
|
||||||
|
Agent {
|
||||||
|
model: agent.model.as_deref().map(asserted),
|
||||||
|
reasoning_effort: agent.reasoning_effort.as_deref().map(asserted),
|
||||||
|
harness: agent.harness.as_deref().map(asserted),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Board {
|
||||||
|
fn notes(&self) -> std::sync::MutexGuard<'_, HashMap<String, Note>> {
|
||||||
|
self.notes.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session `sid` said who its client is (`initialize`).
|
||||||
|
pub fn initialized(&self, sid: &str, client: Client) {
|
||||||
|
self.notes().entry(sid.to_string()).or_default().client = Some(client_of(client));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A call of `sid` began (INVARIANT 2).
|
||||||
|
pub fn begin(self: &Arc<Self>, sid: &str) -> Live {
|
||||||
|
self.notes().entry(sid.to_string()).or_default().running += 1;
|
||||||
|
Live {
|
||||||
|
board: self.clone(),
|
||||||
|
sid: sid.to_string(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A call of `sid` is done and recorded: what it was, what came of
|
||||||
|
/// it, and what its client and agent said, if they did.
|
||||||
|
pub fn finished(
|
||||||
|
&self,
|
||||||
|
sid: &str,
|
||||||
|
subject: &str,
|
||||||
|
outcome: &Outcome,
|
||||||
|
client: Option<&Client>,
|
||||||
|
agent: Option<&Agent>,
|
||||||
|
at: i64,
|
||||||
|
) {
|
||||||
|
let mut notes = self.notes();
|
||||||
|
let note = notes.entry(sid.to_string()).or_default();
|
||||||
|
if let Some(client) = client {
|
||||||
|
note.client = Some(client_of(client.clone()));
|
||||||
|
}
|
||||||
|
if let Some(agent) = agent {
|
||||||
|
note.agent = Some(agent_of(agent.clone()));
|
||||||
|
}
|
||||||
|
note.last = Some(Last {
|
||||||
|
subject: asserted(subject),
|
||||||
|
outcome: outcome.clone(),
|
||||||
|
at,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The session `sid` ended.
|
||||||
|
pub fn forget(&self, sid: &str) {
|
||||||
|
self.notes().remove(sid);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The notes of the sessions `live` still names, and no other
|
||||||
|
/// (INVARIANT 3): the others are dropped.
|
||||||
|
pub fn snapshot(&self, live: &[String]) -> HashMap<String, Note> {
|
||||||
|
let mut notes = self.notes();
|
||||||
|
notes.retain(|sid, note| note.running > 0 || live.contains(sid));
|
||||||
|
live.iter()
|
||||||
|
.map(|sid| (sid.clone(), notes.get(sid).cloned().unwrap_or_default()))
|
||||||
|
.collect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn client(name: &str) -> Client {
|
||||||
|
Client {
|
||||||
|
name: name.into(),
|
||||||
|
version: "1.2".into(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_call_counts_as_running_until_its_guard_is_dropped() {
|
||||||
|
let board = Arc::new(Board::default());
|
||||||
|
let (a, b) = (board.begin("s1"), board.begin("s1"));
|
||||||
|
assert_eq!(board.snapshot(&["s1".into()])["s1"].running, 2);
|
||||||
|
drop(a);
|
||||||
|
assert_eq!(board.snapshot(&["s1".into()])["s1"].running, 1);
|
||||||
|
drop(b);
|
||||||
|
assert_eq!(board.snapshot(&["s1".into()])["s1"].running, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn the_last_call_and_what_the_client_said_are_kept_and_masked() {
|
||||||
|
let board = Board::default();
|
||||||
|
board.initialized("s1", client("Claude Code"));
|
||||||
|
board.finished(
|
||||||
|
"s1",
|
||||||
|
"books.chart",
|
||||||
|
&Outcome::Ok,
|
||||||
|
Some(&client("Claude Code 123-45-6789")),
|
||||||
|
Some(&Agent {
|
||||||
|
model: Some("m".into()),
|
||||||
|
reasoning_effort: None,
|
||||||
|
harness: Some("h".into()),
|
||||||
|
}),
|
||||||
|
100,
|
||||||
|
);
|
||||||
|
board.finished(
|
||||||
|
"s1",
|
||||||
|
"books.trial_balance",
|
||||||
|
&Outcome::Error,
|
||||||
|
None,
|
||||||
|
None,
|
||||||
|
200,
|
||||||
|
);
|
||||||
|
let note = &board.snapshot(&["s1".into()])["s1"];
|
||||||
|
let said = note.client.as_ref().unwrap();
|
||||||
|
assert!(!said.name.contains("6789"), "a TIN is masked: {said:?}");
|
||||||
|
assert_eq!(note.agent.as_ref().unwrap().model.as_deref(), Some("m"));
|
||||||
|
assert_eq!(
|
||||||
|
note.last,
|
||||||
|
Some(Last {
|
||||||
|
subject: "books.trial_balance".into(),
|
||||||
|
outcome: Outcome::Error,
|
||||||
|
at: 200
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn a_session_that_ended_is_not_listed_and_its_note_is_dropped() {
|
||||||
|
let board = Board::default();
|
||||||
|
board.initialized("gone", client("x"));
|
||||||
|
board.initialized("kept", client("y"));
|
||||||
|
let listed = board.snapshot(&["kept".into()]);
|
||||||
|
assert_eq!(listed.keys().collect::<Vec<_>>(), vec!["kept"]);
|
||||||
|
assert!(board.notes().get("gone").is_none());
|
||||||
|
board.forget("kept");
|
||||||
|
assert!(board.notes().is_empty());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -111,11 +111,15 @@ impl BooksServer {
|
|||||||
&self,
|
&self,
|
||||||
params: Parameters<BackUpNowParams>,
|
params: Parameters<BackUpNowParams>,
|
||||||
) -> Result<Json<BackupOut>, String> {
|
) -> Result<Json<BackupOut>, String> {
|
||||||
Ok(Json(
|
// Stopped by a close (backup.rs INVARIANT 11): said so, and on
|
||||||
self.backups
|
// record as stopped, not as an answer it gave.
|
||||||
.run_with("asked", params.0.new_disk)
|
match self.backups.run_with("asked", params.0.new_disk).await {
|
||||||
.await?
|
Ok(status) => Ok(Json(status.into())),
|
||||||
.into(),
|
Err(why) if why.starts_with(crate::server::STOPPED_BY_CLOSE_WORDS) => {
|
||||||
))
|
crate::server::stopped_by_close();
|
||||||
|
Err(why)
|
||||||
|
}
|
||||||
|
Err(why) => Err(why),
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -266,6 +266,16 @@ fn cash_flow_csv(stmt: &ledger_core::CashFlowStatement) -> String {
|
|||||||
csv
|
csv
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A store error as a call's answer: one that is a close's stop is said so,
|
||||||
|
/// and marks the call's access record (server.rs `stopped_by_close`).
|
||||||
|
fn stoppable(e: ledger_store::StoreError) -> String {
|
||||||
|
if matches!(e, ledger_store::StoreError::Cancelled) {
|
||||||
|
crate::server::stopped_by_close()
|
||||||
|
} else {
|
||||||
|
e.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[tool_router(router = reports_router, vis = "pub(super)")]
|
#[tool_router(router = reports_router, vis = "pub(super)")]
|
||||||
impl BooksServer {
|
impl BooksServer {
|
||||||
#[tool(
|
#[tool(
|
||||||
@@ -707,10 +717,16 @@ impl BooksServer {
|
|||||||
)
|
)
|
||||||
)]
|
)]
|
||||||
async fn verify(&self, params: Parameters<VerifyParams>) -> Result<Json<VerifyOut>, String> {
|
async fn verify(&self, params: Parameters<VerifyParams>) -> Result<Json<VerifyOut>, String> {
|
||||||
|
self.backups.hold("books.verify");
|
||||||
let mut store = self.lock()?;
|
let mut store = self.lock()?;
|
||||||
let report = store.verify_and_heal().map_err(|e| e.to_string())?;
|
// The replay and the hashing of every stored file are looked at
|
||||||
|
// once per journal line and per file: a close stops them
|
||||||
|
// (local.rs INVARIANT 10). Healing a drifted database is begun only
|
||||||
|
// if no stop was asked for before it, and then finishes.
|
||||||
|
let _stop = ledger_store::cancel::scope(self.store.hurry_flag());
|
||||||
|
let report = store.verify_and_heal().map_err(stoppable)?;
|
||||||
let blobs = if params.0.blobs {
|
let blobs = if params.0.blobs {
|
||||||
Some(store.verify_blobs().map_err(|e| e.to_string())?)
|
Some(store.verify_blobs().map_err(stoppable)?)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
@@ -1126,7 +1142,32 @@ impl BooksServer {
|
|||||||
/// 3. A locked vault or a missing TIN never fails the package: the
|
/// 3. A locked vault or a missing TIN never fails the package: the
|
||||||
/// row says why (vault_tin), the README lists it, and so does
|
/// row says why (vault_tin), the README lists it, and so does
|
||||||
/// tin_gaps (members, and 1099 payees that are reportable).
|
/// tin_gaps (members, and 1099 payees that are reportable).
|
||||||
/// 4. Read-only: nothing is journaled.
|
/// 4. Nothing is journaled but the decisions an override records (a
|
||||||
|
/// reason for exporting without an audit, a reason for exporting
|
||||||
|
/// with open drafts), and only once the package is certain to be
|
||||||
|
/// made. Every refusal that can be known from the books as they
|
||||||
|
/// stand is decided first: the two named ones (the audit, the open
|
||||||
|
/// drafts) and every one the build itself can make (a member's
|
||||||
|
/// unknown capital account, a report that can't be built), by
|
||||||
|
/// running the build once, read-only and in memory, before the
|
||||||
|
/// decision is journaled (without the stored files and the vault,
|
||||||
|
/// which a machine fails at, not the books). So a package refused
|
||||||
|
/// for what the books say journals nothing, on every retry. What
|
||||||
|
/// can still fail after a decision is journaled is only a failure
|
||||||
|
/// of the machine (the disk reading a stored file, memory, the
|
||||||
|
/// hand-over); the decision is then on record, with the reason in
|
||||||
|
/// the access log, and a later export that succeeds records its
|
||||||
|
/// own. The decisions stay ahead of the build because the
|
||||||
|
/// package describes the books it is made from, itself included:
|
||||||
|
/// its README and every report's footer carry the journal's event
|
||||||
|
/// count at the build (ledger_package::package, report_meta), which
|
||||||
|
/// counts the decisions. A close that has begun is looked for once,
|
||||||
|
/// immediately before the first decision is journaled: it refuses
|
||||||
|
/// then, journaling nothing. From the journaling to the hand-over
|
||||||
|
/// nothing looks at the close's stop (the build is no longer
|
||||||
|
/// stoppable, local.rs INVARIANT 10), so a decision on record is a
|
||||||
|
/// package handed over, unless the machine fails, which a close
|
||||||
|
/// cannot make it do.
|
||||||
/// ```
|
/// ```
|
||||||
#[tool(
|
#[tool(
|
||||||
name = "books.export_cpa_package",
|
name = "books.export_cpa_package",
|
||||||
@@ -1144,7 +1185,11 @@ impl BooksServer {
|
|||||||
) -> Result<Json<ExportCpaPackageOut>, String> {
|
) -> Result<Json<ExportCpaPackageOut>, String> {
|
||||||
let p = params.0;
|
let p = params.0;
|
||||||
let as_of = self.as_of(p.as_of.as_deref())?;
|
let as_of = self.as_of(p.as_of.as_deref())?;
|
||||||
|
self.backups.hold("books.export_cpa_package");
|
||||||
let mut store = self.lock()?;
|
let mut store = self.lock()?;
|
||||||
|
// The decisions an override records, journaled below only once every
|
||||||
|
// refusal has been decided (INVARIANT 4).
|
||||||
|
let mut decisions: Vec<ledger_core::conventions::NewDecision> = Vec::new();
|
||||||
// A package no counted audit stands behind is not final either
|
// A package no counted audit stands behind is not final either
|
||||||
// (plan P8, D-9): on books that declared `audits`, refused under
|
// (plan P8, D-9): on books that declared `audits`, refused under
|
||||||
// policy.cpa_package_requires_audit = refuse unless a reason is
|
// policy.cpa_package_requires_audit = refuse unless a reason is
|
||||||
@@ -1174,20 +1219,18 @@ impl BooksServer {
|
|||||||
let by = CALLER
|
let by = CALLER
|
||||||
.with(|c| c.borrow().as_ref().map(|(_, name)| name.clone()))
|
.with(|c| c.borrow().as_ref().map(|(_, name)| name.clone()))
|
||||||
.unwrap_or_else(|| ledger_store::auth::DEFAULT_NAME.to_string());
|
.unwrap_or_else(|| ledger_store::auth::DEFAULT_NAME.to_string());
|
||||||
store
|
decisions.push(ledger_core::conventions::NewDecision {
|
||||||
.record_decision(&ledger_core::conventions::NewDecision {
|
subject: format!("CPA package as of {as_of} without a counted audit"),
|
||||||
subject: format!("CPA package as of {as_of} without a counted audit"),
|
decision_md: format!(
|
||||||
decision_md: format!(
|
"The CPA package as of {as_of} was exported without an audit at the books' current head attested at the bar. Reason: {reason}"
|
||||||
"The CPA package as of {as_of} was exported without an audit at the books' current head attested at the bar. Reason: {reason}"
|
),
|
||||||
),
|
decided_by: vec![by],
|
||||||
decided_by: vec![by],
|
decided_on: today(),
|
||||||
decided_on: today(),
|
evidence_attachment: None,
|
||||||
evidence_attachment: None,
|
supersedes: None,
|
||||||
supersedes: None,
|
citation: None,
|
||||||
citation: None,
|
projects: Vec::new(),
|
||||||
projects: Vec::new(),
|
});
|
||||||
})
|
|
||||||
.map_err(|e| e.to_string())?;
|
|
||||||
} else {
|
} else {
|
||||||
audit_warning = Some(format!(
|
audit_warning = Some(format!(
|
||||||
"No counted audit stands behind this package: {why}."
|
"No counted audit stands behind this package: {why}."
|
||||||
@@ -1224,23 +1267,71 @@ impl BooksServer {
|
|||||||
let by = CALLER
|
let by = CALLER
|
||||||
.with(|c| c.borrow().as_ref().map(|(_, name)| name.clone()))
|
.with(|c| c.borrow().as_ref().map(|(_, name)| name.clone()))
|
||||||
.unwrap_or_else(|| ledger_store::auth::DEFAULT_NAME.to_string());
|
.unwrap_or_else(|| ledger_store::auth::DEFAULT_NAME.to_string());
|
||||||
store
|
decisions.push(ledger_core::conventions::NewDecision {
|
||||||
.record_decision(&ledger_core::conventions::NewDecision {
|
subject: format!("CPA package as of {as_of} with open drafts"),
|
||||||
subject: format!("CPA package as of {as_of} with open drafts"),
|
decision_md: format!(
|
||||||
decision_md: format!(
|
"The CPA package as of {as_of} was exported with {} draft(s) open: {}. Reason: {}",
|
||||||
"The CPA package as of {as_of} was exported with {} draft(s) open: {}. Reason: {}",
|
open_drafts.len(),
|
||||||
open_drafts.len(),
|
named.join("; "),
|
||||||
named.join("; "),
|
allow.reason.trim()
|
||||||
allow.reason.trim()
|
),
|
||||||
),
|
decided_by: vec![by],
|
||||||
decided_by: vec![by],
|
decided_on: today(),
|
||||||
decided_on: today(),
|
evidence_attachment: None,
|
||||||
evidence_attachment: None,
|
supersedes: None,
|
||||||
supersedes: None,
|
citation: None,
|
||||||
citation: None,
|
projects: Vec::new(),
|
||||||
projects: Vec::new(),
|
});
|
||||||
})
|
}
|
||||||
.map_err(|e| e.to_string())?;
|
// Every refusal the build can make from the books as they stand is
|
||||||
|
// decided before a decision goes on record (INVARIANT 4): the build
|
||||||
|
// is run once, in memory, to see that it will succeed. It is
|
||||||
|
// read-only (ledger_package INVARIANT 5: it takes the books by
|
||||||
|
// shared reference and writes nowhere, and it leaves its result to
|
||||||
|
// be dropped), so it changes nothing. It leaves out what only the
|
||||||
|
// machine can fail at: the stored files (include_receipts false) and
|
||||||
|
// the vault (no TIN source: a TIN it can't give never fails a
|
||||||
|
// package, ledger_package INVARIANT 3). A close that begins during
|
||||||
|
// it stops it, before anything is journaled.
|
||||||
|
if !decisions.is_empty() {
|
||||||
|
let _stop = ledger_store::cancel::scope(self.store.hurry_flag());
|
||||||
|
ledger_package::build_package(
|
||||||
|
&*store,
|
||||||
|
&package_settings(&self.settings()),
|
||||||
|
&ledger_package::PackageRequest {
|
||||||
|
as_of,
|
||||||
|
prepared_on: today(),
|
||||||
|
cash_accounts: &p.cash_accounts,
|
||||||
|
financing_accounts: &p.financing_accounts,
|
||||||
|
investing_accounts: &p.investing_accounts,
|
||||||
|
include_receipts: false,
|
||||||
|
tins: None,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.map_err(|e| {
|
||||||
|
if e == ledger_store::StoreError::Cancelled.to_string() {
|
||||||
|
crate::server::stopped_by_close()
|
||||||
|
} else {
|
||||||
|
e
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
}
|
||||||
|
// The decisions go on record now, ahead of the build (the package
|
||||||
|
// counts them: INVARIANT 4), and the close is looked for once more,
|
||||||
|
// immediately before the first: past it the package is made
|
||||||
|
// whatever a close does.
|
||||||
|
let journaled = !decisions.is_empty();
|
||||||
|
if journaled {
|
||||||
|
if self.store.hurried() {
|
||||||
|
return Err(crate::server::stopped_by_close());
|
||||||
|
}
|
||||||
|
for decision in &decisions {
|
||||||
|
store.record_decision(decision).map_err(|e| e.to_string())?;
|
||||||
|
}
|
||||||
|
// The test knob's seam (`--timer-hold`, `call:books.export_cpa_
|
||||||
|
// package:journaled`): a close that begins here must not stop
|
||||||
|
// the build.
|
||||||
|
self.backups.hold("books.export_cpa_package:journaled");
|
||||||
}
|
}
|
||||||
let book = book_name(&store);
|
let book = book_name(&store);
|
||||||
// The vault, opened once and never creating a key: locked, each
|
// The vault, opened once and never creating a key: locked, each
|
||||||
@@ -1251,7 +1342,13 @@ impl BooksServer {
|
|||||||
.as_ref()
|
.as_ref()
|
||||||
.map(|vault| move |id| vault_tin(ledger, vault, id));
|
.map(|vault| move |id| vault_tin(ledger, vault, id));
|
||||||
// Built from the books under the lock, written nowhere
|
// Built from the books under the lock, written nowhere
|
||||||
// (ledger_package INVARIANT 1).
|
// (ledger_package INVARIANT 1). Every stored file it holds is read
|
||||||
|
// one at a time, and a close stops it between two (local.rs
|
||||||
|
// INVARIANT 10).
|
||||||
|
// Not once a decision is journaled for it (INVARIANT 4): then it runs
|
||||||
|
// to the hand-over, which local.rs INVARIANT 10 names as a call a
|
||||||
|
// close does not stop.
|
||||||
|
let _stop = (!journaled).then(|| ledger_store::cancel::scope(self.store.hurry_flag()));
|
||||||
let package = ledger_package::build_package(
|
let package = ledger_package::build_package(
|
||||||
&*store,
|
&*store,
|
||||||
&package_settings(&self.settings()),
|
&package_settings(&self.settings()),
|
||||||
@@ -1264,7 +1361,15 @@ impl BooksServer {
|
|||||||
include_receipts: p.include_receipts,
|
include_receipts: p.include_receipts,
|
||||||
tins: tins.as_ref().map(|f| f as ledger_package::TinSource<'_>),
|
tins: tins.as_ref().map(|f| f as ledger_package::TinSource<'_>),
|
||||||
},
|
},
|
||||||
)?;
|
)
|
||||||
|
.map_err(|e| {
|
||||||
|
if e == ledger_store::StoreError::Cancelled.to_string() {
|
||||||
|
crate::server::stopped_by_close()
|
||||||
|
} else {
|
||||||
|
e
|
||||||
|
}
|
||||||
|
})?;
|
||||||
|
drop(_stop);
|
||||||
let vault_dir = if p.include_tins {
|
let vault_dir = if p.include_tins {
|
||||||
self.tin_record_dir(&store)?
|
self.tin_record_dir(&store)?
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -126,6 +126,8 @@ pub fn build_package<B: PackageBooks + ?Sized>(
|
|||||||
req: &PackageRequest<'_>,
|
req: &PackageRequest<'_>,
|
||||||
) -> Result<Package, String> {
|
) -> Result<Package, String> {
|
||||||
use ledger_import::{XlsxReport, report, report_to_xlsx, statement_pdf};
|
use ledger_import::{XlsxReport, report, report_to_xlsx, statement_pdf};
|
||||||
|
// A stop asked for before any of the work (the books server's close).
|
||||||
|
ledger_store::cancel::check().map_err(|e| e.to_string())?;
|
||||||
let company = settings.company;
|
let company = settings.company;
|
||||||
let (as_of, today) = (req.as_of, req.prepared_on);
|
let (as_of, today) = (req.as_of, req.prepared_on);
|
||||||
let meta = report_meta(company, req.prepared_on, books.journal_seq());
|
let meta = report_meta(company, req.prepared_on, books.journal_seq());
|
||||||
@@ -490,6 +492,10 @@ pub fn build_package<B: PackageBooks + ?Sized>(
|
|||||||
};
|
};
|
||||||
let mut index = String::from("entry_id,date,description,amount,file,sha256\n");
|
let mut index = String::from("entry_id,date,description,amount,file,sha256\n");
|
||||||
for a in books.all_attachments().map_err(|e| e.to_string())? {
|
for a in books.all_attachments().map_err(|e| e.to_string())? {
|
||||||
|
// A stop asked for (the books server's close) is looked at once
|
||||||
|
// per stored file read: a package of many files isn't held to
|
||||||
|
// its end by it (ledger_store::cancel).
|
||||||
|
ledger_store::cancel::check().map_err(|e| e.to_string())?;
|
||||||
if a.withdrawn_at.is_some() {
|
if a.withdrawn_at.is_some() {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,6 +19,12 @@
|
|||||||
//! name and version, a request id, the tool or resource it named)
|
//! name and version, a request id, the tool or resource it named)
|
||||||
//! has any full TIN masked and is then cut to 64 characters.
|
//! has any full TIN masked and is then cut to 64 characters.
|
||||||
//! 3. Records go in one at a time, in the order they are made.
|
//! 3. Records go in one at a time, in the order they are made.
|
||||||
|
//! 4. A log can be closed (`close`, under the lock every record goes in
|
||||||
|
//! under): a record whose append began before it is whole, one after
|
||||||
|
//! it is refused (`ChainError::Closed`), unwritten. So a record
|
||||||
|
//! still on its way when its book is let go (a refusal written late)
|
||||||
|
//! never reaches the file, nor, once the book is opened again, the
|
||||||
|
//! new log's chain.
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::chain::{self, ChainError, ChainLog, Head};
|
use crate::chain::{self, ChainError, ChainLog, Head};
|
||||||
@@ -220,6 +226,12 @@ impl AccessLog {
|
|||||||
log.append(fields).map(|(_, head)| head)
|
log.append(fields).map(|(_, head)| head)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Take no more records, ever (INVARIANT 4): waits for the record
|
||||||
|
/// being appended, if one is.
|
||||||
|
pub fn close(&self) {
|
||||||
|
self.log.lock().unwrap_or_else(|e| e.into_inner()).close();
|
||||||
|
}
|
||||||
|
|
||||||
/// Where the log ends now.
|
/// Where the log ends now.
|
||||||
pub fn head(&self) -> Head {
|
pub fn head(&self) -> Head {
|
||||||
self.log
|
self.log
|
||||||
@@ -289,6 +301,30 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A closed log takes no more records (INVARIANT 4): a handle kept from
|
||||||
|
/// before a close can't append after the log is opened again, which
|
||||||
|
/// would break the new log's chain.
|
||||||
|
#[test]
|
||||||
|
fn a_closed_log_writes_nothing_and_a_reopened_one_stays_whole() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let old = AccessLog::open(dir.path()).unwrap();
|
||||||
|
old.record(&access(1)).unwrap();
|
||||||
|
old.close();
|
||||||
|
let file = || std::fs::read(dir.path().join(ACCESS_FILE)).unwrap();
|
||||||
|
let at_close = file();
|
||||||
|
assert_eq!(old.record(&access(2)), Err(ChainError::Closed));
|
||||||
|
assert_eq!(file(), at_close, "a closed log wrote");
|
||||||
|
// The book is opened again: a new log, against its own head.
|
||||||
|
let new = AccessLog::open(dir.path()).unwrap();
|
||||||
|
new.record(&access(3)).unwrap();
|
||||||
|
// The old handle, used late, writes nothing.
|
||||||
|
assert_eq!(old.record(&access(4)), Err(ChainError::Closed));
|
||||||
|
new.record(&access(5)).unwrap();
|
||||||
|
let (back, head) = read(dir.path()).unwrap();
|
||||||
|
assert_eq!(back.len(), 3);
|
||||||
|
assert_eq!(head.seq, 3);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn records_read_back_as_written() {
|
fn records_read_back_as_written() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
+1526
-64
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,84 @@
|
|||||||
|
//! A stop request the long loops over a book's journal and files look at
|
||||||
|
//! (a backup's drill or proof, ledger-store `backup`): a step that has to
|
||||||
|
//! end when the books are let go (a close) can't wait for a replay of a
|
||||||
|
//! journal of any length to come to its end.
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! GOAL: a verification over a book's journal or files that was asked to
|
||||||
|
//! stop stops promptly, at its next step, and leaves nothing of its
|
||||||
|
//! own half-made, however large the book.
|
||||||
|
//! SOURCE: the books server's close (ledger-mcp local.rs INVARIANT 10 and
|
||||||
|
//! 13: a close is answered only when nothing of its backups still
|
||||||
|
//! runs, and is bounded).
|
||||||
|
//! INVARIANTS:
|
||||||
|
//! 1. A request is scoped to the thread that made it (`scope`), for as
|
||||||
|
//! long as the scope lives; code on other threads, and code outside a
|
||||||
|
//! scope, never sees one. Nothing is shared, so no other work of the
|
||||||
|
//! process can be stopped by it.
|
||||||
|
//! 2. `check` is looked at once per journal line (verifying, replaying,
|
||||||
|
//! applying to the projection), once per stored file hashed, and at
|
||||||
|
//! the boundaries between a verification's phases: the longest it
|
||||||
|
//! goes without looking is one line or one file.
|
||||||
|
//! 3. A stop is an error (`StoreError::Cancelled`), never a partial
|
||||||
|
//! success: what a stopped verification had made is the caller's to
|
||||||
|
//! remove (the books it was opened on are a scratch folder's).
|
||||||
|
//! 4. A step that can't be left half-made is shielded (`shielded`): the
|
||||||
|
//! stop is looked at before it begins, never inside it. The database's
|
||||||
|
//! rebuild from the journal (`verify_and_heal`, healing a drift) is
|
||||||
|
//! one: stopped part way it would leave the live ledger part replayed.
|
||||||
|
//! The look comes before ANYTHING is done for the heal (the database
|
||||||
|
//! copied aside included), so a stopped heal leaves nothing behind.
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use crate::error::StoreError;
|
||||||
|
use std::cell::RefCell;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
|
||||||
|
thread_local! {
|
||||||
|
static FLAG: RefCell<Option<Arc<AtomicBool>>> = const { RefCell::new(None) };
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A stop request in force on this thread, until dropped.
|
||||||
|
pub struct Scope(Option<Arc<AtomicBool>>);
|
||||||
|
|
||||||
|
impl Drop for Scope {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
FLAG.with(|f| *f.borrow_mut() = self.0.take());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Look for `flag` (INVARIANT 1) on this thread, until the returned scope
|
||||||
|
/// is dropped (the request in force before it comes back).
|
||||||
|
#[must_use]
|
||||||
|
pub fn scope(flag: Arc<AtomicBool>) -> Scope {
|
||||||
|
Scope(FLAG.with(|f| f.borrow_mut().replace(flag)))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Run `f` with no stop in force on this thread (the request in force
|
||||||
|
/// before comes back after): for the one step that can't be left half-made,
|
||||||
|
/// such as rebuilding the database from the journal, which would leave the
|
||||||
|
/// live ledger part replayed.
|
||||||
|
pub fn shielded<R>(f: impl FnOnce() -> R) -> R {
|
||||||
|
let outer = FLAG.with(|flag| flag.borrow_mut().take());
|
||||||
|
let _restore = Scope(outer);
|
||||||
|
f()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a stop was asked for.
|
||||||
|
pub fn requested() -> bool {
|
||||||
|
FLAG.with(|f| {
|
||||||
|
f.borrow()
|
||||||
|
.as_ref()
|
||||||
|
.is_some_and(|c| c.load(Ordering::SeqCst))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ok, or `StoreError::Cancelled` when a stop was asked for (INVARIANT 2).
|
||||||
|
pub fn check() -> Result<(), StoreError> {
|
||||||
|
if requested() {
|
||||||
|
Err(StoreError::Cancelled)
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,6 +28,11 @@
|
|||||||
//! 4. Only an unfinished last line (no newline: an append cut short by
|
//! 4. Only an unfinished last line (no newline: an append cut short by
|
||||||
//! a crash, never acknowledged) is set aside: open cuts it away,
|
//! a crash, never acknowledged) is set aside: open cuts it away,
|
||||||
//! read reports it.
|
//! read reports it.
|
||||||
|
//! 5. A log can be closed (`close`), and a closed log takes no more
|
||||||
|
//! appends, ever: a holder of it from before the book was let go can
|
||||||
|
//! never write after the book is opened again, when a new log is
|
||||||
|
//! opened on the file against its own head (an append from the old
|
||||||
|
//! handle would break the chain there).
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::journal::{canonical_json, sha256_hex};
|
use crate::journal::{canonical_json, sha256_hex};
|
||||||
@@ -60,6 +65,8 @@ pub enum ChainError {
|
|||||||
Io(std::io::ErrorKind),
|
Io(std::io::ErrorKind),
|
||||||
/// An earlier append failed: the log must be reopened (INVARIANT 2).
|
/// An earlier append failed: the log must be reopened (INVARIANT 2).
|
||||||
Broken,
|
Broken,
|
||||||
|
/// The log was closed: its book was let go (INVARIANT 5).
|
||||||
|
Closed,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Display for ChainError {
|
impl std::fmt::Display for ChainError {
|
||||||
@@ -68,6 +75,7 @@ impl std::fmt::Display for ChainError {
|
|||||||
ChainError::Damaged { line, why } => write!(f, "record {line} is damaged: {why}"),
|
ChainError::Damaged { line, why } => write!(f, "record {line} is damaged: {why}"),
|
||||||
ChainError::Io(kind) => write!(f, "the disk refused: {kind}"),
|
ChainError::Io(kind) => write!(f, "the disk refused: {kind}"),
|
||||||
ChainError::Broken => f.write_str("an earlier record couldn't be written"),
|
ChainError::Broken => f.write_str("an earlier record couldn't be written"),
|
||||||
|
ChainError::Closed => f.write_str("the log was closed: its books are not open"),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -168,6 +176,7 @@ pub struct ChainLog {
|
|||||||
file: File,
|
file: File,
|
||||||
head: Head,
|
head: Head,
|
||||||
broken: bool,
|
broken: bool,
|
||||||
|
closed: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl std::fmt::Debug for ChainLog {
|
impl std::fmt::Debug for ChainLog {
|
||||||
@@ -175,6 +184,7 @@ impl std::fmt::Debug for ChainLog {
|
|||||||
f.debug_struct("ChainLog")
|
f.debug_struct("ChainLog")
|
||||||
.field("head", &self.head)
|
.field("head", &self.head)
|
||||||
.field("broken", &self.broken)
|
.field("broken", &self.broken)
|
||||||
|
.field("closed", &self.closed)
|
||||||
.finish_non_exhaustive()
|
.finish_non_exhaustive()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -224,6 +234,7 @@ impl ChainLog {
|
|||||||
file,
|
file,
|
||||||
head: read.head,
|
head: read.head,
|
||||||
broken: false,
|
broken: false,
|
||||||
|
closed: false,
|
||||||
},
|
},
|
||||||
read.records,
|
read.records,
|
||||||
))
|
))
|
||||||
@@ -234,6 +245,11 @@ impl ChainLog {
|
|||||||
&self.head
|
&self.head
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Take no more appends, ever (INVARIANT 5).
|
||||||
|
pub fn close(&mut self) {
|
||||||
|
self.closed = true;
|
||||||
|
}
|
||||||
|
|
||||||
/// The log's file.
|
/// The log's file.
|
||||||
pub fn path(&self) -> &Path {
|
pub fn path(&self) -> &Path {
|
||||||
&self.path
|
&self.path
|
||||||
@@ -243,6 +259,9 @@ impl ChainLog {
|
|||||||
/// and `hash` (which `fields` must not hold). Returns the record as
|
/// and `hash` (which `fields` must not hold). Returns the record as
|
||||||
/// written and the new head (INVARIANT 2).
|
/// written and the new head (INVARIANT 2).
|
||||||
pub fn append(&mut self, fields: Map<String, Value>) -> Result<(Value, Head), ChainError> {
|
pub fn append(&mut self, fields: Map<String, Value>) -> Result<(Value, Head), ChainError> {
|
||||||
|
if self.closed {
|
||||||
|
return Err(ChainError::Closed);
|
||||||
|
}
|
||||||
if self.broken {
|
if self.broken {
|
||||||
return Err(ChainError::Broken);
|
return Err(ChainError::Broken);
|
||||||
}
|
}
|
||||||
@@ -600,6 +619,7 @@ mod tests {
|
|||||||
hash: genesis(G),
|
hash: genesis(G),
|
||||||
},
|
},
|
||||||
broken: false,
|
broken: false,
|
||||||
|
closed: false,
|
||||||
};
|
};
|
||||||
assert!(matches!(log.append(fields(1)), Err(ChainError::Io(_))));
|
assert!(matches!(log.append(fields(1)), Err(ChainError::Io(_))));
|
||||||
assert_eq!(log.head().seq, 0, "the head didn't move");
|
assert_eq!(log.head().seq, 0, "the head didn't move");
|
||||||
|
|||||||
@@ -5,6 +5,10 @@ use thiserror::Error;
|
|||||||
/// Every way a store operation can fail.
|
/// Every way a store operation can fail.
|
||||||
#[derive(Debug, Error)]
|
#[derive(Debug, Error)]
|
||||||
pub enum StoreError {
|
pub enum StoreError {
|
||||||
|
/// A verification was told to stop ([`crate::cancel`]): the books it
|
||||||
|
/// was reading are being let go.
|
||||||
|
#[error("stopped: the books are closing")]
|
||||||
|
Cancelled,
|
||||||
/// An attachment link names a subject that doesn't exist.
|
/// An attachment link names a subject that doesn't exist.
|
||||||
#[error("no {0} to link to")]
|
#[error("no {0} to link to")]
|
||||||
UnknownSubject(String),
|
UnknownSubject(String),
|
||||||
|
|||||||
@@ -21,6 +21,13 @@
|
|||||||
//! lapsed ones are swept when the books open, whenever one is made,
|
//! lapsed ones are swept when the books open, whenever one is made,
|
||||||
//! and by the server's sweeper. A token has at most MAX_LIVE.
|
//! and by the server's sweeper. A token has at most MAX_LIVE.
|
||||||
//! 4. No error names a path.
|
//! 4. No error names a path.
|
||||||
|
//! 5. Exports can be closed (`close`, under the lock every change to the
|
||||||
|
//! folder is made under): after it none is made, given or swept by
|
||||||
|
//! any holder of these exports from before, so a book let go is
|
||||||
|
//! never touched by a late request or a sweep, whoever has it open
|
||||||
|
//! by then. A fetch (`get`) reads under that lock: `close` waits for
|
||||||
|
//! one under way, so no byte of a closed book's folder is read for a
|
||||||
|
//! caller after `close` has returned.
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::journal::sha256_hex;
|
use crate::journal::sha256_hex;
|
||||||
@@ -87,8 +94,9 @@ impl From<std::io::Error> for ExportError {
|
|||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Exports {
|
pub struct Exports {
|
||||||
dir: PathBuf,
|
dir: PathBuf,
|
||||||
/// Held while exports are made or swept (INVARIANT 3).
|
/// Held while exports are made or swept (INVARIANT 3). True once
|
||||||
lock: std::sync::Arc<std::sync::Mutex<()>>,
|
/// closed (INVARIANT 5).
|
||||||
|
lock: std::sync::Arc<std::sync::Mutex<bool>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// `ex_` and 32 letters `a` to `p`, a letter a nibble (INVARIANT 1).
|
/// `ex_` and 32 letters `a` to `p`, a letter a nibble (INVARIANT 1).
|
||||||
@@ -132,10 +140,16 @@ impl Exports {
|
|||||||
Ok(exports)
|
Ok(exports)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn locked(&self) -> std::sync::MutexGuard<'_, ()> {
|
fn locked(&self) -> std::sync::MutexGuard<'_, bool> {
|
||||||
self.lock.lock().unwrap_or_else(|e| e.into_inner())
|
self.lock.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Change nothing in these exports, and give none, from now on
|
||||||
|
/// (INVARIANT 5): waits for the change being made, if one is.
|
||||||
|
pub fn close(&self) {
|
||||||
|
*self.locked() = true;
|
||||||
|
}
|
||||||
|
|
||||||
fn path(&self, id: &str, ext: &str) -> PathBuf {
|
fn path(&self, id: &str, ext: &str) -> PathBuf {
|
||||||
self.dir.join(format!("{id}.{ext}"))
|
self.dir.join(format!("{id}.{ext}"))
|
||||||
}
|
}
|
||||||
@@ -152,7 +166,10 @@ impl Exports {
|
|||||||
if let Some(why) = file_name_problem(file_name).or_else(|| mime_problem(mime)) {
|
if let Some(why) = file_name_problem(file_name).or_else(|| mime_problem(mime)) {
|
||||||
return Err(ExportError::Bad(why));
|
return Err(ExportError::Bad(why));
|
||||||
}
|
}
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
|
if *held {
|
||||||
|
return Err(ExportError::Bad("the books aren't open".into()));
|
||||||
|
}
|
||||||
self.sweep_held(now);
|
self.sweep_held(now);
|
||||||
if self.live_for(token, now) >= MAX_LIVE {
|
if self.live_for(token, now) >= MAX_LIVE {
|
||||||
return Err(ExportError::Bad(format!(
|
return Err(ExportError::Bad(format!(
|
||||||
@@ -196,6 +213,12 @@ impl Exports {
|
|||||||
return Err(ExportError::Unknown(id.chars().take(40).collect()));
|
return Err(ExportError::Unknown(id.chars().take(40).collect()));
|
||||||
}
|
}
|
||||||
let unknown = || ExportError::Unknown(id.to_string());
|
let unknown = || ExportError::Unknown(id.to_string());
|
||||||
|
// Read under the lock a close takes (INVARIANT 5): `close` waits
|
||||||
|
// for a fetch under way, and none begins after it.
|
||||||
|
let held = self.locked();
|
||||||
|
if *held {
|
||||||
|
return Err(ExportError::Bad("the books aren't open".into()));
|
||||||
|
}
|
||||||
let record = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?;
|
let record = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?;
|
||||||
let export: Export = serde_json::from_slice(&record).map_err(|_| unknown())?;
|
let export: Export = serde_json::from_slice(&record).map_err(|_| unknown())?;
|
||||||
if export.expires <= now {
|
if export.expires <= now {
|
||||||
@@ -205,6 +228,7 @@ impl Exports {
|
|||||||
return Err(ExportError::NotYours);
|
return Err(ExportError::NotYours);
|
||||||
}
|
}
|
||||||
let bytes = std::fs::read(self.path(id, "bin")).map_err(|_| unknown())?;
|
let bytes = std::fs::read(self.path(id, "bin")).map_err(|_| unknown())?;
|
||||||
|
drop(held);
|
||||||
if bytes.len() as u64 != export.size || sha256_hex(&bytes) != export.sha256 {
|
if bytes.len() as u64 != export.size || sha256_hex(&bytes) != export.sha256 {
|
||||||
return Err(ExportError::Damaged);
|
return Err(ExportError::Damaged);
|
||||||
}
|
}
|
||||||
@@ -228,8 +252,10 @@ impl Exports {
|
|||||||
/// Sweep away every export that lapsed by `now`, and anything left
|
/// Sweep away every export that lapsed by `now`, and anything left
|
||||||
/// without one (INVARIANT 3).
|
/// without one (INVARIANT 3).
|
||||||
pub fn sweep(&self, now: i64) {
|
pub fn sweep(&self, now: i64) {
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
self.sweep_held(now);
|
if !*held {
|
||||||
|
self.sweep_held(now);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn sweep_held(&self, now: i64) {
|
fn sweep_held(&self, now: i64) {
|
||||||
@@ -259,6 +285,99 @@ mod tests {
|
|||||||
|
|
||||||
const NOW: i64 = 1_800_000_000;
|
const NOW: i64 = 1_800_000_000;
|
||||||
|
|
||||||
|
/// Closed, exports are made, given and swept by no one (INVARIANT 5).
|
||||||
|
#[test]
|
||||||
|
fn closed_exports_change_nothing_and_give_nothing() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let x = Exports::open(dir.path(), NOW).unwrap();
|
||||||
|
let e = x.put("t", "a.csv", "text/csv", b"x", NOW).unwrap();
|
||||||
|
x.close();
|
||||||
|
let seen = || {
|
||||||
|
let mut names: Vec<_> = std::fs::read_dir(dir.path().join(EXPORTS_DIR))
|
||||||
|
.unwrap()
|
||||||
|
.map(|f| f.unwrap().file_name())
|
||||||
|
.collect();
|
||||||
|
names.sort();
|
||||||
|
names
|
||||||
|
};
|
||||||
|
let before = seen();
|
||||||
|
assert!(x.put("t", "b.csv", "text/csv", b"y", NOW).is_err());
|
||||||
|
assert!(x.get(&e.id, "t", NOW).is_err());
|
||||||
|
// A sweep long after everything lapsed removes nothing.
|
||||||
|
x.sweep(NOW + 10 * EXPORT_TTL);
|
||||||
|
assert_eq!(seen(), before);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// INVARIANT 5: a fetch reads under the lock a close takes, so a close
|
||||||
|
/// waits for the fetch under way instead of returning while bytes of
|
||||||
|
/// the folder are still being read for a caller. The fetch is held
|
||||||
|
/// inside its read (the export's file is a named pipe nothing writes
|
||||||
|
/// to yet), and `close` must not return until it is let go.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_close_waits_for_a_fetch_that_is_reading() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let x = Exports::open(dir.path(), NOW).unwrap();
|
||||||
|
let e = x.put("t", "a.csv", "text/csv", b"x", NOW).unwrap();
|
||||||
|
let bin = x.path(&e.id, "bin");
|
||||||
|
std::fs::remove_file(&bin).unwrap();
|
||||||
|
let made = std::process::Command::new("mkfifo").arg(&bin).status();
|
||||||
|
assert!(made.unwrap().success());
|
||||||
|
let fetching = {
|
||||||
|
let (x, id) = (x.clone(), e.id.clone());
|
||||||
|
std::thread::spawn(move || x.get(&id, "t", NOW))
|
||||||
|
};
|
||||||
|
// The fetch holds the lock, blocked opening the pipe for reading (no
|
||||||
|
// writer yet). A writer can be opened without blocking only once a
|
||||||
|
// reader has the pipe open, so that is the condition waited for (the
|
||||||
|
// writer, kept, is the one that lets the read end later).
|
||||||
|
use std::os::unix::fs::OpenOptionsExt;
|
||||||
|
let by = std::time::Instant::now() + std::time::Duration::from_secs(60);
|
||||||
|
let writer = loop {
|
||||||
|
match std::fs::OpenOptions::new()
|
||||||
|
.write(true)
|
||||||
|
.custom_flags(libc::O_NONBLOCK)
|
||||||
|
.open(&bin)
|
||||||
|
{
|
||||||
|
Ok(w) => break w,
|
||||||
|
Err(_) => {
|
||||||
|
assert!(
|
||||||
|
std::time::Instant::now() < by,
|
||||||
|
"the fetch never reached the pipe"
|
||||||
|
);
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
let (begun, started) = std::sync::mpsc::channel();
|
||||||
|
let (done, closed) = std::sync::mpsc::channel();
|
||||||
|
let closing = {
|
||||||
|
let x = x.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let _ = begun.send(());
|
||||||
|
x.close();
|
||||||
|
let _ = done.send(());
|
||||||
|
})
|
||||||
|
};
|
||||||
|
started.recv().unwrap();
|
||||||
|
// A negative window: it can only fail if the close returned, never
|
||||||
|
// because the machine was slow.
|
||||||
|
assert!(
|
||||||
|
closed
|
||||||
|
.recv_timeout(std::time::Duration::from_millis(500))
|
||||||
|
.is_err(),
|
||||||
|
"the close returned while a fetch was reading the folder"
|
||||||
|
);
|
||||||
|
// A writer that sends nothing lets the read end (an empty file,
|
||||||
|
// not the size kept: the fetch is refused).
|
||||||
|
drop(writer);
|
||||||
|
assert!(fetching.join().unwrap().is_err());
|
||||||
|
closed
|
||||||
|
.recv_timeout(std::time::Duration::from_secs(5))
|
||||||
|
.expect("the close returns once the fetch has ended");
|
||||||
|
closing.join().unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn an_export_is_kept_fifteen_minutes() {
|
fn an_export_is_kept_fifteen_minutes() {
|
||||||
// What its refusal tells the human: kept 15 minutes, then gone.
|
// What its refusal tells the human: kept 15 minutes, then gone.
|
||||||
|
|||||||
@@ -0,0 +1,554 @@
|
|||||||
|
//! The lock files a git leaves in a repository, found and (only where it
|
||||||
|
//! is ours to) removed through a directory handle (ledger-store `backup`
|
||||||
|
//! INVARIANT 5).
|
||||||
|
//!
|
||||||
|
//! ```text
|
||||||
|
//! GOAL: a lock file a stopped git left can be seen, and removed from the
|
||||||
|
//! one repository this program owns, without ever touching anything
|
||||||
|
//! a swapped folder or link points to.
|
||||||
|
//! SOURCE: the books server's close (ledger-mcp local.rs INVARIANT 10, 13:
|
||||||
|
//! a close is answered with no git of ours still working, and
|
||||||
|
//! leaves nothing a person must clean up); git's own lock files
|
||||||
|
//! (git-config, gitrepository-layout: `HEAD.lock`, `index.lock`,
|
||||||
|
//! `<ref>.lock`, `packed-refs.lock`, `shallow.lock`,
|
||||||
|
//! `config.lock`).
|
||||||
|
//! INVARIANTS:
|
||||||
|
//! 1. A repository is opened once (`RepoDir::open`, `open_in`): a
|
||||||
|
//! directory that is not a link, the folder it was found in kept as
|
||||||
|
//! the book's own. Every look and every removal after that goes
|
||||||
|
//! through that handle: the folders below it (`refs/`, and those
|
||||||
|
//! under it) are each opened from the one above with links refused,
|
||||||
|
//! so a folder swapped for a link, or the repository's own path swapped
|
||||||
|
//! for one, after the handle was opened, sends nothing anywhere: the
|
||||||
|
//! handle still names the folder that was opened.
|
||||||
|
//! 2. Only a regular file is ever removed (never a link, never a folder,
|
||||||
|
//! never a file whose type changed), and only one named as git names
|
||||||
|
//! its locks, in the places git puts them (`is_lock`). A name that
|
||||||
|
//! isn't one is refused.
|
||||||
|
//! 3. Where there is no directory handle to be had (not Unix) each step
|
||||||
|
//! looks at the path itself and refuses a link: the same rules,
|
||||||
|
//! without the guarantee against a swap in between. Nothing else
|
||||||
|
//! about the platform's behaviour is designed here.
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use std::io;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
use std::time::SystemTime;
|
||||||
|
|
||||||
|
/// Locks git makes in a repository's own folder.
|
||||||
|
const TOP: [&str; 5] = [
|
||||||
|
"HEAD.lock",
|
||||||
|
"index.lock",
|
||||||
|
"config.lock",
|
||||||
|
"packed-refs.lock",
|
||||||
|
"shallow.lock",
|
||||||
|
];
|
||||||
|
/// Locks git makes below it, outside `refs/`.
|
||||||
|
const BELOW: [&str; 2] = [
|
||||||
|
"objects/info/commit-graph.lock",
|
||||||
|
"objects/pack/multi-pack-index.lock",
|
||||||
|
];
|
||||||
|
/// How deep under `refs/` a lock is looked for.
|
||||||
|
const REFS_DEPTH: usize = 12;
|
||||||
|
|
||||||
|
/// Whether `rel` (a path in a repository, with `/` between its parts) is
|
||||||
|
/// named as git names a lock, in a place git puts one (INVARIANT 2).
|
||||||
|
pub fn is_lock(rel: &str) -> bool {
|
||||||
|
if TOP.contains(&rel) || BELOW.contains(&rel) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
let Some(under) = rel.strip_prefix("refs/") else {
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
let parts: Vec<&str> = under.split('/').collect();
|
||||||
|
parts.len() <= REFS_DEPTH
|
||||||
|
&& parts
|
||||||
|
.iter()
|
||||||
|
.all(|p| !p.is_empty() && *p != "." && *p != "..")
|
||||||
|
&& parts
|
||||||
|
.last()
|
||||||
|
.is_some_and(|name| name.len() > ".lock".len() && name.ends_with(".lock"))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A lock found: its path in the repository, and when it was last written.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct Found {
|
||||||
|
/// `index.lock`, `refs/heads/main.lock`.
|
||||||
|
pub lock: String,
|
||||||
|
/// Its modification time, when the system said.
|
||||||
|
pub modified: Option<SystemTime>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A repository's folder, opened once (INVARIANT 1).
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct RepoDir {
|
||||||
|
path: PathBuf,
|
||||||
|
inner: imp::Dir,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RepoDir {
|
||||||
|
/// The folder at `path`, which must not itself be a link.
|
||||||
|
pub fn open(path: &Path) -> io::Result<RepoDir> {
|
||||||
|
Ok(RepoDir {
|
||||||
|
path: path.to_path_buf(),
|
||||||
|
inner: imp::open(path)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The folder `name` inside the folder `parent` (the book's own folder
|
||||||
|
/// holding its archive): `name` must not be a link.
|
||||||
|
pub fn open_in(parent: &Path, name: &str) -> io::Result<RepoDir> {
|
||||||
|
Ok(RepoDir {
|
||||||
|
path: parent.join(name),
|
||||||
|
inner: imp::open_in(parent, name)?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The path it was opened by (for words, never for an operation).
|
||||||
|
pub fn path(&self) -> &Path {
|
||||||
|
&self.path
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The locks in it, sorted: regular files named as git names its locks.
|
||||||
|
pub fn locks(&self) -> Vec<Found> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
for rel in TOP.iter().chain(BELOW.iter()) {
|
||||||
|
if let Some(modified) = self.inner.regular(rel) {
|
||||||
|
out.push(Found {
|
||||||
|
lock: (*rel).to_string(),
|
||||||
|
modified,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self.inner.refs(&mut out, REFS_DEPTH);
|
||||||
|
out.sort_by(|a, b| a.lock.cmp(&b.lock));
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the lock `rel` (INVARIANTS 1, 2): Ok(true) if a regular file
|
||||||
|
/// of that name was removed, Ok(false) if there was none (or it was
|
||||||
|
/// not a regular file: nothing was done), Err if the name isn't a
|
||||||
|
/// lock's or the system refused.
|
||||||
|
pub fn remove(&self, rel: &str) -> io::Result<bool> {
|
||||||
|
if !is_lock(rel) {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
"not a name git gives a lock",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
self.inner.remove(rel)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(unix)]
|
||||||
|
mod imp {
|
||||||
|
use super::{Found, SystemTime};
|
||||||
|
use std::ffi::{CStr, CString, OsStr};
|
||||||
|
use std::io;
|
||||||
|
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd, RawFd};
|
||||||
|
use std::os::unix::ffi::OsStrExt;
|
||||||
|
use std::path::Path;
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Dir(OwnedFd);
|
||||||
|
|
||||||
|
const FLAGS: libc::c_int = libc::O_RDONLY | libc::O_DIRECTORY | libc::O_CLOEXEC;
|
||||||
|
|
||||||
|
fn c(text: &OsStr) -> io::Result<CString> {
|
||||||
|
CString::new(text.as_bytes())
|
||||||
|
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "a name with a NUL"))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn owned(fd: libc::c_int) -> io::Result<OwnedFd> {
|
||||||
|
if fd < 0 {
|
||||||
|
Err(io::Error::last_os_error())
|
||||||
|
} else {
|
||||||
|
// SAFETY: a file descriptor just returned by the system, owned
|
||||||
|
// by no one else.
|
||||||
|
Ok(unsafe { OwnedFd::from_raw_fd(fd) })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open(path: &Path) -> io::Result<Dir> {
|
||||||
|
let path = c(path.as_os_str())?;
|
||||||
|
// SAFETY: a NUL-ended path; the flags refuse a link at its end.
|
||||||
|
owned(unsafe { libc::open(path.as_ptr(), FLAGS | libc::O_NOFOLLOW) }).map(Dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open_in(parent: &Path, name: &str) -> io::Result<Dir> {
|
||||||
|
let parent = c(parent.as_os_str())?;
|
||||||
|
// SAFETY: as in `open`; the parent may be reached through links (it
|
||||||
|
// is the book's own folder), only `name` may not be one.
|
||||||
|
let parent = owned(unsafe { libc::open(parent.as_ptr(), FLAGS) })?;
|
||||||
|
sub(parent.as_raw_fd(), name).map(Dir)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The folder `name` of `dir`, a link refused.
|
||||||
|
fn sub(dir: RawFd, name: &str) -> io::Result<OwnedFd> {
|
||||||
|
let name = c(OsStr::new(name))?;
|
||||||
|
// SAFETY: `dir` is open for the call; the name is NUL-ended.
|
||||||
|
owned(unsafe { libc::openat(dir, name.as_ptr(), FLAGS | libc::O_NOFOLLOW) })
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `name` in `dir` as it is (a link is not followed): its stat.
|
||||||
|
fn stat(dir: RawFd, name: &str) -> io::Result<libc::stat> {
|
||||||
|
let name = c(OsStr::new(name))?;
|
||||||
|
// SAFETY: zeroed stat is a valid out-parameter; `dir` is open.
|
||||||
|
let mut st: libc::stat = unsafe { std::mem::zeroed() };
|
||||||
|
let found =
|
||||||
|
unsafe { libc::fstatat(dir, name.as_ptr(), &mut st, libc::AT_SYMLINK_NOFOLLOW) };
|
||||||
|
if found == 0 {
|
||||||
|
Ok(st)
|
||||||
|
} else {
|
||||||
|
Err(io::Error::last_os_error())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_regular(st: &libc::stat) -> bool {
|
||||||
|
(st.st_mode & libc::S_IFMT) == libc::S_IFREG
|
||||||
|
}
|
||||||
|
|
||||||
|
fn is_dir(st: &libc::stat) -> bool {
|
||||||
|
(st.st_mode & libc::S_IFMT) == libc::S_IFDIR
|
||||||
|
}
|
||||||
|
|
||||||
|
fn modified(st: &libc::stat) -> Option<SystemTime> {
|
||||||
|
let secs = u64::try_from(st.st_mtime).ok()?;
|
||||||
|
let nanos = u32::try_from(st.st_mtime_nsec).ok()?;
|
||||||
|
Some(SystemTime::UNIX_EPOCH + std::time::Duration::new(secs, nanos))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The names in the folder `dir` (a fresh look each time).
|
||||||
|
fn names(dir: RawFd) -> Vec<String> {
|
||||||
|
// SAFETY: a duplicate of an open descriptor, handed to fdopendir,
|
||||||
|
// which owns it from then on (closedir closes it).
|
||||||
|
let copy = unsafe { libc::dup(dir) };
|
||||||
|
if copy < 0 {
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
let stream = unsafe { libc::fdopendir(copy) };
|
||||||
|
if stream.is_null() {
|
||||||
|
// SAFETY: fdopendir didn't take it.
|
||||||
|
unsafe { libc::close(copy) };
|
||||||
|
return Vec::new();
|
||||||
|
}
|
||||||
|
let mut out = Vec::new();
|
||||||
|
// SAFETY: `stream` is a live directory stream until closedir; each
|
||||||
|
// entry's name is a NUL-ended string valid until the next readdir.
|
||||||
|
unsafe {
|
||||||
|
libc::rewinddir(stream);
|
||||||
|
loop {
|
||||||
|
let entry = libc::readdir(stream);
|
||||||
|
if entry.is_null() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let name = CStr::from_ptr((*entry).d_name.as_ptr());
|
||||||
|
if let Ok(name) = name.to_str()
|
||||||
|
&& name != "."
|
||||||
|
&& name != ".."
|
||||||
|
{
|
||||||
|
out.push(name.to_string());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
libc::closedir(stream);
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Dir {
|
||||||
|
/// The folder holding `rel`, opened step by step from this one
|
||||||
|
/// with a link refused at each, and `rel`'s last part.
|
||||||
|
fn parent_of<'a>(&self, rel: &'a str) -> io::Result<(OwnedFd, &'a str)> {
|
||||||
|
let mut parts: Vec<&str> = rel.split('/').collect();
|
||||||
|
let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?;
|
||||||
|
// SAFETY: a duplicate of the open descriptor, owned here.
|
||||||
|
let mut here = owned(unsafe { libc::dup(self.0.as_raw_fd()) })?;
|
||||||
|
for part in parts {
|
||||||
|
here = sub(here.as_raw_fd(), part)?;
|
||||||
|
}
|
||||||
|
Ok((here, last))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A regular file at `rel`: its modification time (when known).
|
||||||
|
pub fn regular(&self, rel: &str) -> Option<Option<SystemTime>> {
|
||||||
|
let (parent, name) = self.parent_of(rel).ok()?;
|
||||||
|
let st = stat(parent.as_raw_fd(), name).ok()?;
|
||||||
|
is_regular(&st).then(|| modified(&st))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The locks under `refs/`, in `out`.
|
||||||
|
pub fn refs(&self, out: &mut Vec<Found>, depth: usize) {
|
||||||
|
let Ok(refs) = sub(self.0.as_raw_fd(), "refs") else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
fn walk(dir: RawFd, prefix: &str, depth: usize, out: &mut Vec<Found>) {
|
||||||
|
for name in names(dir) {
|
||||||
|
let Ok(st) = stat(dir, &name) else { continue };
|
||||||
|
let rel = format!("{prefix}{name}");
|
||||||
|
if is_regular(&st) {
|
||||||
|
if super::is_lock(&rel) {
|
||||||
|
out.push(Found {
|
||||||
|
lock: rel,
|
||||||
|
modified: modified(&st),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else if is_dir(&st)
|
||||||
|
&& depth > 0
|
||||||
|
&& let Ok(inner) = sub(dir, &name)
|
||||||
|
{
|
||||||
|
walk(inner.as_raw_fd(), &format!("{rel}/"), depth - 1, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
walk(refs.as_raw_fd(), "refs/", depth, out);
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(&self, rel: &str) -> io::Result<bool> {
|
||||||
|
let (parent, name) = match self.parent_of(rel) {
|
||||||
|
Ok(found) => found,
|
||||||
|
// A folder that isn't there (or is a link): nothing to remove.
|
||||||
|
Err(_) => return Ok(false),
|
||||||
|
};
|
||||||
|
match stat(parent.as_raw_fd(), name) {
|
||||||
|
Ok(st) if is_regular(&st) => {}
|
||||||
|
_ => return Ok(false),
|
||||||
|
}
|
||||||
|
let name = c(OsStr::new(name))?;
|
||||||
|
// SAFETY: the parent is open; the name is NUL-ended and relative
|
||||||
|
// to it, and names a regular file just looked at.
|
||||||
|
let removed = unsafe { libc::unlinkat(parent.as_raw_fd(), name.as_ptr(), 0) };
|
||||||
|
if removed == 0 {
|
||||||
|
Ok(true)
|
||||||
|
} else {
|
||||||
|
let e = io::Error::last_os_error();
|
||||||
|
if e.kind() == io::ErrorKind::NotFound {
|
||||||
|
Ok(false)
|
||||||
|
} else {
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(unix))]
|
||||||
|
mod imp {
|
||||||
|
use super::{Found, SystemTime};
|
||||||
|
use std::io;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct Dir(PathBuf);
|
||||||
|
|
||||||
|
fn plain(path: &Path) -> io::Result<()> {
|
||||||
|
let meta = std::fs::symlink_metadata(path)?;
|
||||||
|
if meta.file_type().is_symlink() || !meta.is_dir() {
|
||||||
|
return Err(io::Error::new(
|
||||||
|
io::ErrorKind::InvalidInput,
|
||||||
|
"not a plain folder",
|
||||||
|
));
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open(path: &Path) -> io::Result<Dir> {
|
||||||
|
plain(path)?;
|
||||||
|
Ok(Dir(path.to_path_buf()))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn open_in(parent: &Path, name: &str) -> io::Result<Dir> {
|
||||||
|
open(&parent.join(name))
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Dir {
|
||||||
|
fn at(&self, rel: &str) -> io::Result<PathBuf> {
|
||||||
|
let mut path = self.0.clone();
|
||||||
|
let mut parts: Vec<&str> = rel.split('/').collect();
|
||||||
|
let last = parts.pop().ok_or(io::ErrorKind::InvalidInput)?;
|
||||||
|
for part in parts {
|
||||||
|
path.push(part);
|
||||||
|
plain(&path)?;
|
||||||
|
}
|
||||||
|
path.push(last);
|
||||||
|
Ok(path)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn regular(&self, rel: &str) -> Option<Option<SystemTime>> {
|
||||||
|
let path = self.at(rel).ok()?;
|
||||||
|
let meta = std::fs::symlink_metadata(path).ok()?;
|
||||||
|
meta.file_type().is_file().then(|| meta.modified().ok())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn refs(&self, out: &mut Vec<Found>, depth: usize) {
|
||||||
|
fn walk(dir: &Path, prefix: &str, depth: usize, out: &mut Vec<Found>) {
|
||||||
|
let Ok(entries) = std::fs::read_dir(dir) else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
for e in entries.flatten() {
|
||||||
|
let Ok(meta) = std::fs::symlink_metadata(e.path()) else {
|
||||||
|
continue;
|
||||||
|
};
|
||||||
|
let rel = format!("{prefix}{}", e.file_name().to_string_lossy());
|
||||||
|
if meta.file_type().is_file() {
|
||||||
|
if super::is_lock(&rel) {
|
||||||
|
out.push(Found {
|
||||||
|
lock: rel,
|
||||||
|
modified: meta.modified().ok(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else if meta.is_dir() && !meta.file_type().is_symlink() && depth > 0 {
|
||||||
|
walk(&e.path(), &format!("{rel}/"), depth - 1, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let refs = self.0.join("refs");
|
||||||
|
if plain(&refs).is_ok() {
|
||||||
|
walk(&refs, "refs/", depth, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn remove(&self, rel: &str) -> io::Result<bool> {
|
||||||
|
let Ok(path) = self.at(rel) else {
|
||||||
|
return Ok(false);
|
||||||
|
};
|
||||||
|
match std::fs::symlink_metadata(&path) {
|
||||||
|
Ok(meta) if meta.file_type().is_file() => std::fs::remove_file(path).map(|()| true),
|
||||||
|
_ => Ok(false),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn repo(dir: &Path) -> PathBuf {
|
||||||
|
let repo = dir.join("repo.git");
|
||||||
|
std::fs::create_dir_all(repo.join("refs/heads")).unwrap();
|
||||||
|
std::fs::create_dir_all(repo.join("objects/pack")).unwrap();
|
||||||
|
std::fs::create_dir_all(repo.join("objects/info")).unwrap();
|
||||||
|
repo
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn only_the_names_git_gives_its_locks_are_locks() {
|
||||||
|
for yes in [
|
||||||
|
"HEAD.lock",
|
||||||
|
"index.lock",
|
||||||
|
"config.lock",
|
||||||
|
"packed-refs.lock",
|
||||||
|
"shallow.lock",
|
||||||
|
"refs/heads/main.lock",
|
||||||
|
"refs/heads/feature/x.lock",
|
||||||
|
"refs/tags/v1.lock",
|
||||||
|
"objects/info/commit-graph.lock",
|
||||||
|
"objects/pack/multi-pack-index.lock",
|
||||||
|
] {
|
||||||
|
assert!(is_lock(yes), "{yes}");
|
||||||
|
}
|
||||||
|
for no in [
|
||||||
|
"",
|
||||||
|
".lock",
|
||||||
|
"refs/.lock",
|
||||||
|
"refs/heads/",
|
||||||
|
"refs/heads/main",
|
||||||
|
"refs/heads/../../x.lock",
|
||||||
|
"refs//x.lock",
|
||||||
|
"refs/heads/./x.lock",
|
||||||
|
"other.lock",
|
||||||
|
"objects/pack/pack-1.pack",
|
||||||
|
"objects/other.lock",
|
||||||
|
"../index.lock",
|
||||||
|
"/etc/x.lock",
|
||||||
|
"hooks/pre-commit.lock",
|
||||||
|
"refs",
|
||||||
|
] {
|
||||||
|
assert!(!is_lock(no), "{no:?}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn locks_are_found_and_only_regular_files_are_removed() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let repo = repo(dir.path());
|
||||||
|
std::fs::write(repo.join("index.lock"), b"").unwrap();
|
||||||
|
std::fs::write(repo.join("refs/heads/main.lock"), b"").unwrap();
|
||||||
|
// Named like locks, but not files: neither is listed nor removed.
|
||||||
|
std::fs::create_dir(repo.join("HEAD.lock")).unwrap();
|
||||||
|
std::fs::write(dir.path().join("elsewhere"), b"").unwrap();
|
||||||
|
#[cfg(unix)]
|
||||||
|
std::os::unix::fs::symlink(dir.path().join("elsewhere"), repo.join("config.lock")).unwrap();
|
||||||
|
// Not a lock's name.
|
||||||
|
std::fs::write(repo.join("refs/heads/main"), b"").unwrap();
|
||||||
|
let handle = RepoDir::open(&repo).unwrap();
|
||||||
|
let found: Vec<String> = handle.locks().into_iter().map(|f| f.lock).collect();
|
||||||
|
assert_eq!(found, ["index.lock", "refs/heads/main.lock"]);
|
||||||
|
assert!(handle.locks().iter().all(|f| f.modified.is_some()));
|
||||||
|
assert!(handle.remove("index.lock").unwrap());
|
||||||
|
assert!(!handle.remove("index.lock").unwrap(), "already gone");
|
||||||
|
assert!(!handle.remove("HEAD.lock").unwrap(), "a folder stays");
|
||||||
|
assert!(repo.join("HEAD.lock").is_dir());
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
assert!(!handle.remove("config.lock").unwrap(), "a link stays");
|
||||||
|
assert!(repo.join("config.lock").is_symlink());
|
||||||
|
assert!(dir.path().join("elsewhere").exists());
|
||||||
|
}
|
||||||
|
assert!(handle.remove("refs/heads/main").is_err(), "not a lock");
|
||||||
|
assert!(repo.join("refs/heads/main").exists());
|
||||||
|
assert!(handle.remove("../elsewhere.lock").is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// INVARIANT 1: a folder (or the repository's own path) swapped for a
|
||||||
|
/// link after the handle was opened sends nothing anywhere.
|
||||||
|
#[cfg(unix)]
|
||||||
|
#[test]
|
||||||
|
fn a_folder_swapped_for_a_link_after_the_handle_was_opened_touches_nothing_outside() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let outside = dir.path().join("outside");
|
||||||
|
std::fs::create_dir_all(outside.join("refs/heads")).unwrap();
|
||||||
|
for lock in ["index.lock", "HEAD.lock", "refs/heads/main.lock"] {
|
||||||
|
std::fs::write(outside.join(lock), b"theirs").unwrap();
|
||||||
|
}
|
||||||
|
// `refs` swapped for a link to a folder holding a lock of that name.
|
||||||
|
let repo_path = repo(dir.path());
|
||||||
|
std::fs::write(repo_path.join("refs/heads/main.lock"), b"ours").unwrap();
|
||||||
|
let handle = RepoDir::open(&repo_path).unwrap();
|
||||||
|
std::fs::rename(repo_path.join("refs"), dir.path().join("refs-moved")).unwrap();
|
||||||
|
std::os::unix::fs::symlink(outside.join("refs"), repo_path.join("refs")).unwrap();
|
||||||
|
assert!(!handle.remove("refs/heads/main.lock").unwrap());
|
||||||
|
assert!(handle.locks().is_empty(), "a link is not looked through");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(outside.join("refs/heads/main.lock")).unwrap(),
|
||||||
|
b"theirs"
|
||||||
|
);
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(dir.path().join("refs-moved/heads/main.lock")).unwrap(),
|
||||||
|
b"ours",
|
||||||
|
"nor was the folder it moved to touched through the link"
|
||||||
|
);
|
||||||
|
// The repository's own path swapped for a link: the handle still
|
||||||
|
// names the folder it opened (moved aside), and the link's target
|
||||||
|
// is never touched.
|
||||||
|
let second = dir.path().join("second.git");
|
||||||
|
std::fs::create_dir_all(second.join("refs")).unwrap();
|
||||||
|
std::fs::write(second.join("index.lock"), b"ours").unwrap();
|
||||||
|
let handle = RepoDir::open(&second).unwrap();
|
||||||
|
std::fs::rename(&second, dir.path().join("second-moved.git")).unwrap();
|
||||||
|
std::os::unix::fs::symlink(&outside, &second).unwrap();
|
||||||
|
assert!(handle.remove("index.lock").unwrap());
|
||||||
|
assert!(!dir.path().join("second-moved.git/index.lock").exists());
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(outside.join("index.lock")).unwrap(),
|
||||||
|
b"theirs",
|
||||||
|
"the link's target was touched"
|
||||||
|
);
|
||||||
|
assert_eq!(std::fs::read(outside.join("HEAD.lock")).unwrap(), b"theirs");
|
||||||
|
// And a repository that is a link when the handle is opened is
|
||||||
|
// refused, with the archive's own `open_in` too.
|
||||||
|
assert!(RepoDir::open(&second).is_err());
|
||||||
|
assert!(RepoDir::open_in(dir.path(), "second.git").is_err());
|
||||||
|
assert!(RepoDir::open_in(dir.path(), "second-moved.git").is_ok());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -317,6 +317,7 @@ fn verify_lines(
|
|||||||
let mut expected_prev = GENESIS_PREV.to_string();
|
let mut expected_prev = GENESIS_PREV.to_string();
|
||||||
let mut raws = body.split(|&b| b == b'\n').enumerate().peekable();
|
let mut raws = body.split(|&b| b == b'\n').enumerate().peekable();
|
||||||
while let Some((i, raw)) = raws.next() {
|
while let Some((i, raw)) = raws.next() {
|
||||||
|
crate::cancel::check()?;
|
||||||
let read = read_line(raw).map_err(|e| {
|
let read = read_line(raw).map_err(|e| {
|
||||||
StoreError::JournalCorrupt(format!("seq {}: unparseable line: {e}", i + 1))
|
StoreError::JournalCorrupt(format!("seq {}: unparseable line: {e}", i + 1))
|
||||||
})?;
|
})?;
|
||||||
|
|||||||
@@ -22,12 +22,14 @@ pub mod access;
|
|||||||
pub mod auth;
|
pub mod auth;
|
||||||
pub mod backup;
|
pub mod backup;
|
||||||
pub mod blob;
|
pub mod blob;
|
||||||
|
pub mod cancel;
|
||||||
pub mod chain;
|
pub mod chain;
|
||||||
pub mod describe;
|
pub mod describe;
|
||||||
pub mod error;
|
pub mod error;
|
||||||
pub mod exports;
|
pub mod exports;
|
||||||
pub mod form1099;
|
pub mod form1099;
|
||||||
pub mod format;
|
pub mod format;
|
||||||
|
pub mod git_locks;
|
||||||
pub mod journal;
|
pub mod journal;
|
||||||
pub mod lock;
|
pub mod lock;
|
||||||
pub mod meta;
|
pub mod meta;
|
||||||
|
|||||||
+380
-69
@@ -29,7 +29,16 @@
|
|||||||
//! file if the source never had one), and a new book appears in the
|
//! file if the source never had one), and a new book appears in the
|
||||||
//! root only whole: every stored file re-hashed against its name,
|
//! root only whole: every stored file re-hashed against its name,
|
||||||
//! every file the books name present, verified end to end, synced to
|
//! every file the books name present, verified end to end, synced to
|
||||||
//! disk, and its head equal to the source's.
|
//! disk, and its head equal to the source's. The original is left as it
|
||||||
|
//! was: a lock file the adoption made in the source is removed again,
|
||||||
|
//! exactly that file and no other, on every way out but its success
|
||||||
|
//! (stopped by the books server's close, refused, or a panic); one the
|
||||||
|
//! source already had is never removed. A success leaves the one it
|
||||||
|
//! made, and says so (`source_lock_created`). Books are made, adopted
|
||||||
|
//! and restored one at a time across processes (`run/books.lock`), and
|
||||||
|
//! a job waiting for its turn looks at its stop every few milliseconds
|
||||||
|
//! and leaves at once when asked, so a close of the books is never held
|
||||||
|
//! up by a job that is only queued.
|
||||||
//! 6. No error names the root or a path inside it: nothing an agent is
|
//! 6. No error names the root or a path inside it: nothing an agent is
|
||||||
//! shown names the books' folder.
|
//! shown names the books' folder.
|
||||||
//! 7. Restoring a backup (plan 3.7) is proven before use, as an adoption
|
//! 7. Restoring a backup (plan 3.7) is proven before use, as an adoption
|
||||||
@@ -116,6 +125,10 @@ pub enum RootError {
|
|||||||
/// Adopting was refused, with why.
|
/// Adopting was refused, with why.
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
Adopt(String),
|
Adopt(String),
|
||||||
|
/// A job was stopped because the books are closing, before its point of
|
||||||
|
/// no return ([`JobStop`]): nothing it did is left.
|
||||||
|
#[error("{0}")]
|
||||||
|
Stopped(String),
|
||||||
/// The store refused (its message with the root's path taken out).
|
/// The store refused (its message with the root's path taken out).
|
||||||
#[error("{0}")]
|
#[error("{0}")]
|
||||||
Store(String, #[source] StoreError),
|
Store(String, #[source] StoreError),
|
||||||
@@ -146,6 +159,87 @@ impl From<std::io::Error> for RootError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// What a job that changes which books the root holds (create, adopt,
|
||||||
|
/// restore) is asked, as it goes, whether it must stop (the books server's
|
||||||
|
/// close): looked at as each phase begins and once per stored file copied;
|
||||||
|
/// a job stops, removes what it made, and leaves the books exactly as they
|
||||||
|
/// were. Each job has a point of no return (the rename that puts its books
|
||||||
|
/// in place), after which nothing is asked and the job finishes: a few
|
||||||
|
/// renames and directory syncs, so short and bounded.
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct JobStop {
|
||||||
|
flag: std::sync::Arc<std::sync::atomic::AtomicBool>,
|
||||||
|
phase: Option<JobPhaseWatch>,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What is told the name of each phase of a job as it begins
|
||||||
|
/// ([`JobStop::with_phase_watch`]).
|
||||||
|
pub type JobPhaseWatch = std::sync::Arc<dyn Fn(&str) + Send + Sync>;
|
||||||
|
|
||||||
|
impl JobStop {
|
||||||
|
/// Stop when `flag` is set.
|
||||||
|
pub fn new(flag: std::sync::Arc<std::sync::atomic::AtomicBool>) -> Self {
|
||||||
|
Self { flag, phase: None }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Never asked to stop (a command run on its own, not in the server).
|
||||||
|
pub fn never() -> Self {
|
||||||
|
Self::new(std::sync::Arc::default())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Told the name of each phase as it begins, before the stop is looked
|
||||||
|
/// at (a seam for tests, and the server's test knob that holds a job
|
||||||
|
/// inside a phase: it may wait, but must give up when the flag is set).
|
||||||
|
#[must_use]
|
||||||
|
pub fn with_phase_watch(mut self, watch: JobPhaseWatch) -> Self {
|
||||||
|
self.phase = Some(watch);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The flag: what git and the store's loops are handed to look at.
|
||||||
|
pub fn flag(&self) -> std::sync::Arc<std::sync::atomic::AtomicBool> {
|
||||||
|
self.flag.clone()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether a stop was asked for.
|
||||||
|
pub fn requested(&self) -> bool {
|
||||||
|
self.flag.load(std::sync::atomic::Ordering::SeqCst)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A phase begins, for a caller that decides for itself what to do about
|
||||||
|
/// a stop: whether one was asked for (the phase watch is told first).
|
||||||
|
pub fn look(&self, phase: &str) -> bool {
|
||||||
|
if let Some(watch) = &self.phase {
|
||||||
|
watch(phase);
|
||||||
|
}
|
||||||
|
self.requested()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A phase begins: Ok, or `Stopped` (naming what was not done).
|
||||||
|
fn at(&self, phase: &str, undone: &str) -> Result<(), RootError> {
|
||||||
|
if let Some(watch) = &self.phase {
|
||||||
|
watch(phase);
|
||||||
|
}
|
||||||
|
if self.requested() {
|
||||||
|
Err(RootError::Stopped(format!(
|
||||||
|
"stopped because the books are closing: nothing was {undone}"
|
||||||
|
)))
|
||||||
|
} else {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A stop that reached the store's own loops or git, said as a job's.
|
||||||
|
fn said(&self, e: RootError, undone: &str) -> RootError {
|
||||||
|
match e {
|
||||||
|
RootError::Store(_, StoreError::Cancelled) => RootError::Stopped(format!(
|
||||||
|
"stopped because the books are closing: nothing was {undone}"
|
||||||
|
)),
|
||||||
|
other => other,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// A book's id within the root: its folder name under `books/`.
|
/// A book's id within the root: its folder name under `books/`.
|
||||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||||
pub struct BookId(String);
|
pub struct BookId(String);
|
||||||
@@ -731,8 +825,11 @@ impl Root {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Take the lock under which books are made: one at a time, across
|
/// Take the lock under which books are made: one at a time, across
|
||||||
/// processes.
|
/// processes. A job that has to wait for another's turn looks at `stop`
|
||||||
fn books_lock(&self) -> Result<std::fs::File, RootError> {
|
/// while it waits (every few milliseconds), and gives up with `Stopped`
|
||||||
|
/// if asked: a close of the books can't be held up by a job that is
|
||||||
|
/// only waiting its turn behind another.
|
||||||
|
fn books_lock(&self, stop: &JobStop, undone: &str) -> Result<std::fs::File, RootError> {
|
||||||
let (run, _) = self.private_subdir(RUN_DIR, false)?;
|
let (run, _) = self.private_subdir(RUN_DIR, false)?;
|
||||||
let path = run.join(BOOKS_LOCK);
|
let path = run.join(BOOKS_LOCK);
|
||||||
let file = std::fs::OpenOptions::new()
|
let file = std::fs::OpenOptions::new()
|
||||||
@@ -741,24 +838,56 @@ impl Root {
|
|||||||
.write(true)
|
.write(true)
|
||||||
.open(&path)?;
|
.open(&path)?;
|
||||||
set_mode(&path, 0o600)?;
|
set_mode(&path, 0o600)?;
|
||||||
file.lock()?;
|
loop {
|
||||||
Ok(file)
|
match file.try_lock() {
|
||||||
|
Ok(()) => return Ok(file),
|
||||||
|
Err(std::fs::TryLockError::WouldBlock) => {
|
||||||
|
// The flag alone: the phase watch is told of phases, not
|
||||||
|
// of every turn of this wait.
|
||||||
|
if stop.requested() {
|
||||||
|
return Err(RootError::Stopped(format!(
|
||||||
|
"stopped because the books are closing: nothing was {undone}"
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(5));
|
||||||
|
}
|
||||||
|
Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Start new, empty books called `id` in `base_currency`. Refused if
|
/// Start new, empty books called `id` in `base_currency`. Refused if
|
||||||
/// books of that id exist. Returns the open store.
|
/// books of that id exist. Returns the open store.
|
||||||
pub fn create_book(&self, id: &BookId, base_currency: Currency) -> Result<Store, RootError> {
|
pub fn create_book(&self, id: &BookId, base_currency: Currency) -> Result<Store, RootError> {
|
||||||
self.create_book_inner(id, base_currency)
|
self.create_book_stoppable(id, base_currency, &JobStop::never())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Self::create_book`], stopped if `stop` asks before its folder is
|
||||||
|
/// made (its point of no return); after that it makes one empty book,
|
||||||
|
/// the same few files and syncs whatever else is in the root.
|
||||||
|
pub fn create_book_stoppable(
|
||||||
|
&self,
|
||||||
|
id: &BookId,
|
||||||
|
base_currency: Currency,
|
||||||
|
stop: &JobStop,
|
||||||
|
) -> Result<Store, RootError> {
|
||||||
|
self.create_book_inner(id, base_currency, stop)
|
||||||
.map_err(|e| self.hide(e))
|
.map_err(|e| self.hide(e))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn create_book_inner(&self, id: &BookId, base_currency: Currency) -> Result<Store, RootError> {
|
fn create_book_inner(
|
||||||
let _lock = self.books_lock()?;
|
&self,
|
||||||
|
id: &BookId,
|
||||||
|
base_currency: Currency,
|
||||||
|
stop: &JobStop,
|
||||||
|
) -> Result<Store, RootError> {
|
||||||
|
let _lock = self.books_lock(stop, "created")?;
|
||||||
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
||||||
let dir = books.join(id.as_str());
|
let dir = books.join(id.as_str());
|
||||||
if std::fs::symlink_metadata(&dir).is_ok() {
|
if std::fs::symlink_metadata(&dir).is_ok() {
|
||||||
return Err(RootError::Exists(id.to_string()));
|
return Err(RootError::Exists(id.to_string()));
|
||||||
}
|
}
|
||||||
|
stop.at("start", "created")?;
|
||||||
make_private_dir(&dir)?;
|
make_private_dir(&dir)?;
|
||||||
match Store::create(&dir, base_currency) {
|
match Store::create(&dir, base_currency) {
|
||||||
Ok(store) => {
|
Ok(store) => {
|
||||||
@@ -793,7 +922,21 @@ impl Root {
|
|||||||
id: &BookId,
|
id: &BookId,
|
||||||
options: &AdoptOptions,
|
options: &AdoptOptions,
|
||||||
) -> Result<AdoptReport, RootError> {
|
) -> Result<AdoptReport, RootError> {
|
||||||
self.adopt_inner(source, id, options)
|
self.adopt_stoppable(source, id, options, &JobStop::never())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Self::adopt`], stopped if `stop` asks at any phase before the
|
||||||
|
/// rename that puts the books in place (its point of no return): the
|
||||||
|
/// staging folder is removed and the root is as it was. After the
|
||||||
|
/// rename it finishes, which is a directory sync.
|
||||||
|
pub fn adopt_stoppable(
|
||||||
|
&self,
|
||||||
|
source: &Path,
|
||||||
|
id: &BookId,
|
||||||
|
options: &AdoptOptions,
|
||||||
|
stop: &JobStop,
|
||||||
|
) -> Result<AdoptReport, RootError> {
|
||||||
|
self.adopt_inner(source, id, options, stop)
|
||||||
.map_err(|e| self.hide(e))
|
.map_err(|e| self.hide(e))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -802,13 +945,15 @@ impl Root {
|
|||||||
source: &Path,
|
source: &Path,
|
||||||
id: &BookId,
|
id: &BookId,
|
||||||
options: &AdoptOptions,
|
options: &AdoptOptions,
|
||||||
|
stop: &JobStop,
|
||||||
) -> Result<AdoptReport, RootError> {
|
) -> Result<AdoptReport, RootError> {
|
||||||
let _lock = self.books_lock()?;
|
let _lock = self.books_lock(stop, "adopted")?;
|
||||||
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
||||||
let dest = books.join(id.as_str());
|
let dest = books.join(id.as_str());
|
||||||
if std::fs::symlink_metadata(&dest).is_ok() {
|
if std::fs::symlink_metadata(&dest).is_ok() {
|
||||||
return Err(RootError::Exists(id.to_string()));
|
return Err(RootError::Exists(id.to_string()));
|
||||||
}
|
}
|
||||||
|
stop.at("start", "adopted")?;
|
||||||
let source = self.adoptable(source)?;
|
let source = self.adoptable(source)?;
|
||||||
for (what, path) in [
|
for (what, path) in [
|
||||||
("vault folder", &options.vault_dir),
|
("vault folder", &options.vault_dir),
|
||||||
@@ -824,9 +969,14 @@ impl Root {
|
|||||||
}
|
}
|
||||||
// Step 1: the source's writer lock, held to the end, so nothing
|
// Step 1: the source's writer lock, held to the end, so nothing
|
||||||
// writes it while it is copied.
|
// writes it while it is copied.
|
||||||
let (_source_lock, source_lock_created) = lock_source(&source)?;
|
let mut source_lock = lock_source(&source)?;
|
||||||
// Step 2: verify the chain and record the head.
|
let source_lock_created = source_lock.created();
|
||||||
let (raw, lines) = read_source_journal(&source)?;
|
// Step 2: verify the chain and record the head. (The chain's check
|
||||||
|
// looks at the stop once per journal line.)
|
||||||
|
let scope = crate::cancel::scope(stop.flag());
|
||||||
|
let (raw, lines) = read_source_journal(&source).map_err(|e| stop.said(e, "adopted"))?;
|
||||||
|
drop(scope);
|
||||||
|
stop.at("journal", "adopted")?;
|
||||||
let head = head_of(&lines);
|
let head = head_of(&lines);
|
||||||
if let Some(expected) = &options.expect_head
|
if let Some(expected) = &options.expect_head
|
||||||
&& *expected != head
|
&& *expected != head
|
||||||
@@ -859,11 +1009,19 @@ impl Root {
|
|||||||
}
|
}
|
||||||
let staging = books.join(format!("{STAGING_PREFIX}{id}-{}", std::process::id()));
|
let staging = books.join(format!("{STAGING_PREFIX}{id}-{}", std::process::id()));
|
||||||
make_private_dir(&staging)?;
|
make_private_dir(&staging)?;
|
||||||
|
// The store's own loops (opening, verifying) look at the stop too.
|
||||||
|
let scope = crate::cancel::scope(stop.flag());
|
||||||
let built = (|| -> Result<AdoptReport, RootError> {
|
let built = (|| -> Result<AdoptReport, RootError> {
|
||||||
|
stop.at("copy", "adopted")?;
|
||||||
// Step 3: the journal as read, then every stored file.
|
// Step 3: the journal as read, then every stored file.
|
||||||
write_private_file(&staging.join(JOURNAL_FILE), &raw)?;
|
write_private_file(&staging.join(JOURNAL_FILE), &raw)?;
|
||||||
let blob_dir = crate::store::BLOBS_DIR;
|
let blob_dir = crate::store::BLOBS_DIR;
|
||||||
let copied = copy_blobs(&source.join(blob_dir), &staging.join(blob_dir))?;
|
let copied = copy_blobs(
|
||||||
|
&source.join(blob_dir),
|
||||||
|
&staging.join(blob_dir),
|
||||||
|
stop,
|
||||||
|
"adopted",
|
||||||
|
)?;
|
||||||
// Step 5: the vault's records and the v1 key.
|
// Step 5: the vault's records and the v1 key.
|
||||||
let vault_files = match &options.vault_dir {
|
let vault_files = match &options.vault_dir {
|
||||||
Some(dir) => copy_flat_private(dir, &staging.join(VAULT_DIR))?,
|
Some(dir) => copy_flat_private(dir, &staging.join(VAULT_DIR))?,
|
||||||
@@ -879,6 +1037,7 @@ impl Root {
|
|||||||
}
|
}
|
||||||
None => false,
|
None => false,
|
||||||
};
|
};
|
||||||
|
stop.at("open", "adopted")?;
|
||||||
let mut store = Store::open(&staging)?;
|
let mut store = Store::open(&staging)?;
|
||||||
if store.head() != head {
|
if store.head() != head {
|
||||||
return Err(RootError::Adopt(format!(
|
return Err(RootError::Adopt(format!(
|
||||||
@@ -899,6 +1058,7 @@ impl Root {
|
|||||||
.join(", ")
|
.join(", ")
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
|
stop.at("verify", "adopted")?;
|
||||||
store.verify_and_heal()?;
|
store.verify_and_heal()?;
|
||||||
let blobs_verified = store.verify_blobs()?;
|
let blobs_verified = store.verify_blobs()?;
|
||||||
// The copy is new books of this version, in its journal format
|
// The copy is new books of this version, in its journal format
|
||||||
@@ -936,13 +1096,22 @@ impl Root {
|
|||||||
format_upgraded,
|
format_upgraded,
|
||||||
})
|
})
|
||||||
})();
|
})();
|
||||||
let renamed = built.and_then(|report| {
|
drop(scope);
|
||||||
std::fs::rename(&staging, &dest)?;
|
let renamed = built
|
||||||
sync_dir(&books)?;
|
.map_err(|e| stop.said(e, "adopted"))
|
||||||
Ok(report)
|
.and_then(|report| {
|
||||||
});
|
// The last look: from the rename on, the job finishes.
|
||||||
|
stop.at("place", "adopted")?;
|
||||||
|
std::fs::rename(&staging, &dest)?;
|
||||||
|
sync_dir(&books)?;
|
||||||
|
Ok(report)
|
||||||
|
});
|
||||||
if renamed.is_err() {
|
if renamed.is_err() {
|
||||||
let _ = std::fs::remove_dir_all(&staging);
|
let _ = std::fs::remove_dir_all(&staging);
|
||||||
|
} else {
|
||||||
|
// Adopted: a lock file made in the source stays and is reported
|
||||||
|
// (`source_lock_created`). Any other way out, it goes.
|
||||||
|
source_lock.keep();
|
||||||
}
|
}
|
||||||
renamed
|
renamed
|
||||||
}
|
}
|
||||||
@@ -991,7 +1160,11 @@ impl Root {
|
|||||||
source: &str,
|
source: &str,
|
||||||
books: &Path,
|
books: &Path,
|
||||||
id: &BookId,
|
id: &BookId,
|
||||||
|
stop: &JobStop,
|
||||||
) -> Result<(PathBuf, crate::backup::Verified), RootError> {
|
) -> Result<(PathBuf, crate::backup::Verified), RootError> {
|
||||||
|
stop.at("fetch", "restored")?;
|
||||||
|
// git, and the verification's own phases and loops, look at the stop.
|
||||||
|
let git = git.clone().with_cancel(stop.flag());
|
||||||
// Anything left from one that never finished goes first: none is
|
// Anything left from one that never finished goes first: none is
|
||||||
// in progress (each holds the books lock).
|
// in progress (each holds the books lock).
|
||||||
for entry in std::fs::read_dir(books)? {
|
for entry in std::fs::read_dir(books)? {
|
||||||
@@ -1005,13 +1178,18 @@ impl Root {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
let scratch = books.join(format!("{RESTORE_PREFIX}{id}-{}", std::process::id()));
|
let scratch = books.join(format!("{RESTORE_PREFIX}{id}-{}", std::process::id()));
|
||||||
match crate::backup::verify(git, source, &scratch) {
|
match crate::backup::verify(&git, source, &scratch) {
|
||||||
Ok(v) => Ok((scratch, v)),
|
Ok(v) => Ok((scratch, v)),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
|
// What the verification wrote goes with it (a stop leaves the
|
||||||
|
// root as it was).
|
||||||
let _ = std::fs::remove_dir_all(&scratch);
|
let _ = std::fs::remove_dir_all(&scratch);
|
||||||
Err(RootError::Adopt(format!(
|
Err(match e {
|
||||||
"that backup can't be restored: {e}"
|
crate::backup::BackupError::Cancelled(_) => RootError::Stopped(
|
||||||
)))
|
"stopped because the books are closing: nothing was restored".into(),
|
||||||
|
),
|
||||||
|
e => RootError::Adopt(format!("that backup can't be restored: {e}")),
|
||||||
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1024,10 +1202,23 @@ impl Root {
|
|||||||
source: &str,
|
source: &str,
|
||||||
id: &BookId,
|
id: &BookId,
|
||||||
) -> Result<RestorePreview, RootError> {
|
) -> Result<RestorePreview, RootError> {
|
||||||
|
self.restore_preview_stoppable(git, source, id, &JobStop::never())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Self::restore_preview`], stopped if `stop` asks: the clone is
|
||||||
|
/// removed and nothing is left.
|
||||||
|
pub fn restore_preview_stoppable(
|
||||||
|
&self,
|
||||||
|
git: &crate::backup::Git,
|
||||||
|
source: &str,
|
||||||
|
id: &BookId,
|
||||||
|
stop: &JobStop,
|
||||||
|
) -> Result<RestorePreview, RootError> {
|
||||||
|
let _scope = crate::cancel::scope(stop.flag());
|
||||||
(|| {
|
(|| {
|
||||||
let _lock = self.books_lock()?;
|
let _lock = self.books_lock(stop, "restored")?;
|
||||||
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
||||||
let (scratch, v) = self.fetch_backup(git, source, &books, id)?;
|
let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?;
|
||||||
let vault = scratch.join(VAULT_DIR);
|
let vault = scratch.join(VAULT_DIR);
|
||||||
let vault_files = if vault.is_dir() {
|
let vault_files = if vault.is_dir() {
|
||||||
std::fs::read_dir(&vault)
|
std::fs::read_dir(&vault)
|
||||||
@@ -1063,7 +1254,24 @@ impl Root {
|
|||||||
expect_head: &(u64, String),
|
expect_head: &(u64, String),
|
||||||
replace: bool,
|
replace: bool,
|
||||||
) -> Result<RestoreReport, RootError> {
|
) -> Result<RestoreReport, RootError> {
|
||||||
self.restore_inner(git, source, id, expect_head, replace)
|
self.restore_stoppable(git, source, id, expect_head, replace, &JobStop::never())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Self::restore`], stopped if `stop` asks at any phase before the
|
||||||
|
/// renames that put the books in place (its point of no return): the
|
||||||
|
/// clone and the staging folder are removed and the root is as it was,
|
||||||
|
/// books that were to be replaced untouched. From the first rename on it
|
||||||
|
/// finishes: two renames and two directory syncs.
|
||||||
|
pub fn restore_stoppable(
|
||||||
|
&self,
|
||||||
|
git: &crate::backup::Git,
|
||||||
|
source: &str,
|
||||||
|
id: &BookId,
|
||||||
|
expect_head: &(u64, String),
|
||||||
|
replace: bool,
|
||||||
|
stop: &JobStop,
|
||||||
|
) -> Result<RestoreReport, RootError> {
|
||||||
|
self.restore_inner(git, source, id, expect_head, replace, stop)
|
||||||
.map_err(|e| match e {
|
.map_err(|e| match e {
|
||||||
// The copy's checks are the adoption's: said as a restore.
|
// The copy's checks are the adoption's: said as a restore.
|
||||||
RootError::Adopt(text) => {
|
RootError::Adopt(text) => {
|
||||||
@@ -1081,8 +1289,9 @@ impl Root {
|
|||||||
id: &BookId,
|
id: &BookId,
|
||||||
expect_head: &(u64, String),
|
expect_head: &(u64, String),
|
||||||
replace: bool,
|
replace: bool,
|
||||||
|
stop: &JobStop,
|
||||||
) -> Result<RestoreReport, RootError> {
|
) -> Result<RestoreReport, RootError> {
|
||||||
let _lock = self.books_lock()?;
|
let _lock = self.books_lock(stop, "restored")?;
|
||||||
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
let (books, _) = self.private_subdir(BOOKS_DIR, false)?;
|
||||||
let dest = books.join(id.as_str());
|
let dest = books.join(id.as_str());
|
||||||
let exists = std::fs::symlink_metadata(&dest).is_ok();
|
let exists = std::fs::symlink_metadata(&dest).is_ok();
|
||||||
@@ -1097,18 +1306,25 @@ impl Root {
|
|||||||
}
|
}
|
||||||
// Books being replaced are moved only while nothing holds them.
|
// Books being replaced are moved only while nothing holds them.
|
||||||
let _held = if exists {
|
let _held = if exists {
|
||||||
Some(lock_source(&dest).map_err(|_| {
|
let mut held = lock_source(&dest).map_err(|_| {
|
||||||
RootError::Adopt(format!(
|
RootError::Adopt(format!(
|
||||||
"the books called {:?} are open: close them first; nothing was restored",
|
"the books called {:?} are open: close them first; nothing was restored",
|
||||||
id.as_str()
|
id.as_str()
|
||||||
))
|
))
|
||||||
})?)
|
})?;
|
||||||
|
// The root's own folder: its lock file is the books', whoever
|
||||||
|
// made it.
|
||||||
|
held.keep();
|
||||||
|
Some(held)
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
};
|
};
|
||||||
let (scratch, v) = self.fetch_backup(git, source, &books, id)?;
|
stop.at("start", "restored")?;
|
||||||
|
let _scope = crate::cancel::scope(stop.flag());
|
||||||
|
let (scratch, v) = self.fetch_backup(git, source, &books, id, stop)?;
|
||||||
let staging = books.join(format!("{RESTORE_PREFIX}{id}-{}-book", std::process::id()));
|
let staging = books.join(format!("{RESTORE_PREFIX}{id}-{}-book", std::process::id()));
|
||||||
let built = (|| -> Result<RestoreReport, RootError> {
|
let built = (|| -> Result<RestoreReport, RootError> {
|
||||||
|
stop.at("copy", "restored")?;
|
||||||
if v.head != *expect_head {
|
if v.head != *expect_head {
|
||||||
return Err(RootError::Adopt(format!(
|
return Err(RootError::Adopt(format!(
|
||||||
"that backup isn't the one previewed (it is now at event {}): nothing was restored; preview it again",
|
"that backup isn't the one previewed (it is now at event {}): nothing was restored; preview it again",
|
||||||
@@ -1124,7 +1340,12 @@ impl Root {
|
|||||||
make_private_dir(&staging)?;
|
make_private_dir(&staging)?;
|
||||||
write_private_file(&staging.join(JOURNAL_FILE), &raw)?;
|
write_private_file(&staging.join(JOURNAL_FILE), &raw)?;
|
||||||
let blob_dir = crate::store::BLOBS_DIR;
|
let blob_dir = crate::store::BLOBS_DIR;
|
||||||
let copied = copy_blobs(&scratch.join(blob_dir), &staging.join(blob_dir))?;
|
let copied = copy_blobs(
|
||||||
|
&scratch.join(blob_dir),
|
||||||
|
&staging.join(blob_dir),
|
||||||
|
stop,
|
||||||
|
"restored",
|
||||||
|
)?;
|
||||||
let vault_files = if scratch.join(VAULT_DIR).is_dir() {
|
let vault_files = if scratch.join(VAULT_DIR).is_dir() {
|
||||||
copy_flat_private(&scratch.join(VAULT_DIR), &staging.join(VAULT_DIR))?
|
copy_flat_private(&scratch.join(VAULT_DIR), &staging.join(VAULT_DIR))?
|
||||||
} else {
|
} else {
|
||||||
@@ -1151,6 +1372,7 @@ impl Root {
|
|||||||
&crate::ops::ops_dir(&staging).join(RESTORED_FROM),
|
&crate::ops::ops_dir(&staging).join(RESTORED_FROM),
|
||||||
v.book.as_deref().unwrap_or("").as_bytes(),
|
v.book.as_deref().unwrap_or("").as_bytes(),
|
||||||
)?;
|
)?;
|
||||||
|
stop.at("open", "restored")?;
|
||||||
let mut store = Store::open(&staging)?;
|
let mut store = Store::open(&staging)?;
|
||||||
if store.head() != v.head {
|
if store.head() != v.head {
|
||||||
return Err(RootError::Adopt(format!(
|
return Err(RootError::Adopt(format!(
|
||||||
@@ -1165,6 +1387,7 @@ impl Root {
|
|||||||
"the backup lacks stored files its books name: nothing was restored".into(),
|
"the backup lacks stored files its books name: nothing was restored".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
stop.at("verify", "restored")?;
|
||||||
store.verify_and_heal()?;
|
store.verify_and_heal()?;
|
||||||
let blobs_verified = store.verify_blobs()?;
|
let blobs_verified = store.verify_blobs()?;
|
||||||
let head = store.head();
|
let head = store.head();
|
||||||
@@ -1180,38 +1403,42 @@ impl Root {
|
|||||||
})
|
})
|
||||||
})();
|
})();
|
||||||
let _ = std::fs::remove_dir_all(&scratch);
|
let _ = std::fs::remove_dir_all(&scratch);
|
||||||
let placed = built.and_then(|mut report| {
|
let placed = built
|
||||||
if exists {
|
.map_err(|e| stop.said(e, "restored"))
|
||||||
let (legacy, _) = self.private_subdir(LEGACY_DIR, false)?;
|
.and_then(|mut report| {
|
||||||
let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S");
|
// The last look: from the first rename on, the job finishes.
|
||||||
let mut name = format!("{id}-{stamp}");
|
stop.at("place", "restored")?;
|
||||||
let mut n = 1;
|
if exists {
|
||||||
while std::fs::symlink_metadata(legacy.join(&name)).is_ok() {
|
let (legacy, _) = self.private_subdir(LEGACY_DIR, false)?;
|
||||||
n += 1;
|
let stamp = chrono::Utc::now().format("%Y%m%d-%H%M%S");
|
||||||
name = format!("{id}-{stamp}-{n}");
|
let mut name = format!("{id}-{stamp}");
|
||||||
}
|
let mut n = 1;
|
||||||
std::fs::rename(&dest, legacy.join(&name))?;
|
while std::fs::symlink_metadata(legacy.join(&name)).is_ok() {
|
||||||
if let Err(e) = std::fs::rename(&staging, &dest) {
|
n += 1;
|
||||||
// The books it would replace go back where they were.
|
name = format!("{id}-{stamp}-{n}");
|
||||||
if std::fs::rename(legacy.join(&name), &dest).is_err() {
|
|
||||||
return Err(RootError::Adopt(format!(
|
|
||||||
"the backup couldn't be put in place ({}), and the books it would \
|
|
||||||
replace are in the legacy folder as {name}: nothing was restored",
|
|
||||||
e.kind()
|
|
||||||
)));
|
|
||||||
}
|
}
|
||||||
return Err(e.into());
|
std::fs::rename(&dest, legacy.join(&name))?;
|
||||||
|
if let Err(e) = std::fs::rename(&staging, &dest) {
|
||||||
|
// The books it would replace go back where they were.
|
||||||
|
if std::fs::rename(legacy.join(&name), &dest).is_err() {
|
||||||
|
return Err(RootError::Adopt(format!(
|
||||||
|
"the backup couldn't be put in place ({}), and the books it would \
|
||||||
|
replace are in the legacy folder as {name}: nothing was restored",
|
||||||
|
e.kind()
|
||||||
|
)));
|
||||||
|
}
|
||||||
|
return Err(e.into());
|
||||||
|
}
|
||||||
|
// In place: a folder that won't sync now is said no more
|
||||||
|
// than any later write's would be.
|
||||||
|
let _ = sync_dir(&legacy);
|
||||||
|
report.replaced = Some(name);
|
||||||
|
} else {
|
||||||
|
std::fs::rename(&staging, &dest)?;
|
||||||
}
|
}
|
||||||
// In place: a folder that won't sync now is said no more
|
let _ = sync_dir(&books);
|
||||||
// than any later write's would be.
|
Ok(report)
|
||||||
let _ = sync_dir(&legacy);
|
});
|
||||||
report.replaced = Some(name);
|
|
||||||
} else {
|
|
||||||
std::fs::rename(&staging, &dest)?;
|
|
||||||
}
|
|
||||||
let _ = sync_dir(&books);
|
|
||||||
Ok(report)
|
|
||||||
});
|
|
||||||
if placed.is_err() {
|
if placed.is_err() {
|
||||||
let _ = std::fs::remove_dir_all(&staging);
|
let _ = std::fs::remove_dir_all(&staging);
|
||||||
}
|
}
|
||||||
@@ -1242,7 +1469,19 @@ impl Root {
|
|||||||
/// checks [`Self::adopt`] makes, writing nothing (not even a lock
|
/// checks [`Self::adopt`] makes, writing nothing (not even a lock
|
||||||
/// file). The adoption itself reads it all again under the lock.
|
/// file). The adoption itself reads it all again under the lock.
|
||||||
pub fn adopt_preview(&self, source: &Path) -> Result<SourcePreview, RootError> {
|
pub fn adopt_preview(&self, source: &Path) -> Result<SourcePreview, RootError> {
|
||||||
|
self.adopt_preview_stoppable(source, &JobStop::never())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// [`Self::adopt_preview`], stopped if `stop` asks (the read of the
|
||||||
|
/// source's journal looks once per line).
|
||||||
|
pub fn adopt_preview_stoppable(
|
||||||
|
&self,
|
||||||
|
source: &Path,
|
||||||
|
stop: &JobStop,
|
||||||
|
) -> Result<SourcePreview, RootError> {
|
||||||
|
let _scope = crate::cancel::scope(stop.flag());
|
||||||
(|| {
|
(|| {
|
||||||
|
stop.at("preview", "read")?;
|
||||||
let source = self.adoptable(source)?;
|
let source = self.adoptable(source)?;
|
||||||
// Held for writing now: adoption would be refused, so is this.
|
// Held for writing now: adoption would be refused, so is this.
|
||||||
if let Ok(lock) = std::fs::File::open(source.join(crate::store::LOCK_FILE))
|
if let Ok(lock) = std::fs::File::open(source.join(crate::store::LOCK_FILE))
|
||||||
@@ -1254,7 +1493,7 @@ impl Root {
|
|||||||
.into(),
|
.into(),
|
||||||
)));
|
)));
|
||||||
}
|
}
|
||||||
let (_, lines) = read_source_journal(&source)?;
|
let (_, lines) = read_source_journal(&source).map_err(|e| stop.said(e, "read"))?;
|
||||||
Ok(SourcePreview {
|
Ok(SourcePreview {
|
||||||
head: head_of(&lines),
|
head: head_of(&lines),
|
||||||
currency: crate::store::journal_currency(&lines)?,
|
currency: crate::store::journal_currency(&lines)?,
|
||||||
@@ -1381,7 +1620,10 @@ impl Root {
|
|||||||
// Held for writing: nothing is moved from under it. A preview
|
// Held for writing: nothing is moved from under it. A preview
|
||||||
// only looks; the move holds the lock to the end.
|
// only looks; the move holds the lock to the end.
|
||||||
let _lock = if confirm {
|
let _lock = if confirm {
|
||||||
Some(lock_source(source)?.0)
|
let mut lock = lock_source(source)?;
|
||||||
|
// The old copy is moved whole, lock file and all.
|
||||||
|
lock.keep();
|
||||||
|
Some(lock)
|
||||||
} else {
|
} else {
|
||||||
if let Ok(lock) = std::fs::File::open(source.join(crate::store::LOCK_FILE))
|
if let Ok(lock) = std::fs::File::open(source.join(crate::store::LOCK_FILE))
|
||||||
&& let Err(std::fs::TryLockError::WouldBlock) = lock.try_lock_shared()
|
&& let Err(std::fs::TryLockError::WouldBlock) = lock.try_lock_shared()
|
||||||
@@ -1830,9 +2072,63 @@ pub struct AdoptReport {
|
|||||||
|
|
||||||
/// The source's writer lock: its lock file opened read-only (so a
|
/// The source's writer lock: its lock file opened read-only (so a
|
||||||
/// read-only source can be adopted and nothing in it changes), or, for
|
/// read-only source can be adopted and nothing in it changes), or, for
|
||||||
/// books that never had one, created. Returns the lock and whether the
|
/// books that never had one, created.
|
||||||
/// file was made.
|
///
|
||||||
fn lock_source(source: &Path) -> Result<(std::fs::File, bool), RootError> {
|
/// A lock file this made is the adoption's own, not the source's: unless
|
||||||
|
/// the adoption succeeds (the caller says so with [`SourceLock::keep`]),
|
||||||
|
/// it is removed when this is dropped, whatever way out the adoption took
|
||||||
|
/// (stopped by a close, failed, or a panic): the original is left as it
|
||||||
|
/// was. A lock file that was there already is never removed, nor is a
|
||||||
|
/// file this didn't make: the path must still name the very file this
|
||||||
|
/// holds, on systems that can tell.
|
||||||
|
struct SourceLock {
|
||||||
|
file: Option<std::fs::File>,
|
||||||
|
path: PathBuf,
|
||||||
|
created: bool,
|
||||||
|
keep: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SourceLock {
|
||||||
|
/// The source had no lock file, so taking its lock made one.
|
||||||
|
fn created(&self) -> bool {
|
||||||
|
self.created
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The lock file stays, whatever this made: the adoption is done (and
|
||||||
|
/// reports it), or the folder is the root's own.
|
||||||
|
fn keep(&mut self) {
|
||||||
|
self.keep = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for SourceLock {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
if !self.created || self.keep {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let Some(file) = self.file.take() else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
// Still the file this made? (Never one another process put there.)
|
||||||
|
#[cfg(unix)]
|
||||||
|
{
|
||||||
|
use std::os::unix::fs::MetadataExt;
|
||||||
|
let same = match (file.metadata(), std::fs::symlink_metadata(&self.path)) {
|
||||||
|
(Ok(mine), Ok(there)) => mine.dev() == there.dev() && mine.ino() == there.ino(),
|
||||||
|
_ => false,
|
||||||
|
};
|
||||||
|
if !same {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Let go of the lock first (a file that is open can't be removed on
|
||||||
|
// every system), then remove exactly that file.
|
||||||
|
drop(file);
|
||||||
|
let _ = std::fs::remove_file(&self.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn lock_source(source: &Path) -> Result<SourceLock, RootError> {
|
||||||
let path = source.join(crate::store::LOCK_FILE);
|
let path = source.join(crate::store::LOCK_FILE);
|
||||||
let (file, created) = match std::fs::File::open(&path) {
|
let (file, created) = match std::fs::File::open(&path) {
|
||||||
Ok(file) => (file, false),
|
Ok(file) => (file, false),
|
||||||
@@ -1841,7 +2137,15 @@ fn lock_source(source: &Path) -> Result<(std::fs::File, bool), RootError> {
|
|||||||
}
|
}
|
||||||
Err(e) => return Err(e.into()),
|
Err(e) => return Err(e.into()),
|
||||||
};
|
};
|
||||||
if !created {
|
// From here the guard owns the file this may have made, so a refusal
|
||||||
|
// below removes it too.
|
||||||
|
let held = SourceLock {
|
||||||
|
file: Some(file),
|
||||||
|
path,
|
||||||
|
created,
|
||||||
|
keep: false,
|
||||||
|
};
|
||||||
|
if !created && let Some(file) = &held.file {
|
||||||
match file.try_lock() {
|
match file.try_lock() {
|
||||||
Ok(()) => {}
|
Ok(()) => {}
|
||||||
Err(std::fs::TryLockError::WouldBlock) => {
|
Err(std::fs::TryLockError::WouldBlock) => {
|
||||||
@@ -1854,7 +2158,7 @@ fn lock_source(source: &Path) -> Result<(std::fs::File, bool), RootError> {
|
|||||||
Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),
|
Err(std::fs::TryLockError::Error(e)) => return Err(e.into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok((file, created))
|
Ok(held)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The head of a verified journal: the last line's seq and the hash the
|
/// The head of a verified journal: the last line's seq and the hash the
|
||||||
@@ -2183,7 +2487,12 @@ struct CopiedBlobs {
|
|||||||
/// its name; an unfinished write (`<sha>.tmp`, a put that never finished)
|
/// its name; an unfinished write (`<sha>.tmp`, a put that never finished)
|
||||||
/// is left behind and counted; anything else (a link, a stray file) is
|
/// is left behind and counted; anything else (a link, a stray file) is
|
||||||
/// refused. Folders 0700, files 0600, every folder synced.
|
/// refused. Folders 0700, files 0600, every folder synced.
|
||||||
fn copy_blobs(from: &Path, to: &Path) -> Result<CopiedBlobs, RootError> {
|
fn copy_blobs(
|
||||||
|
from: &Path,
|
||||||
|
to: &Path,
|
||||||
|
stop: &JobStop,
|
||||||
|
undone: &str,
|
||||||
|
) -> Result<CopiedBlobs, RootError> {
|
||||||
use sha2::{Digest, Sha256};
|
use sha2::{Digest, Sha256};
|
||||||
let mut copied = CopiedBlobs {
|
let mut copied = CopiedBlobs {
|
||||||
shas: BTreeSet::new(),
|
shas: BTreeSet::new(),
|
||||||
@@ -2251,6 +2560,8 @@ fn copy_blobs(from: &Path, to: &Path) -> Result<CopiedBlobs, RootError> {
|
|||||||
}
|
}
|
||||||
return Err(stray(&f.path()));
|
return Err(stray(&f.path()));
|
||||||
}
|
}
|
||||||
|
// Once per stored file (one read, one hash, one write).
|
||||||
|
stop.at("file", undone)?;
|
||||||
let bytes = std::fs::read(f.path())?;
|
let bytes = std::fs::read(f.path())?;
|
||||||
if hex::encode(Sha256::digest(&bytes)) != name.to_lowercase() {
|
if hex::encode(Sha256::digest(&bytes)) != name.to_lowercase() {
|
||||||
return Err(RootError::Adopt(format!(
|
return Err(RootError::Adopt(format!(
|
||||||
|
|||||||
@@ -669,6 +669,7 @@ impl Store {
|
|||||||
// open with the journal and the database as they were.
|
// open with the journal and the database as they were.
|
||||||
let mut ledger = Ledger::new(base_currency);
|
let mut ledger = Ledger::new(base_currency);
|
||||||
for line in &lines {
|
for line in &lines {
|
||||||
|
crate::cancel::check()?;
|
||||||
replay_line_into_ledger(&mut ledger, line, base_currency)?;
|
replay_line_into_ledger(&mut ledger, line, base_currency)?;
|
||||||
}
|
}
|
||||||
// Only then is an append cut off mid-line (never acknowledged) set
|
// Only then is an append cut off mid-line (never acknowledged) set
|
||||||
@@ -845,6 +846,7 @@ impl Store {
|
|||||||
// The ledger is already their replay (Store::open): only the
|
// The ledger is already their replay (Store::open): only the
|
||||||
// projection is caught up here.
|
// projection is caught up here.
|
||||||
for line in lines.iter().filter(|l| l.seq > last_applied) {
|
for line in lines.iter().filter(|l| l.seq > last_applied) {
|
||||||
|
crate::cancel::check()?;
|
||||||
apply_line_to_sqlite(&self.conn, line)?;
|
apply_line_to_sqlite(&self.conn, line)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -6273,8 +6275,10 @@ impl Store {
|
|||||||
let lines = read_and_verify_journal(self.journal.path())?;
|
let lines = read_and_verify_journal(self.journal.path())?;
|
||||||
let mut replayed = Ledger::new(self.base_currency);
|
let mut replayed = Ledger::new(self.base_currency);
|
||||||
for line in &lines {
|
for line in &lines {
|
||||||
|
crate::cancel::check()?;
|
||||||
replay_line_into_ledger(&mut replayed, line, self.base_currency)?;
|
replay_line_into_ledger(&mut replayed, line, self.base_currency)?;
|
||||||
}
|
}
|
||||||
|
crate::cancel::check()?;
|
||||||
let a = reports::snapshot(&replayed).map_err(StoreError::Ledger)?;
|
let a = reports::snapshot(&replayed).map_err(StoreError::Ledger)?;
|
||||||
let b = reports::snapshot(&self.ledger).map_err(StoreError::Ledger)?;
|
let b = reports::snapshot(&self.ledger).map_err(StoreError::Ledger)?;
|
||||||
if a != b {
|
if a != b {
|
||||||
@@ -6371,25 +6375,15 @@ impl Store {
|
|||||||
/// healed: none.
|
/// healed: none.
|
||||||
/// 2. IF the projection or ledger diverged (VerifyMismatch): SHOULD copy
|
/// 2. IF the projection or ledger diverged (VerifyMismatch): SHOULD copy
|
||||||
/// the database aside, rebuild from the journal, verify again, and
|
/// the database aside, rebuild from the journal, verify again, and
|
||||||
/// report why it healed.
|
/// report why it healed. A stop asked before the copy leaves no
|
||||||
|
/// copy and no rebuild; from the copy on none is looked at.
|
||||||
/// 3. IF the journal itself fails: SHOULD refuse
|
/// 3. IF the journal itself fails: SHOULD refuse
|
||||||
/// - NEVER touch the journal.
|
/// - NEVER touch the journal.
|
||||||
/// ```
|
/// ```
|
||||||
pub fn verify_and_heal(&mut self) -> Result<VerifyReport, StoreError> {
|
pub fn verify_and_heal(&mut self) -> Result<VerifyReport, StoreError> {
|
||||||
let healed = match self.verify() {
|
let healed = match self.verify() {
|
||||||
Ok(()) => None,
|
Ok(()) => None,
|
||||||
Err(StoreError::VerifyMismatch(why)) => {
|
Err(StoreError::VerifyMismatch(why)) => Some(self.heal_drift(why)?),
|
||||||
let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
|
|
||||||
let keep = self.db_path.with_extension(format!("mismatch.{stamp}"));
|
|
||||||
std::fs::copy(&self.db_path, &keep)?;
|
|
||||||
eprintln!(
|
|
||||||
"wanderbooks: {why}; kept the old database as {} beside it and rebuilt from the journal",
|
|
||||||
keep.file_name().unwrap_or_default().to_string_lossy()
|
|
||||||
);
|
|
||||||
self.rebuild()?;
|
|
||||||
self.verify()?;
|
|
||||||
Some(why)
|
|
||||||
}
|
|
||||||
Err(e) => return Err(e),
|
Err(e) => return Err(e),
|
||||||
};
|
};
|
||||||
let lines = read_and_verify_journal(self.journal.path())?;
|
let lines = read_and_verify_journal(self.journal.path())?;
|
||||||
@@ -6405,6 +6399,37 @@ impl Store {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The healing of a drifted projection (`verify_and_heal`), `why` being
|
||||||
|
/// what verification found. A stop is looked at FIRST, before the
|
||||||
|
/// database is copied aside or anything is touched: a stopped heal
|
||||||
|
/// leaves no `.mismatch` copy and no rebuild (cancel INVARIANT 4). From
|
||||||
|
/// the copy on, nothing looks at a stop: the rebuild and its second
|
||||||
|
/// verification are shielded, because stopped part way the live ledger
|
||||||
|
/// would be left part replayed. Their cost is the copy of the database
|
||||||
|
/// and about six passes over the journal (the rebuild reads and
|
||||||
|
/// chain-checks it, applies it to the database and replays it into the
|
||||||
|
/// ledger; the verification reads and chain-checks it, replays it and
|
||||||
|
/// applies it to a fresh projection), and each stored file read and
|
||||||
|
/// hashed once by the verification: a named term of the books server's
|
||||||
|
/// close bound (ledger-mcp local.rs INVARIANT 10), met only after a
|
||||||
|
/// drift.
|
||||||
|
#[doc(hidden)]
|
||||||
|
pub fn heal_drift(&mut self, why: String) -> Result<String, StoreError> {
|
||||||
|
crate::cancel::check()?;
|
||||||
|
let stamp = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string();
|
||||||
|
let keep = self.db_path.with_extension(format!("mismatch.{stamp}"));
|
||||||
|
std::fs::copy(&self.db_path, &keep)?;
|
||||||
|
eprintln!(
|
||||||
|
"wanderbooks: {why}; kept the old database as {} beside it and rebuilt from the journal",
|
||||||
|
keep.file_name().unwrap_or_default().to_string_lossy()
|
||||||
|
);
|
||||||
|
crate::cancel::shielded(|| -> Result<(), StoreError> {
|
||||||
|
self.rebuild()?;
|
||||||
|
self.verify()
|
||||||
|
})?;
|
||||||
|
Ok(why)
|
||||||
|
}
|
||||||
|
|
||||||
/// The SHA-256 of every stored file the books name (receipts and
|
/// The SHA-256 of every stored file the books name (receipts and
|
||||||
/// documents, withdrawn ones included).
|
/// documents, withdrawn ones included).
|
||||||
pub fn stored_blob_shas(&self) -> Result<Vec<String>, StoreError> {
|
pub fn stored_blob_shas(&self) -> Result<Vec<String>, StoreError> {
|
||||||
@@ -6426,6 +6451,7 @@ impl Store {
|
|||||||
.collect::<Result<_, _>>()?;
|
.collect::<Result<_, _>>()?;
|
||||||
let mut n = 0u64;
|
let mut n = 0u64;
|
||||||
for sha in shas {
|
for sha in shas {
|
||||||
|
crate::cancel::check()?;
|
||||||
self.blobs.get(&sha)?;
|
self.blobs.get(&sha)?;
|
||||||
n += 1;
|
n += 1;
|
||||||
}
|
}
|
||||||
@@ -6449,10 +6475,12 @@ impl Store {
|
|||||||
Self::write_meta(&self.conn, "last_applied_seq", "0")?;
|
Self::write_meta(&self.conn, "last_applied_seq", "0")?;
|
||||||
let lines = read_and_verify_journal(self.journal.path())?;
|
let lines = read_and_verify_journal(self.journal.path())?;
|
||||||
for line in &lines {
|
for line in &lines {
|
||||||
|
crate::cancel::check()?;
|
||||||
apply_line_to_sqlite(&self.conn, line)?;
|
apply_line_to_sqlite(&self.conn, line)?;
|
||||||
}
|
}
|
||||||
self.ledger = Ledger::new(self.base_currency);
|
self.ledger = Ledger::new(self.base_currency);
|
||||||
for line in &lines {
|
for line in &lines {
|
||||||
|
crate::cancel::check()?;
|
||||||
replay_line_into_ledger(&mut self.ledger, line, self.base_currency)?;
|
replay_line_into_ledger(&mut self.ledger, line, self.base_currency)?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
|
|||||||
@@ -28,6 +28,24 @@
|
|||||||
//! 4. No error names a path.
|
//! 4. No error names a path.
|
||||||
//! 5. A token has at most MAX_LIVE grants under way, so what one agent
|
//! 5. A token has at most MAX_LIVE grants under way, so what one agent
|
||||||
//! can keep on the disk is bounded.
|
//! can keep on the disk is bounded.
|
||||||
|
//! 6. Uploads can be closed (`close`, under the lock every change to
|
||||||
|
//! the folder is made under): after it nothing is granted, taken,
|
||||||
|
//! swept, given back or forgotten, by any holder of these uploads
|
||||||
|
//! from before, so a book let go (closed, or replaced by a restore)
|
||||||
|
//! is never touched by a sweep, a late request or a claim dropped
|
||||||
|
//! after, whoever has the book open by then. A file coming in
|
||||||
|
//! (`receive`) is the one change that spans time: each chunk is
|
||||||
|
//! written under that lock, and the rename that keeps the bytes is
|
||||||
|
//! made under it, so once `close` has returned no byte is written
|
||||||
|
//! and none is kept; what the request had written (its `.part`) is
|
||||||
|
//! removed by the request, when it next looks (its next chunk, or
|
||||||
|
//! its end), which is the only thing a request begun before the
|
||||||
|
//! close does to the folder after it, and the removal of a file
|
||||||
|
//! only that request made. A request that is still waiting for its
|
||||||
|
//! next bytes when the close returns is not woken by the type: a
|
||||||
|
//! caller that must not leave that part behind waits for the
|
||||||
|
//! request (the books server's gate does, and cuts one that never
|
||||||
|
//! finishes arriving).
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
use crate::journal::sha256_hex;
|
use crate::journal::sha256_hex;
|
||||||
@@ -36,6 +54,8 @@ use sha2::{Digest, Sha256};
|
|||||||
use std::io::{Read, Write};
|
use std::io::{Read, Write};
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
/// What an upload is told when its books were let go (INVARIANT 6).
|
||||||
|
const CLOSED: &str = "the books aren't open";
|
||||||
/// The uploads' folder, in a book's folder.
|
/// The uploads' folder, in a book's folder.
|
||||||
pub const UPLOADS_DIR: &str = "uploads";
|
pub const UPLOADS_DIR: &str = "uploads";
|
||||||
/// The largest file taken (plan 4.7).
|
/// The largest file taken (plan 4.7).
|
||||||
@@ -99,7 +119,10 @@ impl Claim {
|
|||||||
impl Drop for Claim {
|
impl Drop for Claim {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
if !self.spent {
|
if !self.spent {
|
||||||
let _held = self.uploads.locked();
|
let held = self.uploads.locked();
|
||||||
|
if *held {
|
||||||
|
return;
|
||||||
|
}
|
||||||
let _ = std::fs::rename(
|
let _ = std::fs::rename(
|
||||||
self.uploads.path(&self.id, TAKEN),
|
self.uploads.path(&self.id, TAKEN),
|
||||||
self.uploads.path(&self.id, "bin"),
|
self.uploads.path(&self.id, "bin"),
|
||||||
@@ -169,8 +192,8 @@ pub struct Uploads {
|
|||||||
dir: PathBuf,
|
dir: PathBuf,
|
||||||
/// Held while grants are made or swept and while bytes change name
|
/// Held while grants are made or swept and while bytes change name
|
||||||
/// (INVARIANTS 1, 2, 5): one server serves a book, so this orders
|
/// (INVARIANTS 1, 2, 5): one server serves a book, so this orders
|
||||||
/// every request to its uploads.
|
/// every request to its uploads. True once closed (INVARIANT 6).
|
||||||
lock: std::sync::Arc<std::sync::Mutex<()>>,
|
lock: std::sync::Arc<std::sync::Mutex<bool>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// The longest file name taken, in bytes (most file systems' limit).
|
/// The longest file name taken, in bytes (most file systems' limit).
|
||||||
@@ -287,10 +310,25 @@ impl Uploads {
|
|||||||
Ok(uploads)
|
Ok(uploads)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn locked(&self) -> std::sync::MutexGuard<'_, ()> {
|
fn locked(&self) -> std::sync::MutexGuard<'_, bool> {
|
||||||
self.lock.lock().unwrap_or_else(|e| e.into_inner())
|
self.lock.lock().unwrap_or_else(|e| e.into_inner())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// The lock, if the uploads aren't closed (INVARIANT 6).
|
||||||
|
fn locked_open(&self) -> Result<std::sync::MutexGuard<'_, bool>, UploadError> {
|
||||||
|
let held = self.locked();
|
||||||
|
if *held {
|
||||||
|
return Err(UploadError::Bad(CLOSED.into()));
|
||||||
|
}
|
||||||
|
Ok(held)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Change nothing in these uploads from now on (INVARIANT 6): waits
|
||||||
|
/// for the change being made, if one is.
|
||||||
|
pub fn close(&self) {
|
||||||
|
*self.locked() = true;
|
||||||
|
}
|
||||||
|
|
||||||
fn path(&self, id: &str, ext: &str) -> PathBuf {
|
fn path(&self, id: &str, ext: &str) -> PathBuf {
|
||||||
self.dir.join(format!("{id}.{ext}"))
|
self.dir.join(format!("{id}.{ext}"))
|
||||||
}
|
}
|
||||||
@@ -327,7 +365,7 @@ impl Uploads {
|
|||||||
"purpose is receipt, document, import (a bank or chart CSV) or w9".into(),
|
"purpose is receipt, document, import (a bank or chart CSV) or w9".into(),
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
let _held = self.locked();
|
let _held = self.locked_open()?;
|
||||||
self.sweep_held(now);
|
self.sweep_held(now);
|
||||||
// INVARIANT 5.
|
// INVARIANT 5.
|
||||||
if self.live_for(token, now) >= MAX_LIVE {
|
if self.live_for(token, now) >= MAX_LIVE {
|
||||||
@@ -378,6 +416,7 @@ impl Uploads {
|
|||||||
return Err(UploadError::Unknown(id.chars().take(40).collect()));
|
return Err(UploadError::Unknown(id.chars().take(40).collect()));
|
||||||
}
|
}
|
||||||
let unknown = || UploadError::Unknown(id.to_string());
|
let unknown = || UploadError::Unknown(id.to_string());
|
||||||
|
drop(self.locked_open()?);
|
||||||
let bytes = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?;
|
let bytes = std::fs::read(self.path(id, "json")).map_err(|_| unknown())?;
|
||||||
let grant: Grant = serde_json::from_slice(&bytes).map_err(|_| unknown())?;
|
let grant: Grant = serde_json::from_slice(&bytes).map_err(|_| unknown())?;
|
||||||
if grant.expires <= now {
|
if grant.expires <= now {
|
||||||
@@ -406,7 +445,7 @@ impl Uploads {
|
|||||||
// One request at a time (INVARIANT 2): no bytes kept or held, and
|
// One request at a time (INVARIANT 2): no bytes kept or held, and
|
||||||
// no `.part` of another request.
|
// no `.part` of another request.
|
||||||
let mut out = {
|
let mut out = {
|
||||||
let _held = self.locked();
|
let _held = self.locked_open()?;
|
||||||
if done.exists() || self.path(id, TAKEN).exists() {
|
if done.exists() || self.path(id, TAKEN).exists() {
|
||||||
return Err(UploadError::AlreadySent);
|
return Err(UploadError::AlreadySent);
|
||||||
}
|
}
|
||||||
@@ -434,6 +473,13 @@ impl Uploads {
|
|||||||
break Ok(());
|
break Ok(());
|
||||||
}
|
}
|
||||||
hasher.update(&buf[..n]);
|
hasher.update(&buf[..n]);
|
||||||
|
// Each chunk is written under the lock a close takes
|
||||||
|
// (INVARIANT 6): once the uploads are closed no more bytes go
|
||||||
|
// into the part, which is removed below.
|
||||||
|
let held = self.locked();
|
||||||
|
if *held {
|
||||||
|
break Err(UploadError::Bad(CLOSED.into()));
|
||||||
|
}
|
||||||
if let Err(e) = out.write_all(&buf[..n]) {
|
if let Err(e) = out.write_all(&buf[..n]) {
|
||||||
break Err(e.into());
|
break Err(e.into());
|
||||||
}
|
}
|
||||||
@@ -459,7 +505,11 @@ impl Uploads {
|
|||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
// Kept only if its grant still stands (it may have lapsed,
|
// Kept only if its grant still stands (it may have lapsed,
|
||||||
// or been filed by another request's bytes, meanwhile).
|
// or been filed by another request's bytes, meanwhile).
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
|
if *held {
|
||||||
|
let _ = std::fs::remove_file(&part);
|
||||||
|
return Err(UploadError::Bad(CLOSED.into()));
|
||||||
|
}
|
||||||
let standing = std::fs::read(self.path(id, "json"))
|
let standing = std::fs::read(self.path(id, "json"))
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|b| serde_json::from_slice::<Grant>(&b).ok())
|
.and_then(|b| serde_json::from_slice::<Grant>(&b).ok())
|
||||||
@@ -493,7 +543,7 @@ impl Uploads {
|
|||||||
let taken = self.path(id, TAKEN);
|
let taken = self.path(id, TAKEN);
|
||||||
// The rename is the hold: of two calls, one gets it.
|
// The rename is the hold: of two calls, one gets it.
|
||||||
{
|
{
|
||||||
let _held = self.locked();
|
let _held = self.locked_open()?;
|
||||||
if let Err(e) = std::fs::rename(self.path(id, "bin"), &taken) {
|
if let Err(e) = std::fs::rename(self.path(id, "bin"), &taken) {
|
||||||
return Err(match e.kind() {
|
return Err(match e.kind() {
|
||||||
std::io::ErrorKind::NotFound if taken.exists() => UploadError::InUse,
|
std::io::ErrorKind::NotFound if taken.exists() => UploadError::InUse,
|
||||||
@@ -527,14 +577,19 @@ impl Uploads {
|
|||||||
/// be written): the grant stands, its bytes are to be sent again.
|
/// be written): the grant stands, its bytes are to be sent again.
|
||||||
pub fn discard(&self, id: &str) {
|
pub fn discard(&self, id: &str) {
|
||||||
if is_id(id) {
|
if is_id(id) {
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
let _ = std::fs::remove_file(self.path(id, "bin"));
|
if !*held {
|
||||||
|
let _ = std::fs::remove_file(self.path(id, "bin"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Forget grant `id` and anything kept for it.
|
/// Forget grant `id` and anything kept for it.
|
||||||
fn forget(&self, id: &str) {
|
fn forget(&self, id: &str) {
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
|
if *held {
|
||||||
|
return;
|
||||||
|
}
|
||||||
for ext in ["json", "part", "bin", TAKEN] {
|
for ext in ["json", "part", "bin", TAKEN] {
|
||||||
let _ = std::fs::remove_file(self.path(id, ext));
|
let _ = std::fs::remove_file(self.path(id, ext));
|
||||||
}
|
}
|
||||||
@@ -543,8 +598,10 @@ impl Uploads {
|
|||||||
/// Sweep away every grant that lapsed by `now`, and anything left
|
/// Sweep away every grant that lapsed by `now`, and anything left
|
||||||
/// without one (INVARIANT 3).
|
/// without one (INVARIANT 3).
|
||||||
pub fn sweep(&self, now: i64) {
|
pub fn sweep(&self, now: i64) {
|
||||||
let _held = self.locked();
|
let held = self.locked();
|
||||||
self.sweep_held(now);
|
if !*held {
|
||||||
|
self.sweep_held(now);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// [`Self::sweep`], the lock held.
|
/// [`Self::sweep`], the lock held.
|
||||||
@@ -588,6 +645,141 @@ mod tests {
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Closed, uploads are granted, received, taken, swept and given back
|
||||||
|
/// by no one, and a claim dropped after puts nothing back (INVARIANT 6).
|
||||||
|
#[test]
|
||||||
|
fn closed_uploads_change_nothing() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let u = Uploads::open(dir.path(), NOW).unwrap();
|
||||||
|
let bytes = b"%PDF-1.4 a receipt".to_vec();
|
||||||
|
let g = grant_for(&u, "tok_a", &bytes);
|
||||||
|
u.receive(&g.id, "tok_a", &mut &bytes[..], NOW).unwrap();
|
||||||
|
let received = u.take(&g.id, "tok_a", NOW).unwrap();
|
||||||
|
let seen = || {
|
||||||
|
let mut names: Vec<_> = std::fs::read_dir(dir.path().join(UPLOADS_DIR))
|
||||||
|
.unwrap()
|
||||||
|
.map(|f| f.unwrap().file_name())
|
||||||
|
.collect();
|
||||||
|
names.sort();
|
||||||
|
names
|
||||||
|
};
|
||||||
|
let held = seen();
|
||||||
|
u.close();
|
||||||
|
assert!(
|
||||||
|
u.grant(
|
||||||
|
"tok_a",
|
||||||
|
&sha256_hex(&bytes),
|
||||||
|
bytes.len() as u64,
|
||||||
|
"application/pdf",
|
||||||
|
"r.pdf",
|
||||||
|
"receipt",
|
||||||
|
NOW
|
||||||
|
)
|
||||||
|
.is_err()
|
||||||
|
);
|
||||||
|
assert!(u.receive(&g.id, "tok_a", &mut &bytes[..], NOW).is_err());
|
||||||
|
assert!(u.take(&g.id, "tok_a", NOW).is_err());
|
||||||
|
u.discard(&g.id);
|
||||||
|
u.sweep(NOW + 10 * UPLOAD_TTL);
|
||||||
|
// The call that held the bytes lets go of them, unspent: nothing
|
||||||
|
// is put back, nor forgotten, in a folder that is no longer ours.
|
||||||
|
drop(received);
|
||||||
|
assert_eq!(seen(), held);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A body that hands out `chunks`, one per read, and tells the test
|
||||||
|
/// before each read (its number, from 1) so it can act at an exact
|
||||||
|
/// point of the transfer.
|
||||||
|
struct Feed<'a> {
|
||||||
|
chunks: std::collections::VecDeque<Vec<u8>>,
|
||||||
|
reads: usize,
|
||||||
|
before: Box<dyn FnMut(usize) + 'a>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl std::io::Read for Feed<'_> {
|
||||||
|
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||||
|
self.reads += 1;
|
||||||
|
(self.before)(self.reads);
|
||||||
|
match self.chunks.pop_front() {
|
||||||
|
Some(c) => {
|
||||||
|
buf[..c.len()].copy_from_slice(&c);
|
||||||
|
Ok(c.len())
|
||||||
|
}
|
||||||
|
None => Ok(0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn names_in(dir: &Path) -> Vec<String> {
|
||||||
|
let mut names: Vec<_> = std::fs::read_dir(dir.join(UPLOADS_DIR))
|
||||||
|
.unwrap()
|
||||||
|
.map(|f| f.unwrap().file_name().to_string_lossy().into_owned())
|
||||||
|
.collect();
|
||||||
|
names.sort();
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
|
/// INVARIANT 6, per chunk: a close that comes while a file is coming
|
||||||
|
/// in stops the request at the chunk that follows it. Not one more
|
||||||
|
/// read is made, no byte is written after the close, and the part the
|
||||||
|
/// request had written is removed.
|
||||||
|
#[test]
|
||||||
|
fn a_close_in_the_middle_of_a_file_stops_it_at_the_next_chunk() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let u = Uploads::open(dir.path(), NOW).unwrap();
|
||||||
|
let bytes: Vec<u8> = (0..3000u32).map(|n| (n % 251) as u8).collect();
|
||||||
|
let g = grant_for(&u, "tok_a", &bytes);
|
||||||
|
let mut feed = Feed {
|
||||||
|
chunks: bytes.chunks(1000).map(<[u8]>::to_vec).collect(),
|
||||||
|
reads: 0,
|
||||||
|
before: Box::new(|read| {
|
||||||
|
if read == 2 {
|
||||||
|
u.close();
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
let refused = u.receive(&g.id, "tok_a", &mut feed, NOW).unwrap_err();
|
||||||
|
assert!(refused.to_string().contains("aren't open"), "{refused}");
|
||||||
|
assert_eq!(feed.reads, 2, "the body was read after the close");
|
||||||
|
let left = names_in(dir.path());
|
||||||
|
assert!(
|
||||||
|
!left
|
||||||
|
.iter()
|
||||||
|
.any(|n| n.ends_with(".part") || n.ends_with(".bin")),
|
||||||
|
"{left:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// INVARIANT 6, the last step: a close that comes after the last byte
|
||||||
|
/// and before the bytes are kept keeps nothing (the rename that makes
|
||||||
|
/// them the upload is under the lock a close takes).
|
||||||
|
#[test]
|
||||||
|
fn a_close_between_the_last_byte_and_the_rename_keeps_nothing() {
|
||||||
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
let u = Uploads::open(dir.path(), NOW).unwrap();
|
||||||
|
let bytes = b"%PDF-1.4 a receipt".to_vec();
|
||||||
|
let g = grant_for(&u, "tok_a", &bytes);
|
||||||
|
let mut feed = Feed {
|
||||||
|
chunks: [bytes.clone()].into(),
|
||||||
|
reads: 0,
|
||||||
|
// The second read is the one that finds the end.
|
||||||
|
before: Box::new(|read| {
|
||||||
|
if read == 2 {
|
||||||
|
u.close();
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
let refused = u.receive(&g.id, "tok_a", &mut feed, NOW).unwrap_err();
|
||||||
|
assert!(refused.to_string().contains("aren't open"), "{refused}");
|
||||||
|
let left = names_in(dir.path());
|
||||||
|
assert!(
|
||||||
|
!left
|
||||||
|
.iter()
|
||||||
|
.any(|n| n.ends_with(".part") || n.ends_with(".bin")),
|
||||||
|
"{left:?}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn bytes_sent_as_declared_are_taken_once() {
|
fn bytes_sent_as_declared_are_taken_once() {
|
||||||
let dir = tempfile::tempdir().unwrap();
|
let dir = tempfile::tempdir().unwrap();
|
||||||
|
|||||||
@@ -1734,3 +1734,343 @@ fn a_registry_rewritten_or_a_vault_given_unchecked_is_refused() {
|
|||||||
}
|
}
|
||||||
assert!(p.vault.is_dir() && p.key.is_file());
|
assert!(p.vault.is_dir() && p.key.is_file());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A stop that is asked at `phase` (and the phases a job has asked, in
|
||||||
|
/// order): the job's own look at its phases, raised from the watcher.
|
||||||
|
fn stopping_at(
|
||||||
|
phase: &'static str,
|
||||||
|
) -> (
|
||||||
|
ledger_store::root::JobStop,
|
||||||
|
std::sync::Arc<std::sync::Mutex<Vec<String>>>,
|
||||||
|
) {
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::sync::{Arc, Mutex};
|
||||||
|
let flag = Arc::new(AtomicBool::new(false));
|
||||||
|
let seen = Arc::new(Mutex::new(Vec::<String>::new()));
|
||||||
|
let stop = ledger_store::root::JobStop::new(flag.clone()).with_phase_watch({
|
||||||
|
let (flag, seen) = (flag.clone(), seen.clone());
|
||||||
|
Arc::new(move |p: &str| {
|
||||||
|
seen.lock().unwrap().push(p.to_string());
|
||||||
|
if p == phase {
|
||||||
|
flag.store(true, Ordering::SeqCst);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
});
|
||||||
|
(stop, seen)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// What a job leaves of the root, byte for byte.
|
||||||
|
fn root_files(root: &Root) -> Vec<(PathBuf, Vec<u8>)> {
|
||||||
|
let mut out = snapshot_files(&root.path().join("books"));
|
||||||
|
if root.path().join("legacy").exists() {
|
||||||
|
out.extend(snapshot_files(&root.path().join("legacy")));
|
||||||
|
}
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A job that changes which books the root holds (create, adopt, restore) is
|
||||||
|
/// asked at each of its phases whether it must stop (the books server's
|
||||||
|
/// close), and stopped at any of them leaves the root byte for byte as it
|
||||||
|
/// was: the staging and scratch folders are gone, books it would have
|
||||||
|
/// replaced untouched, `legacy/` as it was. The last phase it asks is the
|
||||||
|
/// look before its point of no return (the renames that put the books in
|
||||||
|
/// place): nothing is asked after, so a stop that comes then is not heeded
|
||||||
|
/// and the job finishes.
|
||||||
|
#[test]
|
||||||
|
fn a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_it_was() {
|
||||||
|
use ledger_store::root::JobStop;
|
||||||
|
let home = tmp("job-stop");
|
||||||
|
let (root, _) = Root::setup(home.path(), None, None).unwrap();
|
||||||
|
// create
|
||||||
|
let before = root_files(&root);
|
||||||
|
let (stop, seen) = stopping_at("start");
|
||||||
|
let e = refused(
|
||||||
|
root.create_book_stoppable(&id("new"), Currency::USD, &stop)
|
||||||
|
.map(|_| ()),
|
||||||
|
);
|
||||||
|
assert!(matches!(e, RootError::Stopped(_)), "{e:?}");
|
||||||
|
assert!(e.to_string().contains("nothing was created"), "{e}");
|
||||||
|
assert_eq!(root_files(&root), before);
|
||||||
|
assert!(root.list_books().unwrap().is_empty());
|
||||||
|
assert!(!root.book_dir(&id("new")).exists(), "its folder was made");
|
||||||
|
assert_eq!(*seen.lock().unwrap(), ["start"]);
|
||||||
|
// adopt
|
||||||
|
let old = tmp("job-stop-old");
|
||||||
|
drop(source_books(old.path(), true));
|
||||||
|
let options = AdoptOptions::default();
|
||||||
|
let phases = [
|
||||||
|
"start", "journal", "copy", "file", "open", "verify", "place",
|
||||||
|
];
|
||||||
|
for phase in phases {
|
||||||
|
let before = root_files(&root);
|
||||||
|
let (stop, seen) = stopping_at(phase);
|
||||||
|
let e = refused(root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop));
|
||||||
|
assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}");
|
||||||
|
assert!(
|
||||||
|
e.to_string().contains("nothing was adopted"),
|
||||||
|
"{phase}: {e}"
|
||||||
|
);
|
||||||
|
assert_eq!(root_files(&root), before, "adopt stopped at {phase}");
|
||||||
|
assert!(root.list_books().unwrap().is_empty(), "{phase}");
|
||||||
|
assert_eq!(seen.lock().unwrap().last().map(String::as_str), Some(phase));
|
||||||
|
}
|
||||||
|
// Never stopped: every phase is asked, in this order, `place` the last.
|
||||||
|
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
|
||||||
|
let flag = std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false));
|
||||||
|
let stop = JobStop::new(flag).with_phase_watch({
|
||||||
|
let seen = seen.clone();
|
||||||
|
std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string()))
|
||||||
|
});
|
||||||
|
root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop)
|
||||||
|
.unwrap();
|
||||||
|
let asked = seen.lock().unwrap().clone();
|
||||||
|
let mut distinct = asked.clone();
|
||||||
|
distinct.dedup();
|
||||||
|
assert_eq!(distinct, phases, "{asked:?}");
|
||||||
|
assert_eq!(asked.last().map(String::as_str), Some("place"), "{asked:?}");
|
||||||
|
// restore, over books that exist: they stay as they are.
|
||||||
|
let dir = root.book_dir(&id("adopted"));
|
||||||
|
let store = Store::open(&dir).unwrap();
|
||||||
|
let source = backed_up(home.path(), &dir, &store).expect("git is installed");
|
||||||
|
drop(store);
|
||||||
|
let git = ledger_store::backup::Git::find().unwrap();
|
||||||
|
let preview = root.restore_preview(&git, &source, &id("adopted")).unwrap();
|
||||||
|
let phases = ["start", "fetch", "copy", "file", "open", "verify", "place"];
|
||||||
|
for phase in phases {
|
||||||
|
let before = root_files(&root);
|
||||||
|
let (stop, seen) = stopping_at(phase);
|
||||||
|
let e = refused(root.restore_stoppable(
|
||||||
|
&git,
|
||||||
|
&source,
|
||||||
|
&id("adopted"),
|
||||||
|
&preview.head,
|
||||||
|
true,
|
||||||
|
&stop,
|
||||||
|
));
|
||||||
|
assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}");
|
||||||
|
assert!(
|
||||||
|
e.to_string().contains("nothing was restored"),
|
||||||
|
"{phase}: {e}"
|
||||||
|
);
|
||||||
|
assert_eq!(root_files(&root), before, "restore stopped at {phase}");
|
||||||
|
assert_eq!(seen.lock().unwrap().last().map(String::as_str), Some(phase));
|
||||||
|
}
|
||||||
|
// The preview too: stopped, nothing left of its clone.
|
||||||
|
let before = root_files(&root);
|
||||||
|
let (stop, _) = stopping_at("fetch");
|
||||||
|
let e = refused(root.restore_preview_stoppable(&git, &source, &id("adopted"), &stop));
|
||||||
|
assert!(matches!(e, RootError::Stopped(_)), "{e:?}");
|
||||||
|
assert_eq!(root_files(&root), before);
|
||||||
|
// Never stopped, a restore asks `place` last and goes through.
|
||||||
|
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
|
||||||
|
let stop = JobStop::new(std::sync::Arc::default()).with_phase_watch({
|
||||||
|
let seen = seen.clone();
|
||||||
|
std::sync::Arc::new(move |p: &str| seen.lock().unwrap().push(p.to_string()))
|
||||||
|
});
|
||||||
|
let r = root
|
||||||
|
.restore_stoppable(&git, &source, &id("adopted"), &preview.head, true, &stop)
|
||||||
|
.unwrap();
|
||||||
|
assert!(r.replaced.is_some());
|
||||||
|
assert_eq!(
|
||||||
|
seen.lock().unwrap().last().map(String::as_str),
|
||||||
|
Some("place")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A folder, name for name and byte for byte: every file and every folder
|
||||||
|
/// in it, with its bytes and its mode.
|
||||||
|
fn tree_exact(dir: &Path) -> Vec<(PathBuf, Option<Vec<u8>>, u32)> {
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut stack = vec![dir.to_path_buf()];
|
||||||
|
while let Some(d) = stack.pop() {
|
||||||
|
for e in std::fs::read_dir(&d).unwrap() {
|
||||||
|
let p = e.unwrap().path();
|
||||||
|
let is_dir = std::fs::symlink_metadata(&p).unwrap().is_dir();
|
||||||
|
out.push((
|
||||||
|
p.strip_prefix(dir).unwrap().to_path_buf(),
|
||||||
|
(!is_dir).then(|| std::fs::read(&p).unwrap()),
|
||||||
|
mode(&p),
|
||||||
|
));
|
||||||
|
if is_dir {
|
||||||
|
stack.push(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
out.sort();
|
||||||
|
out
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An adoption makes the source's lock file when the source has none (INVARIANT
|
||||||
|
/// 5), and the original is to be left as it was: so a lock file the adoption
|
||||||
|
/// itself made is removed on every way out but its success (stopped by a close
|
||||||
|
/// at any phase, refused, or a panic), exactly that file and nothing else; one
|
||||||
|
/// the source already had is never removed, and a success leaves the one it
|
||||||
|
/// made and says so.
|
||||||
|
#[test]
|
||||||
|
fn an_adoption_that_does_not_finish_leaves_no_lock_file_in_the_source() {
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::AtomicBool;
|
||||||
|
let home = tmp("adopt-lock");
|
||||||
|
let (root, _) = Root::setup(home.path(), None, None).unwrap();
|
||||||
|
let old = tmp("adopt-lock-src");
|
||||||
|
drop(source_books(old.path(), true));
|
||||||
|
let lock = old.path().join(ledger_store::LOCK_FILE);
|
||||||
|
std::fs::remove_file(&lock).unwrap();
|
||||||
|
let before = tree_exact(old.path());
|
||||||
|
assert!(
|
||||||
|
before
|
||||||
|
.iter()
|
||||||
|
.all(|(n, ..)| n != Path::new(ledger_store::LOCK_FILE))
|
||||||
|
);
|
||||||
|
let options = AdoptOptions::default();
|
||||||
|
// Stopped at every phase, before the lock is taken and after.
|
||||||
|
for phase in [
|
||||||
|
"start", "journal", "copy", "file", "open", "verify", "place",
|
||||||
|
] {
|
||||||
|
let (stop, _) = stopping_at(phase);
|
||||||
|
let e = refused(root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop));
|
||||||
|
assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}");
|
||||||
|
assert_eq!(
|
||||||
|
tree_exact(old.path()),
|
||||||
|
before,
|
||||||
|
"the source after an adoption stopped at {phase}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Refused after the lock: the books changed since the preview.
|
||||||
|
let wrong = AdoptOptions {
|
||||||
|
expect_head: Some((999, "not the head".into())),
|
||||||
|
..AdoptOptions::default()
|
||||||
|
};
|
||||||
|
let e = refused(root.adopt(old.path(), &id("adopted"), &wrong));
|
||||||
|
assert!(e.to_string().contains("changed since the preview"), "{e}");
|
||||||
|
assert_eq!(tree_exact(old.path()), before, "after a refusal");
|
||||||
|
// A panic, in the middle of the copy.
|
||||||
|
let flag = Arc::new(AtomicBool::new(false));
|
||||||
|
let stop = ledger_store::root::JobStop::new(flag).with_phase_watch(Arc::new(|p: &str| {
|
||||||
|
if p == "verify" {
|
||||||
|
panic!("a panic in the middle of an adoption");
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
let gone = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||||
|
root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop)
|
||||||
|
.map(|_| ())
|
||||||
|
}));
|
||||||
|
assert!(gone.is_err(), "the adoption panicked");
|
||||||
|
assert_eq!(tree_exact(old.path()), before, "after a panic");
|
||||||
|
assert!(root.list_books().unwrap().is_empty());
|
||||||
|
// The lock held while the adoption runs is gone with it: the source can
|
||||||
|
// be taken for writing at once.
|
||||||
|
drop(Store::open(old.path()).unwrap());
|
||||||
|
std::fs::remove_file(&lock).unwrap();
|
||||||
|
// Not removed when it isn't the file the adoption made: a lock file put
|
||||||
|
// there by someone else while the adoption ran (it was swapped at the
|
||||||
|
// last phase) stays.
|
||||||
|
let flag = Arc::new(AtomicBool::new(false));
|
||||||
|
let swap = lock.clone();
|
||||||
|
let stop = ledger_store::root::JobStop::new(flag).with_phase_watch(Arc::new(move |p: &str| {
|
||||||
|
if p == "verify" {
|
||||||
|
std::fs::remove_file(&swap).unwrap();
|
||||||
|
std::fs::write(&swap, b"someone else's").unwrap();
|
||||||
|
panic!("stopped after the swap");
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
let _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
|
||||||
|
root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop)
|
||||||
|
.map(|_| ())
|
||||||
|
}));
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(&lock).unwrap(),
|
||||||
|
b"someone else's",
|
||||||
|
"a lock file the adoption did not make was removed"
|
||||||
|
);
|
||||||
|
std::fs::remove_file(&lock).unwrap();
|
||||||
|
assert_eq!(tree_exact(old.path()), before);
|
||||||
|
// A source that had its lock file keeps it, stopped or not: the folder
|
||||||
|
// is as it was, and the adoption reports it made none.
|
||||||
|
drop(Store::open(old.path()).unwrap());
|
||||||
|
let had = tree_exact(old.path());
|
||||||
|
assert!(
|
||||||
|
had.iter()
|
||||||
|
.any(|(n, ..)| n == Path::new(ledger_store::LOCK_FILE))
|
||||||
|
);
|
||||||
|
for phase in ["copy", "verify", "place"] {
|
||||||
|
let (stop, _) = stopping_at(phase);
|
||||||
|
let e = refused(root.adopt_stoppable(old.path(), &id("adopted"), &options, &stop));
|
||||||
|
assert!(matches!(e, RootError::Stopped(_)), "{phase}: {e:?}");
|
||||||
|
assert_eq!(tree_exact(old.path()), had, "a lock it had, at {phase}");
|
||||||
|
}
|
||||||
|
let report = root.adopt(old.path(), &id("adopted"), &options).unwrap();
|
||||||
|
assert!(!report.source_lock_created);
|
||||||
|
assert_eq!(tree_exact(old.path()), had);
|
||||||
|
// And a success of a source with none leaves the one it made, as before.
|
||||||
|
let fresh = tmp("adopt-lock-src2");
|
||||||
|
drop(source_books(fresh.path(), true));
|
||||||
|
std::fs::remove_file(fresh.path().join(ledger_store::LOCK_FILE)).unwrap();
|
||||||
|
let report = root.adopt(fresh.path(), &id("second"), &options).unwrap();
|
||||||
|
assert!(report.source_lock_created);
|
||||||
|
assert!(fresh.path().join(ledger_store::LOCK_FILE).is_file());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A job waiting for another's turn at making books (they are made one at a
|
||||||
|
/// time, across processes) gives up when it is asked to stop, whatever the
|
||||||
|
/// job holding the turn does: a close can't be held up by a job that is only
|
||||||
|
/// queued. A job that isn't asked to stop waits its turn, and goes through
|
||||||
|
/// when it comes.
|
||||||
|
#[test]
|
||||||
|
fn a_job_waiting_for_its_turn_stops_when_asked_and_otherwise_waits_for_it() {
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
let home = tmp("turn");
|
||||||
|
let (root, _) = Root::setup(home.path(), None, None).unwrap();
|
||||||
|
// Another process's turn: the lock file is held.
|
||||||
|
let turn = std::fs::OpenOptions::new()
|
||||||
|
.create(true)
|
||||||
|
.truncate(false)
|
||||||
|
.write(true)
|
||||||
|
.open(root.path().join("run/books.lock"))
|
||||||
|
.unwrap();
|
||||||
|
turn.lock().unwrap();
|
||||||
|
let flag = Arc::new(AtomicBool::new(false));
|
||||||
|
let waiting = {
|
||||||
|
let flag = flag.clone();
|
||||||
|
let root = root.clone();
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
root.create_book_stoppable(
|
||||||
|
&id("queued"),
|
||||||
|
Currency::USD,
|
||||||
|
&ledger_store::root::JobStop::new(flag),
|
||||||
|
)
|
||||||
|
.map(|_| ())
|
||||||
|
})
|
||||||
|
};
|
||||||
|
// Queued: it has not made its folder, nor stopped, while the turn is
|
||||||
|
// held and nothing asks it to.
|
||||||
|
let by = std::time::Instant::now() + std::time::Duration::from_millis(400);
|
||||||
|
while std::time::Instant::now() < by {
|
||||||
|
assert!(!waiting.is_finished(), "it didn't wait for its turn");
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||||
|
}
|
||||||
|
flag.store(true, Ordering::SeqCst);
|
||||||
|
let by = std::time::Instant::now() + std::time::Duration::from_secs(60);
|
||||||
|
while !waiting.is_finished() {
|
||||||
|
assert!(
|
||||||
|
std::time::Instant::now() < by,
|
||||||
|
"a job waiting for its turn didn't stop when asked"
|
||||||
|
);
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||||
|
}
|
||||||
|
let e = refused(waiting.join().unwrap());
|
||||||
|
assert!(matches!(e, RootError::Stopped(_)), "{e:?}");
|
||||||
|
assert!(e.to_string().contains("nothing was created"), "{e}");
|
||||||
|
assert!(!root.book_dir(&id("queued")).exists());
|
||||||
|
// Not asked: it waits, and goes through when the turn is let go.
|
||||||
|
let other = {
|
||||||
|
let root = root.clone();
|
||||||
|
std::thread::spawn(move || root.create_book(&id("patient"), Currency::USD).map(|_| ()))
|
||||||
|
};
|
||||||
|
std::thread::sleep(std::time::Duration::from_millis(150));
|
||||||
|
assert!(!other.is_finished());
|
||||||
|
drop(turn);
|
||||||
|
other.join().unwrap().unwrap();
|
||||||
|
assert_eq!(root.list_books().unwrap(), vec![id("patient")]);
|
||||||
|
}
|
||||||
@@ -883,6 +883,72 @@ fn vendor_1099_tags_replay_and_project() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A stop asked before a heal begins leaves nothing behind (cancel INVARIANT
|
||||||
|
/// 4, store.rs `heal_drift`): no `.mismatch` copy of the database and no
|
||||||
|
/// rebuild, the database exactly as it was (still drifted), and the stop is
|
||||||
|
/// the answer. Healed with no stop, the same drift heals.
|
||||||
|
#[test]
|
||||||
|
fn a_stop_before_a_heal_leaves_no_copy_and_no_rebuild() {
|
||||||
|
let dir = test_dir("heal-stopped");
|
||||||
|
let mut store = build_books(&dir);
|
||||||
|
let e = store
|
||||||
|
.ledger()
|
||||||
|
.posted_entries()
|
||||||
|
.next()
|
||||||
|
.map(|e| e.id())
|
||||||
|
.unwrap();
|
||||||
|
store
|
||||||
|
.attach_receipt(Some(e), "r.png", "image/png", b"receipt", None)
|
||||||
|
.unwrap();
|
||||||
|
drop(store);
|
||||||
|
let db = dir.join(ledger_store::db_file());
|
||||||
|
let conn = rusqlite::Connection::open(&db).unwrap();
|
||||||
|
conn.execute("UPDATE attachments SET entry_id = NULL", [])
|
||||||
|
.unwrap();
|
||||||
|
drop(conn);
|
||||||
|
let mut store = Store::open(&dir).unwrap();
|
||||||
|
let Err(StoreError::VerifyMismatch(why)) = store.verify() else {
|
||||||
|
panic!("the drift wasn't found");
|
||||||
|
};
|
||||||
|
let files = |dir: &std::path::Path| {
|
||||||
|
let mut names: Vec<String> = std::fs::read_dir(dir)
|
||||||
|
.unwrap()
|
||||||
|
.filter_map(|d| d.ok())
|
||||||
|
.map(|d| d.file_name().to_string_lossy().into_owned())
|
||||||
|
.collect();
|
||||||
|
names.sort();
|
||||||
|
names
|
||||||
|
};
|
||||||
|
let (names, db_bytes) = (files(&dir), std::fs::read(&db).unwrap());
|
||||||
|
{
|
||||||
|
// The stop arrives after the drift was found, before the heal.
|
||||||
|
let _stop = ledger_store::cancel::scope(std::sync::Arc::new(
|
||||||
|
std::sync::atomic::AtomicBool::new(true),
|
||||||
|
));
|
||||||
|
assert!(matches!(
|
||||||
|
store.heal_drift(why.clone()),
|
||||||
|
Err(StoreError::Cancelled)
|
||||||
|
));
|
||||||
|
}
|
||||||
|
assert_eq!(files(&dir), names, "a stopped heal left a copy behind");
|
||||||
|
assert_eq!(
|
||||||
|
std::fs::read(&db).unwrap(),
|
||||||
|
db_bytes,
|
||||||
|
"a stopped heal rebuilt the database"
|
||||||
|
);
|
||||||
|
assert!(
|
||||||
|
matches!(store.verify(), Err(StoreError::VerifyMismatch(_))),
|
||||||
|
"still drifted: nothing was rebuilt"
|
||||||
|
);
|
||||||
|
// Not stopped, the same drift heals, keeping its copy.
|
||||||
|
let report = store.verify_and_heal().unwrap();
|
||||||
|
assert!(report.healed.is_some());
|
||||||
|
assert!(
|
||||||
|
files(&dir).iter().any(|n| n.contains(".mismatch.")),
|
||||||
|
"the divergent database is kept for forensics"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn the_whole_projection_is_checked_and_healed() {
|
fn the_whole_projection_is_checked_and_healed() {
|
||||||
let dir = test_dir("heal");
|
let dir = test_dir("heal");
|
||||||
|
|||||||
@@ -287,6 +287,15 @@ re-verifies the journal.
|
|||||||
|
|
||||||
## The local transport and the Windows arms (`ledger-mcp::ipc`, `ledger-store::winsec`, P11c, D-62)
|
## The local transport and the Windows arms (`ledger-mcp::ipc`, `ledger-store::winsec`, P11c, D-62)
|
||||||
|
|
||||||
|
The books server opens the books of the data root at its start (all, or the
|
||||||
|
ones `--open` names), and opens or closes **one** while it runs (admin
|
||||||
|
requests `open_book` and `close_book`, `ledger-mcp/src/local.rs`
|
||||||
|
INVARIANT 10; plan/p15-app-and-relay.md 3.1): each open book has a gate
|
||||||
|
every request enters before it touches the book, which a close shuts and
|
||||||
|
waits empty, so the app's tab for a company can be its book's open state.
|
||||||
|
`sessions.rs` keeps the per-book board of who is connected (the admin
|
||||||
|
`sessions` request).
|
||||||
|
|
||||||
The books server, the host and everything that talks to them meet on
|
The books server, the host and everything that talks to them meet on
|
||||||
channels only this account can open (plan 3.9). `ledger_mcp::ipc` is the
|
channels only this account can open (plan 3.9). `ledger_mcp::ipc` is the
|
||||||
one seam: `Endpoint` (a socket in the root's `run/` on Unix; the pipe
|
one seam: `Endpoint` (a socket in the root's `run/` on Unix; the pipe
|
||||||
|
|||||||
+147
-1
@@ -267,7 +267,10 @@ reach through the bridge.
|
|||||||
- **Served books** (`wanderbooks server`, started by the host; an agent
|
- **Served books** (`wanderbooks server`, started by the host; an agent
|
||||||
connects with `wanderbooks mcp --book ID`, the bridge: stdio to the
|
connects with `wanderbooks mcp --book ID`, the bridge: stdio to the
|
||||||
agent, the server's socket upstream): every book
|
agent, the server's socket upstream): every book
|
||||||
in the data root, on a socket in the root's private `run/` folder that
|
in the data root that is open (all of them at the start, unless
|
||||||
|
`wanderbooks server --open none|ID[,ID…]` says otherwise; one is opened
|
||||||
|
or closed while the server runs, "Opening and closing one book" below),
|
||||||
|
on a socket in the root's private `run/` folder that
|
||||||
only this account can connect to. Every request carries a bearer token
|
only this account can connect to. Every request carries a bearer token
|
||||||
live for that book (refused 401 without one, 403 with another book's).
|
live for that book (refused 401 without one, 403 with another book's).
|
||||||
Refusals at the door, tool calls, uploads, downloads and exports are
|
Refusals at the door, tool calls, uploads, downloads and exports are
|
||||||
@@ -275,6 +278,12 @@ reach through the bridge.
|
|||||||
book stops taking requests (an upload, download or export is then
|
book stops taking requests (an upload, download or export is then
|
||||||
refused, 503).
|
refused, 503).
|
||||||
- `/b/{book}/mcp`: the book's MCP service. A request is at most 1 MiB.
|
- `/b/{book}/mcp`: the book's MCP service. A request is at most 1 MiB.
|
||||||
|
- A book that exists but is **closed** is refused on every route below
|
||||||
|
and on this one: 503 with `x-wanderbooks-refused: closed` and the words
|
||||||
|
`The books "ID" aren't open: open them in Wanderbooks.` (the bridge
|
||||||
|
hands them to the agent as they are). A book that doesn't exist is 404
|
||||||
|
`no-such-books`; one that failed to open is 503 `not-open` with why.
|
||||||
|
Nothing of a closed book is written, its access log included.
|
||||||
- `PUT /b/{book}/u/{upload}`: an upload's bytes (`books.begin_upload`),
|
- `PUT /b/{book}/u/{upload}`: an upload's bytes (`books.begin_upload`),
|
||||||
from the token that began it; what `wanderbooks upload --book B
|
from the token that began it; what `wanderbooks upload --book B
|
||||||
[--token NAME] UPLOAD FILE` sends. Streamed to the disk, kept only if
|
[--token NAME] UPLOAD FILE` sends. Streamed to the disk, kept only if
|
||||||
@@ -331,6 +340,143 @@ reach through the bridge.
|
|||||||
hidden file and hard-linked in: never a partial file under the real
|
hidden file and hard-linked in: never a partial file under the real
|
||||||
name, never over another file.
|
name, never over another file.
|
||||||
|
|
||||||
|
### Opening and closing one book (plan/p15-app-and-relay.md 3.1, D-77, D-78)
|
||||||
|
|
||||||
|
The desktop app has one tab per company, and a company is reachable by
|
||||||
|
agents exactly while its tab is open, so the books server opens and closes
|
||||||
|
**one** book while it runs. These are requests on the admin socket (the
|
||||||
|
command line sends them: `wanderbooks books open ID`, `wanderbooks books
|
||||||
|
close ID`; `books list` and `doctor` show each book as open, closed, or
|
||||||
|
didn't open, with why). Protocol version 1: the requests are new, the
|
||||||
|
`closed` flag of a listed book defaults to false.
|
||||||
|
|
||||||
|
- `open_book { id }` opens a closed (or failed) book of the data root with
|
||||||
|
exactly the checks of the server's start (verified, a drifted database
|
||||||
|
rebuilt, a format upgrade waited for as at the start). Answers `opened`,
|
||||||
|
`already_open`, `no_such_book`, or `could_not_open` with why (the book
|
||||||
|
stays listed, with that `problem`).
|
||||||
|
- `close_book { id }` answers `closed`, `closed_backup_incomplete` (with
|
||||||
|
why), `was_not_open` or `no_such_book`.
|
||||||
|
In this order: new calls on the book are refused (the door is shut and
|
||||||
|
the book listed closed); the calls running on it finish, on every route
|
||||||
|
(an ordinary call: nothing is killed, nothing is half-done; the calls
|
||||||
|
that can run long are stopped instead, see below); the answers on their way out
|
||||||
|
are sent, for 10 seconds at most (a client that never reads its answer
|
||||||
|
doesn't hold the book open); a request whose body has not been read
|
||||||
|
to its end when that time runs out (counted from the start of the
|
||||||
|
close: an upload or a call that began and stopped sending) is cut: its
|
||||||
|
connection is closed, an upload's part file is removed, nothing of an
|
||||||
|
MCP call reached the journal, and the access log says `cut_by_close`;
|
||||||
|
a call whose body arrived whole and is running is never cut, it
|
||||||
|
finishes; its MCP sessions end (an agent's next
|
||||||
|
request on one gets the "isn't open" words above, and after a reopening
|
||||||
|
a 404 "Session not found", which a client takes as "open a new one"); its
|
||||||
|
last backup is made, as at the server's close, for 60 seconds at most
|
||||||
|
(a drill, or a format upgrade not yet journaled, is stopped when the
|
||||||
|
close begins, at its next look, so it never takes the last backup's
|
||||||
|
turn; its scratch clone is removed and the books are unchanged):
|
||||||
|
a backup still running after that is stopped (git is sent SIGTERM, which
|
||||||
|
makes it remove its own lock files, and killed with all it started only
|
||||||
|
if it hasn't ended after 5 seconds) and waited for to end. The program
|
||||||
|
never writes to or deletes from a backup folder (it is the owner's, and
|
||||||
|
may be shared with other computers or a sync program): a lock git left
|
||||||
|
there when it had to be killed is left in place, recorded in
|
||||||
|
`ops/backup.jsonl` as `lock_left` with its whole path, and the target's
|
||||||
|
backup is marked failed with words naming the file and saying to remove
|
||||||
|
it only when nothing else is using the backup folder (`books.backup`
|
||||||
|
and the close's answer say the same; the next backup that finds the
|
||||||
|
lock gone goes on). In the book's own archive (`archive.git`, private to
|
||||||
|
the program; running git by hand inside it is unsupported) it removes
|
||||||
|
only the locks its own stopped git made, and, at open and when a backup
|
||||||
|
begins, locks older than ten minutes, each recorded `lock_removed`;
|
||||||
|
**What a close stops, and what it waits for.** At its start a close
|
||||||
|
stops the calls and jobs that can do long I/O or loop over a book's
|
||||||
|
whole journal or files, each at its next look: `books.back_up_now` and
|
||||||
|
a backup a timer asked for (git is stopped; the call answers that it was
|
||||||
|
stopped because the books are closing, its access record says
|
||||||
|
`refused: stopped_by_close`, and nothing it was doing is recorded as done;
|
||||||
|
a commit it had made stands), `books.verify` (once per journal line and
|
||||||
|
per stored file; a heal of a drifted database is begun only if no stop
|
||||||
|
was asked before it, then finishes), `books.export_cpa_package` (once per
|
||||||
|
stored file, unless it has journaled a decision, below), a drill, and a
|
||||||
|
format upgrade not yet at its final look (a
|
||||||
|
stop is honoured up to that look; one that arrives after it still
|
||||||
|
upgrades and records success). A stop is scoped to what it concerns. On
|
||||||
|
the admin socket, a close of the book X stops the work on X only: an open
|
||||||
|
of X, and a restore that replaces X. A create, an adoption and a restore
|
||||||
|
that replaces nothing make a new book, which no close of a book is the
|
||||||
|
close of: a close of one book never stops, fails, refuses or delays them,
|
||||||
|
nor an open or a close of another book (each book has its own turn; books
|
||||||
|
are made, adopted and restored one at a time, and a job queued for its
|
||||||
|
turn leaves at once when asked to stop). The server's own close stops
|
||||||
|
every job. A stopped job, before its point of no return (the rename that
|
||||||
|
puts the books in place; create's making of its folder), removes what it
|
||||||
|
wrote (an adoption also removes the lock file it made in the source
|
||||||
|
folder, so the original is left as it was) and leaves the root byte for
|
||||||
|
byte as it was, and answers that it was stopped because the books are
|
||||||
|
closing; after it the job finishes (a rename or two and two directory
|
||||||
|
syncs), and the book is then opened unless that, too, is stopped (it is
|
||||||
|
left closed, and the answer says so). `books.export_cpa_package` with a
|
||||||
|
reason to export (without an audit, with open drafts) journals that
|
||||||
|
decision before it builds, because the package counts it (its README and
|
||||||
|
every footer carry the journal's event count at the build): a close is
|
||||||
|
looked for once, immediately before the first decision is journaled, and
|
||||||
|
a stop then journals nothing; after it the package is made whatever a
|
||||||
|
close does, so no decision is on record for a package that was never
|
||||||
|
made (every refusal is decided before any decision is journaled). Every
|
||||||
|
other call does work bounded by the size of one request and is waited
|
||||||
|
for. Three are the named exceptions to the close's bound, each waited for
|
||||||
|
in full if a close meets it: `books.import_bank_csv` (a file of up to
|
||||||
|
25 MiB is rehearsed whole and then written row by row, each row
|
||||||
|
journaled; worst case, a full import of the largest file accepted),
|
||||||
|
a report or export over the whole journal (CPU on the ledger in memory,
|
||||||
|
not stopped; worst case, one report over the whole book), and a package
|
||||||
|
after its decision is journaled (worst case, one build over the whole
|
||||||
|
book). Otherwise
|
||||||
|
the close is bounded by the sum written in the server's INVARIANT 10
|
||||||
|
(`local.rs`: running calls, the grace, the answers' grace, the stop of a
|
||||||
|
hurried step, the last backup's 60 s, the stop of what is left of it);
|
||||||
|
then nothing of the server's can write
|
||||||
|
to the book: its access log, uploads, exports and backups are closed
|
||||||
|
under the locks their writes go in under, so a handle held from before
|
||||||
|
can never write after a reopening; its store is let go, releasing the
|
||||||
|
writer lock, so another process could open the book. Only then is the
|
||||||
|
close answered: `closed`, or `closed_backup_incomplete` when the last
|
||||||
|
backup wasn't whole (a target failed, or the backup was stopped after
|
||||||
|
its time): the book is closed all the same, and what it holds since the
|
||||||
|
last good backup isn't backed up. Every other book keeps serving, and
|
||||||
|
none of its calls waits for this close. For every call, either it ran
|
||||||
|
completely and is in the journal, or it was refused unrun and nothing of
|
||||||
|
it is; after the answer, no call on that book runs until it is opened
|
||||||
|
again. **A call whose answer was never read** (the client was slow, or
|
||||||
|
gone, and the grace ran out) is the same case as a connection dropped at
|
||||||
|
any other moment: the call ran, and its access record, written before the
|
||||||
|
answer went, says so (outcome and head). Nothing in the journaled tools
|
||||||
|
makes asking again safe: they carry no client key and none checks for a
|
||||||
|
duplicate, so a draft asked for twice is two drafts. A client that
|
||||||
|
reconnects after a close should read the book's state (or the access
|
||||||
|
record, `books.audit`) before it repeats a write. A restore over an open
|
||||||
|
book (`restore --replace`) lets go of the book in the same way (waits for
|
||||||
|
what is inside the book's door, ends its sessions, stops its backups,
|
||||||
|
closes its logs) before it moves the book into `legacy/`; the book is
|
||||||
|
listed closed from the moment the restore begins, so a call that comes
|
||||||
|
meanwhile is told the books aren't open (503, as in a close), never that
|
||||||
|
there are no such books (404).
|
||||||
|
- **The server's own close** (its standard input ends, or SIGTERM) is the
|
||||||
|
same path for every open book at once: at its start every book's door
|
||||||
|
is shut and the cut (above) is set for 10 seconds from that moment; each
|
||||||
|
book is then released as `close_book` releases it. The server exits 0
|
||||||
|
once they are all closed (and the HTTP side has ended); a request that
|
||||||
|
arrives meanwhile is refused as closing (503) and not recorded, the
|
||||||
|
door being shut.
|
||||||
|
- `sessions` lists, for each open book, its live MCP sessions: the token's
|
||||||
|
**name** (never the token, its text or its hash), the client's name and
|
||||||
|
version from `initialize`, the agent's self-report (`books.start`'s
|
||||||
|
`agent`, if it made one), when it connected, how many of its calls are
|
||||||
|
running now, and its last tool with its outcome and time. A session
|
||||||
|
that ended is not listed; nothing is kept across a server restart.
|
||||||
|
`wanderbooks doctor` prints these lines under "Assistants connected".
|
||||||
|
|
||||||
## Server instructions
|
## Server instructions
|
||||||
|
|
||||||
The MCP `initialize` response carries an `instructions` string, the
|
The MCP `initialize` response carries an `instructions` string, the
|
||||||
|
|||||||
@@ -33,7 +33,14 @@ easily backupable, journable":
|
|||||||
ahead, the commit under the store's lock) and pushes it to the
|
ahead, the commit under the store's lock) and pushes it to the
|
||||||
owner's private repository and backup folder, versioned and
|
owner's private repository and backup folder, versioned and
|
||||||
deduplicated, with full history (docs/mcp-interface.md, "Tools —
|
deduplicated, with full history (docs/mcp-interface.md, "Tools —
|
||||||
backups").
|
backups"). The program stops its git gently (SIGTERM first, so git
|
||||||
|
removes its own lock files, and a kill only after 5 seconds), and never
|
||||||
|
writes to or deletes from a backup folder, which is the owner's (shared,
|
||||||
|
perhaps, with another computer or a sync program): a lock git left
|
||||||
|
there after a kill is reported with its path, never removed. The book's
|
||||||
|
own archive (`archive.git`) is private to the program; there it removes
|
||||||
|
only the locks its own stopped git made, and locks older than ten
|
||||||
|
minutes found when the books open or a backup begins.
|
||||||
- **Journable.** It literally is a journal: `{seq, ts, type, payload, prev}`.
|
- **Journable.** It literally is a journal: `{seq, ts, type, payload, prev}`.
|
||||||
Greppable, diffable, replayable. The audit trail isn't a feature bolted
|
Greppable, diffable, replayable. The audit trail isn't a feature bolted
|
||||||
on — it's the storage format.
|
on — it's the storage format.
|
||||||
|
|||||||
+87
-1
@@ -4084,7 +4084,8 @@ it checks are already theorems.
|
|||||||
a medium effort, no claim, a lowered bar read retroactively),
|
a medium effort, no claim, a lowered bar read retroactively),
|
||||||
`a_period_is_attested_on_a_standing_audit`,
|
`a_period_is_attested_on_a_standing_audit`,
|
||||||
`cpa_package_refuses_without_a_counted_audit_unless_a_reason_is_given`
|
`cpa_package_refuses_without_a_counted_audit_unless_a_reason_is_given`
|
||||||
(refused, a reason journaled as a decision, an audit alone not enough, a
|
(refused, a reason journaled as a decision, and none journaled when an open
|
||||||
|
draft then refuses the same package, an audit alone not enough, a
|
||||||
year attested below the whole bar not enough, the whole bar, an entry
|
year attested below the whole bar not enough, the whole bar, an entry
|
||||||
since, `warn`), `audits_wait_for_the_upgrade` (the fixture over the
|
since, `warn`), `audits_wait_for_the_upgrade` (the fixture over the
|
||||||
wire; the package is not held up by an audit it cannot ask for).
|
wire; the package is not held up by an audit it cannot ask for).
|
||||||
@@ -4290,6 +4291,91 @@ that make a group, the reversal skip, the `total > threshold` end),
|
|||||||
`audit::check_split` (`> unit`, not `>=`), `AttestationBar::parse`'s range
|
`audit::check_split` (`> unit`, not `>=`), `AttestationBar::parse`'s range
|
||||||
(1..=64), `reconcilable::reconciliation_due` (`<=` through, `<` reconciled).
|
(1..=64), `reconcilable::reconciliation_due` (`<=` through, `<` reconciled).
|
||||||
|
|
||||||
|
## P15 A1: open and close one book, and who is connected (2026-11-20)
|
||||||
|
|
||||||
|
The server opens and closes one book while it runs (`ledger-mcp/src/local.rs`
|
||||||
|
INVARIANTS 3, 10 to 12; `admin.rs` INVARIANTS 8 and 9; `sessions.rs`). The
|
||||||
|
rule the tests prove: for every call, either it ran completely and is in
|
||||||
|
the journal, or it was refused and nothing of it is; after a close is
|
||||||
|
answered no call on that book runs until it is opened again; and a close of
|
||||||
|
one book never refuses or holds up a call on another.
|
||||||
|
|
||||||
|
| Test | What it proves |
|
||||||
|
|---|---|
|
||||||
|
| `local::tests::a_closed_book_is_refused_as_closed_and_the_other_still_serves` | a closed book's door says `closed` with the words an agent can relay, a name that is no book says `no-such-books`, the other book still passes the door, the list shows closed (not a problem), closing twice is `was_not_open`, opening is `opened` then `already_open`, a name that is no book is `no_such_book` |
|
||||||
|
| `local::tests::a_closed_book_can_be_opened_by_another_program_and_not_by_two` | a close releases the store's writer lock (another `Store::open` succeeds); while another holds it, opening says `another program has these books open` and the book is listed with that problem; once it lets go it opens |
|
||||||
|
| `local::tests::a_close_waits_for_the_requests_inside_and_refuses_the_next` | a close answers only after a request already inside the book's gate has left; a request arriving meanwhile is refused as closed at once; another book's door is not held up |
|
||||||
|
| `local::tests::the_books_open_at_the_start_are_chosen_by_option` | `--open` takes `all`, `none`, or ids, and refuses a bad id |
|
||||||
|
| `local::tests::the_sessions_request_says_who_is_connected_and_never_their_token` | the sessions list: the token's name, the client from `initialize` (known before any call), the agent's self-report, the last call; no token text; an ended session is not listed; a book's sessions end with it and a reopened book has none |
|
||||||
|
| `sessions::tests` (3) | the running count rides in the call's guard; the last call, the client and the agent are kept, masked of any full TIN; a note for an ended session is dropped |
|
||||||
|
| `book_open_close::books_left_closed_at_the_start_say_so_and_open_when_asked` | a real server started with `--open BOOK`: the other book is listed closed and says so on the MCP, download, export and upload routes; a name that is no book is 404; opening serves |
|
||||||
|
| `book_open_close::the_open_option_takes_none_and_refuses_a_book_that_doesnt_exist` | `--open none` leaves every book closed; `--open nobody` exits 2 before opening anything |
|
||||||
|
| `book_open_close::the_sessions_request_names_each_connection_and_never_its_token` | over the real socket: two tokens, two clients, an agent's report, neither token's text nor SHA-256 in the answer, an ended session gone, a close ends the book's sessions |
|
||||||
|
| `book_open_close::closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing` | the hammer: 6 agents on one book (which has a backup target, every timer at 10 ms, and two clients sending bad tokens so refusals are being recorded) and 4 on another make journaled drafts and reads while the first is closed and reopened 12 times, and a maker thread creates up to eight new books and closes and opens a third over and over (every one must be answered as asked: a close of the first never stops, refuses or fails an admin job on another book; a probabilistic check, the deterministic one is `closing_and_opening_one_book_never_…`); every file of the closed book (journal, access log, every ops log, stored files, the backup's repository) is hashed when the close is answered and compared just before the reopening, every cycle; "the other book progressed" waits on that condition, not a sleep; the logs end as whole chains; both journals are replayed afterwards: every acknowledged draft is in its journal exactly once under the id it was told, no refused call left anything, the closed book's journal and access log never moved between the close answer and the reopening, the other book never refused a call and kept answering while the first was closed, and the books replay with gapless ids |
|
||||||
|
| `book_open_close::a_close_doesnt_wait_for_a_clients_open_event_stream` | a client keeps its standalone event stream (a GET) open (known open: its response head has come; no sleep): closing its book still answers at once, not after the grace for answers on their way out (it took 12 s while the stream was counted as an answer, which stalled the bridge in a hand demonstration) |
|
||||||
|
| `local::tests::a_refusal_being_recorded_keeps_its_place_when_its_client_hangs_up` | a request refused at the door has its access record written by a task that keeps its place inside the book's door: with the only blocking thread held and the request's future dropped, the door stays counted, a close waits, and the record is written before it empties (it was uncounted: the record could land after the close, and after a reopening) |
|
||||||
|
| `local::tests::handles_from_before_a_close_do_nothing_after_the_book_is_open_again` | the access log, uploads, exports and backups taken before a close, used after the same book is opened again (a late record, a sweep, a grant, an export, a run, a drill, a format upgrade), write nothing: the reopened book's tree is byte for byte what its own upgrade left, and its backup record is a whole chain (fails when the backups' shut flag and record close are removed) |
|
||||||
|
| `ledger-store` `access::tests::a_closed_log_writes_nothing_and_a_reopened_one_stays_whole`, `uploads::tests::closed_uploads_change_nothing`, `exports::tests::closed_exports_change_nothing_and_give_nothing`, `backup::tests::a_cancelled_git_stops_what_runs_and_starts_nothing` | the closed state of each handle (under the lock its writes go in under), and git's cancel flag (a running command is stopped with all it started, none starts) |
|
||||||
|
| `book_open_close::a_client_that_never_reads_its_answer_cannot_hold_a_close_nor_break_the_log` | a client asks for the 500 KB tools list and never reads it (the answer is stuck in the socket): the close waits the answer grace (shortened to 700 ms) and then answers; the folder doesn't move afterwards; after the reopening the access log is one whole chain |
|
||||||
|
| `book_open_close::a_stalled_upload_body_cannot_hold_a_close_and_leaves_no_part_file` | an upload stops sending half way: the close waits the grace (600 ms), cuts it (connection closed, no part file, no bytes kept, record `cut_by_close`) and answers; the folder stands still; one whole access chain across the reopening (hung before the change) |
|
||||||
|
| `book_open_close::a_stalled_mcp_body_cannot_hold_a_close_and_nothing_of_it_is_journaled` | a `tools/call` whose body stops half way is cut by the close: connection closed, the call is not in the journal, record `cut_by_close` (hung before the change) |
|
||||||
|
| `book_open_close::a_restore_over_an_open_book_is_not_held_by_a_stalled_upload` | a restore over an open book with an upload stalled half way: the upload is cut after the grace, no part file in `legacy/`, the replaced book's log records `cut_by_close`, the restore is answered |
|
||||||
|
| `book_open_close::a_restore_over_an_open_book_waits_for_what_is_inside_it` | (extended) every call while the restore waits for a half-received upload gets 503 and the closed words, never 404 `no such books` (fails when the restore takes the book out of the list before it shuts the door) |
|
||||||
|
| `ledger-store` `uploads::tests::a_close_in_the_middle_of_a_file_stops_it_at_the_next_chunk`, `uploads::tests::a_close_between_the_last_byte_and_the_rename_keeps_nothing`, `exports::tests::a_close_waits_for_a_fetch_that_is_reading` | the types' own claims (INVARIANT 6 of uploads, 5 of exports): a close in the middle of a file stops it at the next chunk (no read after, no part left), a close between the last byte and the rename keeps nothing, and a fetch reads under the lock a close takes (a named pipe holds it inside its read; `close` must not return); each fails with its guard removed |
|
||||||
|
| `book_open_close::a_slow_upload_that_finishes_within_the_grace_is_not_cut` | (made deterministic) the grace is a minute and the rest of the bytes go only after the book is listed closed: the cut waits for the grace (fails with the cut set to fire at once) |
|
||||||
|
| `book_open_close::an_upload_still_arriving_when_the_grace_runs_out_is_cut_however_active_it_is` | the mirror: a client sending 8 KB every 25 ms (not stalled) of a 3 MB body with a 600 ms grace is cut (`cut_by_close`, no part, no bytes kept) and the close answered; driven by the client's condition (it sends until the connection is closed), fails with the cut removed |
|
||||||
|
| `book_open_close::the_servers_own_close_cuts_stalled_requests_and_exits_zero_in_time` | one upload stalled on one book and one MCP body stalled on another, the server's stdin closed: exit code 0 within the bound, both cut after the grace, no part file, nothing journaled, two `cut_by_close` records, every log whole |
|
||||||
|
| `book_open_close::a_backup_and_a_sweep_that_took_their_handles_before_a_close_do_nothing_after_it`, `…a_drill_and_a_sweep…` | `--timer-hold` holds a timer between taking a book's handles and acting; the book is closed meanwhile, stray files planted, the timers go on: the closed book's tree doesn't move; opened again the sweep works (fail with the handles' closed state, the gate's check and the backups' shut flag removed) |
|
||||||
|
| `book_open_close::a_close_stops_a_slow_drill_instead_of_waiting_for_it` | `--slow-steps` makes each phase of a drill wait a minute: the close answers plain `closed` (the last backup was made), within the stated sum, with the drill's scratch clone removed (fails without `hurry`: `closed_backup_incomplete`) |
|
||||||
|
| `book_open_close::a_close_that_stops_git_in_a_commit_or_a_push_leaves_no_lock_and_the_next_backup_succeeds` | REAL git (a wrapper that points git's hooks at a `reference-transaction` hook that waits) stopped inside `init`, a commit and a push to a folder by a close: git is sent SIGTERM and removes its own locks, so none is left in the archive or the folder and the backup's record holds no `lock_removed` or `lock_left` (nothing for the server to clean up), the reopened book backs up with no step by hand, `git fsck --strict` passes on both |
|
||||||
|
| `local::tests::a_close_stops_a_format_upgrade_before_it_is_journaled` | an upgrade held in its backup's proof: the close stops it, it says nothing was upgraded, the journal is byte for byte as before |
|
||||||
|
| `local::tests::a_body_read_to_its_end_is_never_cut_and_one_not_yet_is` | the line of the cut: a body read to its end is never cut (the cut firing, the body asked again), one not read to its end is cut even with bytes on the way |
|
||||||
|
| `ledger-store` `backup::tests::a_git_stopped_by_sigterm_mid_commit_…`, `…_stopped_mid_add_…`, `a_push_stopped_by_sigterm_…`, `a_git_that_ignores_sigterm_…`, `a_git_that_cannot_end_on_sigterm_…`, `a_lock_left_in_a_folder_target_…`, `a_push_stopped_during_the_pack_transfer_…`, `the_archives_age_rule_at_open`, `removal_after_a_stop_goes_through_the_handle_…`, `git_locks::tests` (3) | REAL git stopped inside a commit (HEAD and ref locks), an add (the index lock) and a push to a folder (the target's ref lock): on SIGTERM it removes its own locks and nothing is noted (the grace is long, so a git that needed the kill would show); a git whose group is frozen (SIGSTOP, so SIGTERM stays pending) is killed only after the grace, and the archive's locks it left (not there when the command began) are removed, noted; the folder target's lock is NEVER removed, reported with its whole path (`LockLeft`, `lock_left` with `path`), a lock that was there before the push is untouched and not named, a later push fails by git's words and removes nothing, the next one passes once the test removes the file; a fake git that traps SIGTERM is sent it first (marker) and killed after the grace with all it started; a 48 MiB pack held in the receiving end's `pre-receive` hook (the target's `incoming-` quarantine present) stopped by SIGTERM and by the kill, `git fsck --strict` on both repositories at once; the archive's locks at open: older than ten minutes removed and noted, younger left and said, non-lock names, folders and links untouched; a swapped `refs` folder or archive path after the handle was opened touches nothing outside; the handle module: exact lock names only, regular files only, no link followed |
|
||||||
|
| `ledger-store` `backup::tests::a_drill_stops_inside_the_phase_it_is_told_to_stop_in` | for each phase (clone, replay, verify, blobs, prefix) a stop set as the phase begins ends the drill inside it (the observer sees no later phase), scratch removed; each case fails when the loop's looks inside that phase are removed |
|
||||||
|
| `book_open_close::a_running_call_is_never_cut_when_the_grace_runs_out` | an ordinary call (`books.attach_receipt`, held inside its read of its file, a named pipe) past the grace (body whole) is not cut: it finishes when fed, is answered and recorded `ok`, and then the close is answered (a backup asked for is no longer this call: it is stoppable) |
|
||||||
|
| `book_open_close::a_close_stops_a_running_backup_call_and_says_so` | `books.back_up_now` held in a stalled `git` (never lifted until the call answers): the close stops it, the call is answered that it was stopped because the books are closing, its access record is `refused: stopped_by_close` with no head, the backup record holds `stopped` and no result of its own for the run, git and all it started are gone, the close's last backup is made and the close answers `closed` |
|
||||||
|
| `book_open_close::a_close_stops_a_running_verification_and_a_running_package_and_says_so` | `books.verify` and `books.export_cpa_package` held as they begin by `--timer-hold` (`call:...`), which the close releases: each is stopped at its first look, answers it was stopped, is recorded `refused: stopped_by_close`, the journal is unchanged |
|
||||||
|
| `book_open_close::a_close_stops_the_restore_and_the_open_of_its_own_book_leaving_the_root_as_it_was` | a restore over a book and the open of a book, each held inside a phase (`restore:copy`, `open:start`): its scratch or staging folder is there while held; a close of THAT book stops it, it answers it was stopped, the root's `books/` and `legacy/` are byte for byte as before; asked again it goes through |
|
||||||
|
| `book_open_close::the_servers_close_stops_every_running_admin_job_leaving_the_root_as_it_was` | restore (a new book, and over `acme`), adopt, create and open, each held inside a phase, the server closed with nothing lifting the hold: each answers it was stopped, the root as it was, exit 0; asked again on a new server the first goes through |
|
||||||
|
| `book_open_close::closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_jobs` | a restore over `beta`, a create of `epsilon` and an adoption of `delta` in flight (they make books one at a time, so the later two queue for their turn, and each is held in its phase in its time), `acme` closed (its backup's git stalled, so the close is slow) and opened again around each; during each close `cedar` is opened and closed and answers while the close of `acme` is still not answered; all three finish (`Restored`, `Created`, `Adopted`, no problem), none was stopped. Mutations: a close that raises a server-wide stop fails it (a queued job stopped); one global lock around open and close fails it (the open waits for the close) |
|
||||||
|
| `book_open_close::a_close_never_leaves_a_decision_on_record_for_a_package_that_was_not_made` | `books.export_cpa_package` with `allow_open_drafts`: held as it begins and the book closed, it is stopped and the journal holds no decision; held right after its decision is journaled and the book closed, it is made, handed over (`ok`), one decision. Mutations: no look before the journaling fails the first; a build still stoppable after it fails the second |
|
||||||
|
| `ledger-store` `tests/root.rs::a_job_stopped_at_any_phase_before_its_point_of_no_return_leaves_the_root_as_it_was` | create, adopt, restore (over existing books) and the restore preview stopped at each phase they ask: `Stopped`, the root (`books/`, `legacy/`) byte for byte as before; never stopped, `place` is the last phase asked (nothing after the point of no return) |
|
||||||
|
| `ledger-store` `tests/root.rs::an_adoption_that_does_not_finish_leaves_no_lock_file_in_the_source` | a source with no lock file: the adoption stopped at each of its seven phases, refused after taking the lock (a stale preview head), and panicking in the middle leaves the source folder name for name, byte for byte and mode for mode as it was; a lock file swapped in by someone else during the adoption is not removed; a source that had its lock keeps it (stopped or adopted, `source_lock_created` false); a success of a source with none leaves the one it made and says so. Mutation: no removal fails it |
|
||||||
|
| `ledger-store` `tests/root.rs::a_job_waiting_for_its_turn_stops_when_asked_and_otherwise_waits_for_it` | the turn at making books held (as another process would): a create that isn't asked to stop waits, and stops within seconds once asked (`Stopped`, nothing made); not asked, it goes through when the turn is let go. Mutation: a blocking wait for the turn fails it |
|
||||||
|
| `book_open_close::a_lock_a_kill_leaves_in_the_backup_folder_is_reported_and_never_removed_by_the_server` | REAL git in a push to a folder with its group frozen, so only the kill after the grace ends it: the lock it leaves is still there after the close, recorded `lock_left` with its whole path, no `lock_removed` for the folder, the close's answer and `books.backup` name the file and say when it may be removed, a lock that was there before is neither touched nor named, a later backup fails by git's words and removes nothing, and once the file is removed the backup goes on, `git fsck --strict` on both |
|
||||||
|
| `book_open_close::a_call_whose_answer_was_never_read_is_on_record_as_having_run` | a journaled draft whose client goes without reading: after the close the access log has its record, outcome `ok`, with the head it wrote (INVARIANT 14: a retry isn't made safe by anything; the record says it ran) |
|
||||||
|
| `book_open_close::a_close_is_not_answered_while_its_backup_still_runs` | a book with a folder target and a stand-in `git` on the server's PATH that waits: the close isn't answered before its backup bound (1.2 s), then answers `closed_backup_incomplete`, git and all it started are gone, and lifting the stall makes nothing resume; the reopened book's backup record is a whole chain and it backs up (fails when `shut` is removed: git still runs after the answer) |
|
||||||
|
| `book_open_close::a_close_whose_backup_fails_says_so_and_leaves_nothing_running` | a target whose disk isn't there: `closed_backup_incomplete` naming the failure, quickly, no git run afterwards; the same book with its disk back is answered plainly `closed` |
|
||||||
|
| `book_open_close::an_upload_in_flight_finishes_before_the_close_is_answered` | an upload half received when the close begins: the close isn't answered until it is complete (200), its bytes are kept, its record is written, no `.part` is left, nothing moves afterwards |
|
||||||
|
| `book_open_close::a_restore_over_an_open_book_waits_for_what_is_inside_it` | a replacing restore over a book with an upload half received isn't answered for five seconds (a restore that doesn't wait takes about one); the upload then completes, the replaced book's log in `legacy/` holds it, is whole, no `.part` is left in `legacy/`, and it stands still (fails when the restore lets the store go without the drain) |
|
||||||
|
| `book_open_close::downloads_during_a_close_complete_or_are_refused` | four clients download a 300 KB file in a loop while the book closes: each answer is a whole 200 or a refusal, the number of 200s is the number of download records, and nothing moves after the answer |
|
||||||
|
| `book_open_close::the_timers_never_touch_a_closed_book` | `--timers 5` (sweep, backup look, drill look every 5 ms) on a book with a backup target, closed and opened 8 times: while closed, with strays planted for a sweep to take, not one file moves; open, it is backed up and drilled; the logs end as whole chains |
|
||||||
|
| `commands::tests::doctor_says_who_is_connected` | the doctor's lines for sessions |
|
||||||
|
|
||||||
|
**Waiting on conditions, not on guesses (review of 2026-11-20).** A test of
|
||||||
|
this branch that slept for a fixed time to let "the other side get there"
|
||||||
|
now waits on the condition: `exports::tests::a_close_waits_for_a_fetch_that_is_reading`
|
||||||
|
(it slept 300 ms assuming its thread had reached the named pipe; it now
|
||||||
|
opens a non-blocking writer on the pipe, which succeeds only once a reader
|
||||||
|
has it open); the two MCP bodies that stop half way
|
||||||
|
(`a_stalled_mcp_body_cannot_hold_a_close_…`, the server's-own-close test, the
|
||||||
|
second of which slept 200 ms and the first nothing at all) send their head
|
||||||
|
with `Expect: 100-continue` and their body only on the server's `100
|
||||||
|
Continue`, which the server sends when its handler first reads the body,
|
||||||
|
inside the book's door (`raw::Raw::start_inside`); the late-timer test no
|
||||||
|
longer sleeps 300 ms before its 800 ms window in which nothing may move;
|
||||||
|
`a_close_whose_backup_fails_…` waits out the backup the opening makes by
|
||||||
|
asking for one itself (it could be stopped by the close and leave a lock). The
|
||||||
|
sleeps that remain are negative windows (a close must NOT have been answered;
|
||||||
|
nothing must move), which can only fail when the property is broken, never
|
||||||
|
because the machine is slow, and pacing of a stimulus (the hammer's jitter,
|
||||||
|
a client trickling an upload on purpose).
|
||||||
|
|
||||||
|
**For P12 (mutation targets).** `Gate::enter` (count before looking at `shut`),
|
||||||
|
`Books::release`'s order (the store's close, the gate emptied, sessions ended, the last backup, `Backups::shut`, the logs and files closed, `let_go`) and `Backups::begin`'s count-before-flag, `Backups::shut` (the flag, the turn, the steps drained, the record closed), `ChainLog::close`, `refused_at_door` taking the request's place into its task, the sweep taking the gate, `door`'s entering
|
||||||
|
before it touches the book, and the gate's riding in the upload and
|
||||||
|
download tasks.
|
||||||
|
|
||||||
## P12: the checklists
|
## P12: the checklists
|
||||||
|
|
||||||
The **For P12** paragraphs above (kept where they were written, with their
|
The **For P12** paragraphs above (kept where they were written, with their
|
||||||
|
|||||||
Reference in new issue
Block a user