fix(mcp): a close stops only the work on its own book; each book has its own turn

Closing or opening book A must never block, fail, stop or delay anything on
book B. Two things were server-wide: the stop a close raised for the admin
jobs (a close of one book stopped another's restore, create and adopt, and
refused opens of others while it ran), and the one lifecycle lock a close
held for its whole length (an open of another book waited out the close's
last backup).

Each book now has its own turn and its own stop (Books::lives). A close of 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; only the server's own close stops them
(and every other job: stop_every_job). The stop is lowered while the book's
turn is still held, so an open queued behind a close is not told it was
stopped by a close that is over. The server's close no longer takes a lock:
every admin job has ended by then. "One at a time" remains for making books
(run/books.lock, ledger_store::root INVARIANT 5), where a queued job leaves at
once when stopped.

INVARIANT 10 now names the calls that are neither stoppable nor bounded by one
request, with their worst cases, so the close's bound as written is true:
books.import_bank_csv (a full import of the largest file accepted), a report
over the whole book, and a package after its decision is journaled (one build
over the whole book).

Tests: a restore over beta, a create and an adoption in flight while acme is
closed and opened over and over, its close slow, with another book opened and
closed during each close (mutations: a server-wide stop; one global lock);
a close stops the restore and open of its own book, and the server's close
stops every job; the hammer also makes books and cycles a third book; a close
before a package's decision journals nothing and one after it does not stop it
(mutations: no look before; a stoppable build after). Spec blocks,
docs/mcp-interface.md and docs/testing.md updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Sonnet 5.5 committed 2026-11-20 19:57:16 -07:00
1 parent d05d1ed7ec
commit a66b56c5c7
4 files changed
+935 -236

No files matched your search

+650 -134
View File
@@ -382,7 +382,10 @@ fn agent(
/// replayed and checked: every acknowledged draft is in its book's journal
/// exactly once, no refused call left anything, a closed book's journal
/// and access log never moved between its close answer and its reopening,
/// and no call on the other book was ever refused.
/// and no call on the other book was ever refused. Meanwhile admin jobs on
/// other books (a third book closed and opened over and over, new books made)
/// are all done and none is ever stopped, refused or told of an error by the
/// closings (local.rs INVARIANT 10).
#[test]
fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() {
const CYCLES: usize = 12;
@@ -405,6 +408,7 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() {
);
home.create(A, "USD");
home.create(B, "USD");
home.create("cedar", "USD");
let disk = home.dir.path().join("disk");
std::fs::create_dir_all(&disk).unwrap();
{
@@ -414,6 +418,46 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() {
w.end();
}
let stop = Arc::new(AtomicBool::new(false));
// Admin jobs on other books, while the hammered one is closed and opened:
// a third book closed and opened over and over, and new books made. Every
// one is done as asked; what isn't is said here.
let spared = Arc::new(Mutex::new((0usize, Vec::<String>::new())));
let maker = {
let (home, stop, spared) = (home.clone(), stop.clone(), spared.clone());
std::thread::spawn(move || {
let mut made = 0;
while !stop.load(Ordering::SeqCst) {
let mut said = Vec::new();
if made < 8 {
made += 1;
match home.admin(Request::Create {
id: format!("made-{made}"),
currency: "USD".into(),
}) {
Response::Created { problem: None, .. } => {}
other => said.push(format!("create: {other:?}")),
}
}
match home.admin(Request::CloseBook { id: "cedar".into() }) {
Response::CloseBook {
outcome: CloseOutcome::Closed,
..
} => {}
other => said.push(format!("close: {other:?}")),
}
match home.admin(Request::OpenBook { id: "cedar".into() }) {
Response::OpenBook {
outcome: OpenOutcome::Opened,
..
} => {}
other => said.push(format!("open: {other:?}")),
}
let mut spared = spared.lock().unwrap();
spared.0 += 1;
spared.1.extend(said);
}
})
};
let done = Arc::new(Mutex::new(Vec::new()));
let reads = Arc::new([AtomicUsize::new(0), AtomicUsize::new(0)]);
let mut agents = Vec::new();
@@ -488,6 +532,16 @@ fn closing_and_opening_a_book_over_and_over_loses_and_duplicates_nothing() {
for a in agents.into_iter().chain(refusers) {
a.join().unwrap();
}
maker.join().unwrap();
{
let spared = spared.lock().unwrap();
assert!(spared.0 > 0, "no admin job ran on the other books");
assert_eq!(
spared.1,
Vec::<String>::new(),
"a close of {A} stopped or refused a job on another book"
);
}
assert!(server.close().success());
// Every log is a whole chain after all those closings.
access_of(&home, A);
@@ -2790,6 +2844,140 @@ fn a_close_stops_a_running_verification_and_a_running_package_and_says_so() {
assert!(server.close().success());
}
/// How many decisions the journal of `id` holds.
#[cfg(unix)]
fn decisions_of(home: &Home, id: &str) -> usize {
files_of(home, id)
.0
.iter()
.filter(|l| l.line_type == "decision.recorded")
.count()
}
/// A package that goes with a decision (a reason to export with drafts open
/// or without an audit) is journaled ahead of its build, because the package
/// counts the decision (its README and every footer carry the journal's
/// event count at the build), so the decision may be on record only for a
/// package that is made: a close that begins before the decision is journaled
/// stops the package, and nothing is journaled; one that begins after it
/// doesn't stop it, and the package is handed over whole (tools/reports.rs
/// `export_cpa_package` INVARIANT 4, local.rs INVARIANT 10). The first call is
/// held as it begins and the second right after its decision is journaled, by
/// the server's test knob (`--timer-hold`), which the close's start releases.
#[cfg(unix)]
#[test]
fn a_close_never_leaves_a_decision_on_record_for_a_package_that_was_not_made() {
let home = Home::new("close-package-decision");
let server = Server::start_with(
&home,
&[
"--timer-hold",
"--timers",
"20",
"--backup-quiet",
"3600000",
],
);
home.create(A, "USD");
let run = home.run();
let args = json!({
"cash_accounts": ["1000"],
"allow_open_drafts": {"reason": "the CPA wants it before the receipt comes"}
});
let seen = |name: &str| {
std::fs::read_to_string(run.join("timer-held"))
.unwrap_or_default()
.lines()
.any(|l| l == name)
};
let mut w = Wire::new(&home, A);
w.initialize("owner");
let r = w.call(
"books.add_account",
json!({"code": "1000", "name": "Bank", "account_type": "asset"}),
);
assert_eq!(r["result"]["isError"], json!(false), "{r}");
draft(&mut w, "still open");
// 1. The close begins before the decision is journaled.
let at_start = "call:books.export_cpa_package";
std::fs::write(run.join("timer-hold"), at_start).unwrap();
let mut package = call_unanswered(&home, &w, 7, "books.export_cpa_package", args.clone());
wait_for("the package is held", Duration::from_secs(60), || {
seen(at_start)
});
let started = std::time::Instant::now();
assert_eq!(decisions_of(&home, A), 0);
let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() });
let (status, said) = package.answer();
assert_eq!(status, 200, "{said}");
assert!(
said.contains("stopped because the books are closing"),
"{said}"
);
assert_eq!(
finished("the close", closing),
Response::CloseBook {
id: A.into(),
outcome: CloseOutcome::Closed
}
);
assert!(started.elapsed() < NEVER_LONGER);
assert_eq!(
decisions_of(&home, A),
0,
"a decision is on record for a package that was stopped"
);
let stopped = access_of(&home, A)
.into_iter()
.find(|r| r.access.subject == "books.export_cpa_package")
.expect("the call is on record");
assert_eq!(
stopped.access.result,
ledger_store::access::Outcome::Refused("stopped_by_close".into())
);
// 2. The close begins after it: the package is made all the same.
std::fs::remove_file(run.join("timer-hold")).unwrap();
assert_eq!(open_book(&home, A), OpenOutcome::Opened);
let after = "call:books.export_cpa_package:journaled";
std::fs::write(run.join("timer-hold"), after).unwrap();
let mut w = Wire::new(&home, A);
w.initialize("owner");
let mut package = call_unanswered(&home, &w, 8, "books.export_cpa_package", args);
wait_for(
"the package is held after its decision",
Duration::from_secs(60),
|| seen(after),
);
assert_eq!(
decisions_of(&home, A),
1,
"the decision isn't journaled yet"
);
let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() });
let (status, said) = package.answer();
assert_eq!(status, 200, "{said}");
assert!(
!said.contains("stopped because the books are closing") && said.contains("download"),
"a package with its decision journaled was stopped by a close: {said}"
);
assert_eq!(
finished("the close", closing),
Response::CloseBook {
id: A.into(),
outcome: CloseOutcome::Closed
}
);
assert_eq!(decisions_of(&home, A), 1);
let made = access_of(&home, A)
.into_iter()
.rev()
.find(|r| r.access.subject == "books.export_cpa_package")
.expect("the call is on record");
assert_eq!(made.access.result, ledger_store::access::Outcome::Ok);
std::fs::remove_file(run.join("timer-hold")).unwrap();
assert!(server.close().success());
}
/// The files of `books/` byte for byte (the staging and scratch folders
/// among them), but for the books in `live`: those the server has open and
/// works on by itself (its timers write their archives and logs).
@@ -2801,88 +2989,255 @@ fn root_without(home: &Home, live: &[&str]) -> BTreeMap<String, (u64, String)> {
.collect()
}
/// A job on the admin socket (restore, adopt, create, open) that is running
/// when a close of another book begins is stopped by it, before its point of
/// no return: it answers that it was stopped because the books are closing,
/// what it wrote is removed, and the root is byte for byte as it was (the
/// job's staging or scratch folder is there while it is held, and gone after;
/// asked again with no close, it goes through). Each job is held inside a
/// phase by the server's test knob (`--timer-hold`, `job:phase`), which the
/// close's start releases; the stop is then at the job's next look.
/// The jobs on the admin socket that can run long (restore, adopt, create,
/// open), each held inside a phase by the server's test knob (`--timer-hold`,
/// `job:phase`) until the name is gone or a stop is asked. Returns, for each,
/// the request, the held name, what it says it didn't do, and whether it
/// leaves a folder of its own in `books/` while it is held.
#[cfg(unix)]
struct Jobs {
/// The backup a restore reads (`acme`'s).
repo: PathBuf,
restore_head: (u64, String),
adopt_head: (u64, String),
data: PathBuf,
toml: String,
/// Keeps the adoption's source alive.
_old: tempfile::TempDir,
}
#[cfg(unix)]
impl Jobs {
/// Books `A` (backed up to a folder) and `cedar` (closed) exist; the
/// previews of a restore of that backup and of an adoption are taken.
fn new(home: &Home) -> Self {
home.create(A, "USD");
home.create(CEDAR, "USD");
assert!(matches!(close_book(home, CEDAR), CloseOutcome::Closed));
let mut w = Wire::new(home, A);
w.initialize("owner");
let repo = backed_up_to_folder(home, &mut w, A);
w.end();
let old = tempfile::Builder::new()
.prefix("wb-close-old-")
.tempdir()
.unwrap();
let data = old.path().join("books-data");
drop(ledger_store::Store::create(&data, ledger_core::Currency::USD).unwrap());
let toml = "[company]\nname = \"Acme Widgets LLC\"\n".to_string();
let restore_head = match home.admin(Request::Restore {
id: "gamma".into(),
source: repo.display().to_string(),
replace: false,
confirmed: false,
expect_head: None,
}) {
Response::RestorePreview(p) => p.head,
other => panic!("{other:?}"),
};
let mut jobs = Self {
repo,
restore_head,
adopt_head: (0, String::new()),
data,
toml,
_old: old,
};
jobs.adopt_head = match home.admin(jobs.adopt(false)) {
Response::Preview(p) => p.source_head,
other => panic!("{other:?}"),
};
jobs
}
fn adopt(&self, confirmed: bool) -> Request {
Request::Adopt {
id: "delta".into(),
source: self.data.clone(),
settings_toml: Some(self.toml.clone()),
config_json: None,
vault_dir: None,
vault_key: None,
confirmed,
expect_head: confirmed.then(|| self.adopt_head.clone()),
skip_unknown: true,
}
}
/// A restore of the backup as books `id`, over the books that exist
/// when `replace`.
fn restore(&self, id: &str, replace: bool) -> Request {
Request::Restore {
id: id.into(),
source: self.repo.display().to_string(),
replace,
confirmed: true,
expect_head: Some(self.restore_head.clone()),
}
}
}
#[cfg(unix)]
const CEDAR: &str = "cedar";
/// How many times the server has said it holds `name` (`run/timer-held`).
#[cfg(unix)]
fn times_held(run: &std::path::Path, name: &str) -> usize {
std::fs::read_to_string(run.join("timer-held"))
.unwrap_or_default()
.lines()
.filter(|l| *l == name)
.count()
}
/// A job started on its own thread, and waited for until the server holds it
/// inside the phase `name`; the thread that will have its answer.
#[cfg(unix)]
fn job_held_in(
home: &Home,
name: &str,
job: &Request,
hold: &str,
) -> std::thread::JoinHandle<Response> {
let run = home.run();
std::fs::write(run.join("timer-hold"), hold).unwrap();
let seen = times_held(&run, name);
let running = std::thread::spawn({
let admin = run.join("admin.sock");
let job = job.clone();
move || ledger_mcp::admin::call(&admin, job).unwrap()
});
wait_for(
&format!("{name} is held inside the job"),
Duration::from_secs(300),
|| times_held(&run, name) > seen || running.is_finished(),
);
if running.is_finished() {
panic!(
"{name}: the job ended before it was held: {:?}",
running.join()
);
}
running
}
/// A job on the admin socket (restore, adopt, create, open) is stopped by a
/// close only when the close is of the book the job works on, or is the
/// server's own (local.rs INVARIANT 10). Stopped, it answers that it was
/// stopped because the books are closing, what it wrote is removed, and the
/// root is byte for byte as it was (the job's staging or scratch folder is
/// there while it is held, and gone after; asked again with no close, it
/// goes through). Each job is held inside a phase by the server's test knob
/// (`--timer-hold`, `job:phase`), which the stop releases; the stop is then at
/// the job's next look.
///
/// A restore over a book, and the opening of a book, are work on that book: a
/// close of it stops them. A create, an adoption and a restore that replaces
/// nothing make a NEW book, which no close of a book is the close of: only the
/// server's stops them (the other test below, of closes that stop nothing).
#[cfg(unix)]
#[test]
fn a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_was() {
const C: &str = "cedar";
let home = Home::new("close-stops-jobs");
let server = Server::start_with(
&home,
&[
"--timer-hold",
"--timers",
"20",
"--backup-quiet",
"3600000",
"--answer-grace",
"300",
],
);
home.create(A, "USD");
home.create(C, "USD");
assert!(matches!(close_book(&home, C), CloseOutcome::Closed));
let mut w = Wire::new(&home, A);
w.initialize("owner");
let repo = backed_up_to_folder(&home, &mut w, A);
w.end();
let old = tempfile::Builder::new()
.prefix("wb-close-old-")
.tempdir()
.unwrap();
let data = old.path().join("books-data");
drop(ledger_store::Store::create(&data, ledger_core::Currency::USD).unwrap());
let toml = "[company]\nname = \"Acme Widgets LLC\"\n".to_string();
fn a_close_stops_the_restore_and_the_open_of_its_own_book_leaving_the_root_as_it_was() {
let home = Home::new("close-stops-own-jobs");
let server = Server::start_with(&home, &JOB_ARGS);
let jobs = Jobs::new(&home);
let run = home.run();
let restore_head = match home.admin(Request::Restore {
id: "gamma".into(),
source: repo.display().to_string(),
replace: false,
confirmed: false,
expect_head: None,
}) {
Response::RestorePreview(p) => p.head,
other => panic!("{other:?}"),
};
let adopt = |confirmed: bool, head: Option<(u64, String)>| Request::Adopt {
id: "delta".into(),
source: data.clone(),
settings_toml: Some(toml.clone()),
config_json: None,
vault_dir: None,
vault_key: None,
confirmed,
expect_head: head,
skip_unknown: true,
};
let adopt_head = match home.admin(adopt(false, None)) {
Response::Preview(p) => p.source_head,
other => panic!("{other:?}"),
};
let restore = || Request::Restore {
id: "gamma".into(),
source: repo.display().to_string(),
replace: false,
confirmed: true,
expect_head: Some(restore_head.clone()),
};
// (the held name, the job, what it says it didn't do, whether it leaves
// a folder of its own in `books/` while it is held)
let jobs: Vec<(&str, Request, &str, bool)> = vec![
("restore:copy", restore(), "nothing was restored", true),
// (the held name, the job, what it says it didn't do, the book whose
// close stops it, whether it leaves a folder of its own in `books/`)
let table: Vec<(&str, Request, &str, &str, bool)> = vec![
(
"adopt:open",
adopt(true, Some(adopt_head)),
"nothing was adopted",
"restore:copy",
jobs.restore(A, true),
"nothing was restored",
A,
true,
),
(
"open:start",
Request::OpenBook { id: CEDAR.into() },
"not opened",
CEDAR,
false,
),
];
// The books open and live while a job is held: not compared (the job's
// own book, not yet there, is).
let live = [A, CEDAR];
for (name, job, said, closes, leaves_a_folder) in table {
let before = root_without(&home, &live);
let legacy_before = tree_of(&home.root().join("legacy"));
let running = job_held_in(&home, name, &job, name);
if leaves_a_folder {
assert_ne!(
root_without(&home, &live),
before,
"{name}: the job wrote nothing while held"
);
}
let started = std::time::Instant::now();
// The close of the book the job works on: it stops the job (it
// waits for the job's turn otherwise), and the test lifts nothing.
let closed = close_book(&home, closes);
assert_eq!(closed, CloseOutcome::WasNotOpen, "{name}");
assert!(started.elapsed() < NEVER_LONGER, "{name}");
let answer = running.join().unwrap();
let text = format!("{answer:?}");
assert!(
text.contains("stopped because the books are closing") && text.contains(said),
"{name}: {text}"
);
std::fs::remove_file(run.join("timer-hold")).unwrap();
assert_eq!(
moved(&before, &root_without(&home, &live)),
Vec::<String>::new(),
"{name}: the root isn't as it was"
);
assert_eq!(
tree_of(&home.root().join("legacy")),
legacy_before,
"{name}"
);
// Asked again, with nothing closing, it goes through.
if closes == A {
assert_eq!(open_book(&home, A), OpenOutcome::Opened, "{name}");
}
match (name, home.admin(job)) {
("restore:copy", Response::Restored(_)) | ("open:start", Response::OpenBook { .. }) => {
}
(name, other) => panic!("{name}, asked again: {other:?}"),
}
}
for id in [A, CEDAR] {
assert_eq!(listed(&home, id), (true, false, None), "{id}");
}
assert!(server.close().success());
}
/// The server's own close stops every job on the admin socket, as a close of
/// one book stops the work on that book: each held inside its phase, the
/// server is closed, and each answers that it was stopped because the books
/// are closing, with the root byte for byte as it was, and the server
/// exits 0.
#[cfg(unix)]
#[test]
fn the_servers_close_stops_every_running_admin_job_leaving_the_root_as_it_was() {
let home = Home::new("server-close-stops-jobs");
let mut server = Server::start_with(&home, &JOB_ARGS);
let jobs = Jobs::new(&home);
let table: Vec<(&str, Request, &str, bool)> = vec![
(
"restore:copy",
jobs.restore("gamma", false),
"nothing was restored",
true,
),
(
"restore:copy",
jobs.restore(A, true),
"nothing was restored",
true,
),
("adopt:open", jobs.adopt(true), "nothing was adopted", true),
(
"create:start",
Request::Create {
@@ -2894,42 +3249,18 @@ fn a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_
),
(
"open:start",
Request::OpenBook { id: C.into() },
Request::OpenBook { id: CEDAR.into() },
"not opened",
false,
),
];
let count = |name: &str| {
std::fs::read_to_string(run.join("timer-held"))
.unwrap_or_default()
.lines()
.filter(|l| *l == name)
.count()
};
// The books open and live while a job is held: not compared (the job's
// own book, not yet there, is).
let mut live = vec![A];
for (name, job, said, leaves_a_folder) in jobs {
// The books a server has open when it is closed write to their folders as
// they are let go: `acme`, and `gamma` once the first job is asked again.
let live = [A, "gamma"];
for (n, (name, job, said, leaves_a_folder)) in table.into_iter().enumerate() {
let before = root_without(&home, &live);
let legacy_before = tree_of(&home.root().join("legacy"));
std::fs::write(run.join("timer-hold"), name).unwrap();
let seen = count(name);
let running = std::thread::spawn({
let admin = home.run().join("admin.sock");
let job = job.clone();
move || ledger_mcp::admin::call(&admin, job).unwrap()
});
wait_for(
&format!("{name} is held inside the job"),
Duration::from_secs(300),
|| count(name) > seen || running.is_finished(),
);
if running.is_finished() {
panic!(
"{name}: the job ended before it was held: {:?}",
running.join()
);
}
let running = job_held_in(&home, name, &job, name);
if leaves_a_folder {
assert_ne!(
root_without(&home, &live),
@@ -2938,21 +3269,17 @@ fn a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_
);
}
let started = std::time::Instant::now();
// The close of another book: it stops the job (it waits for the
// job's lock otherwise), and the test lifts nothing.
let closed = close_book(&home, A);
assert_eq!(closed, CloseOutcome::Closed, "{name}");
// Nothing lifts the hold but the server's close.
assert!(server.close().success(), "{name}");
assert!(started.elapsed() < NEVER_LONGER, "{name}");
let answer = running.join().unwrap();
let text = format!("{answer:?}");
let text = format!("{:?}", running.join().unwrap());
assert!(
text.contains("stopped because the books are closing") && text.contains(said),
"{name}: {text}"
);
std::fs::remove_file(run.join("timer-hold")).unwrap();
let after = root_without(&home, &live);
std::fs::remove_file(home.run().join("timer-hold")).unwrap();
assert_eq!(
moved(&before, &after),
moved(&before, &root_without(&home, &live)),
Vec::<String>::new(),
"{name}: the root isn't as it was"
);
@@ -2961,29 +3288,218 @@ fn a_close_stops_a_running_restore_adopt_create_and_open_leaving_the_root_as_it_
legacy_before,
"{name}"
);
assert_eq!(open_book(&home, A), OpenOutcome::Opened, "{name}");
// Asked again, with nothing closing, it goes through.
match (name, home.admin(job)) {
("restore:copy", Response::Restored(_))
| ("adopt:open", Response::Adopted(_))
| ("create:start", Response::Created { .. })
| ("open:start", Response::OpenBook { .. }) => {}
(name, other) => panic!("{name}, asked again: {other:?}"),
server = job_server_again(&home);
// Asked again, with nothing closing, it goes through (the first time
// on this server only: the others would change what comes next).
if n == 0 {
match home.admin(job) {
Response::Restored(_) => {}
other => panic!("{name}, asked again: {other:?}"),
}
// Only `acme` is opened again: `cedar` is closed, as the open
// job after this needs it.
assert_eq!(listed(&home, CEDAR), (false, true, None));
}
live.push(match name {
"restore:copy" => "gamma",
"adopt:open" => "delta",
"create:start" => "epsilon",
_ => C,
});
}
assert_eq!(listed(&home, C), (true, false, None));
for id in ["gamma", "delta", "epsilon"] {
assert_eq!(listed(&home, id), (true, false, None), "{id}");
}
assert!(server.close().success());
}
/// An admin request made on its own thread.
#[cfg(unix)]
fn admin_in_thread(home: &Home, request: Request) -> std::thread::JoinHandle<Response> {
let admin = home.run().join("admin.sock");
std::thread::spawn(move || ledger_mcp::admin::call(&admin, request).unwrap())
}
/// Wait for a thread to finish, failing (never hanging) if it doesn't.
#[cfg(unix)]
fn finished<T>(what: &str, thread: std::thread::JoinHandle<T>) -> T {
wait_for(what, Duration::from_secs(120), || thread.is_finished());
thread.join().unwrap()
}
/// Closing and opening one book never stops, fails, refuses or delays
/// another book's work (local.rs INVARIANT 10, the first rule of the unit),
/// the work on the admin socket included. A restore over `beta`, a create of
/// `epsilon` and an adoption of `delta` are each held in flight (inside a
/// phase, by the server's test knob; they make books one at a time, so the
/// second and third wait for their turn, not yet held, until the one before
/// is let go), and `acme` is closed and opened again while each is: its
/// close is made slow (its backup's git stalls), and during it another book
/// (`cedar`) is opened and closed and answers at once, while the close of
/// `acme` is still not answered. All three jobs finish correctly, none
/// stopped, none told of any error.
#[cfg(unix)]
#[test]
fn closing_and_opening_one_book_never_stops_waits_for_or_refuses_another_books_jobs() {
let home = Home::new("close-spares-other-jobs");
let shim = shim_git(&home);
let mut args = JOB_ARGS.to_vec();
args.extend(["--close-backup", "120000"]);
let server = server_with_shim(&home, &shim, &args);
let jobs = Jobs::new(&home);
home.create(B, "USD");
let run = home.run();
let stalled = || {
std::fs::read_to_string(shim.join("stalled"))
.unwrap_or_default()
.lines()
.count()
};
// One close and reopening of `acme`, while the jobs are held.
let cycle = |why: &str| {
let before = stalled();
std::fs::write(shim.join("stall"), b"").unwrap();
let closing = admin_in_thread(&home, Request::CloseBook { id: A.into() });
wait_for(
&format!("{why}: the close of {A} is in its backup"),
Duration::from_secs(120),
|| stalled() > before || closing.is_finished(),
);
assert!(
!closing.is_finished(),
"{why}: the close of {A} was answered with its backup stalled"
);
// Another book is opened, and closed, while this close is not
// answered: neither waits for it, nor is refused.
let opening = admin_in_thread(&home, Request::OpenBook { id: CEDAR.into() });
assert_eq!(
finished(
&format!("{why}: an open of {CEDAR} during the close of {A}"),
opening
),
Response::OpenBook {
id: CEDAR.into(),
outcome: OpenOutcome::Opened
},
"{why}"
);
assert!(!closing.is_finished(), "{why}: the close was answered");
let shutting = admin_in_thread(&home, Request::CloseBook { id: CEDAR.into() });
assert_eq!(
finished(
&format!("{why}: a close of {CEDAR} during the close of {A}"),
shutting
),
Response::CloseBook {
id: CEDAR.into(),
outcome: CloseOutcome::Closed
},
"{why}"
);
assert!(!closing.is_finished(), "{why}: the close was answered");
std::fs::remove_file(shim.join("stall")).unwrap();
assert_eq!(
finished(&format!("{why}: the close of {A}"), closing),
Response::CloseBook {
id: A.into(),
outcome: CloseOutcome::Closed
},
"{why}"
);
assert_eq!(open_book(&home, A), OpenOutcome::Opened, "{why}");
};
let hold = |names: &[&str]| std::fs::write(run.join("timer-hold"), names.join(",")).unwrap();
// The restore holds the turn; the other two are asked, and wait for it.
let restore = jobs.restore(B, true);
let restoring = job_held_in(
&home,
"restore:copy",
&restore,
"restore:copy,create:start,adopt:open",
);
let create = Request::Create {
id: "epsilon".into(),
currency: "USD".into(),
};
// (The server says every phase it passes, held or not: the books made
// so far have passed `create:start`.)
let seen = |name: &str| times_held(&run, name);
let base = [
("create:start", seen("create:start")),
("adopt:open", seen("adopt:open")),
];
let taken = |name: &str| {
seen(name)
> base
.iter()
.find(|(n, _)| *n == name)
.map(|(_, c)| *c)
.unwrap()
};
let queued = [
("create:start", admin_in_thread(&home, create)),
("adopt:open", admin_in_thread(&home, jobs.adopt(true))),
];
for n in 0..2 {
cycle(&format!("restore over {B}, round {n}"));
assert!(!restoring.is_finished(), "the restore was stopped or ended");
assert!(
queued.iter().all(|(_, q)| !q.is_finished()),
"a queued job was stopped or ended"
);
}
assert!(
!taken("create:start") && !taken("adopt:open"),
"a job took the turn from the restore"
);
// The restore is let go; it finishes.
hold(&["create:start", "adopt:open"]);
match finished("the restore over beta", restoring) {
Response::Restored(r) => assert!(r.problem.is_none(), "{r:?}"),
other => panic!("the restore: {other:?}"),
}
// Then each of the others takes the turn in its time, and is held.
let mut waiting: Vec<(&str, std::thread::JoinHandle<Response>)> = queued.into_iter().collect();
while !waiting.is_empty() {
wait_for(
"a queued job has its turn",
Duration::from_secs(300),
|| waiting.iter().any(|(n, _)| taken(n)),
);
let at = waiting.iter().position(|(n, _)| taken(n)).unwrap();
let (name, job) = waiting.remove(at);
assert!(!job.is_finished(), "{name} ended while it was held");
cycle(name);
assert!(!job.is_finished(), "{name} was stopped or ended");
let names: Vec<&str> = waiting.iter().map(|(n, _)| *n).collect();
hold(&names);
match (name, finished(name, job)) {
("create:start", Response::Created { problem, .. }) => {
assert!(problem.is_none(), "{problem:?}");
}
("adopt:open", Response::Adopted(a)) => assert!(a.problem.is_none(), "{a:?}"),
(name, other) => panic!("{name}: {other:?}"),
}
}
for id in [A, B, "epsilon", "delta"] {
assert_eq!(listed(&home, id), (true, false, None), "{id}");
}
assert_eq!(listed(&home, CEDAR), (false, true, None));
assert!(server.close().success());
}
/// The arguments of the servers the job tests start.
#[cfg(unix)]
const JOB_ARGS: [&str; 7] = [
"--timer-hold",
"--timers",
"20",
"--backup-quiet",
"3600000",
"--answer-grace",
"300",
];
/// A server again, on books made by an earlier one: only `acme` open, as it
/// was left (the other books of the root are closed).
#[cfg(unix)]
fn job_server_again(home: &Home) -> Server {
let mut args = JOB_ARGS.to_vec();
args.extend(["--open", A]);
Server::start_with(home, &args)
}
/// A git that can't end on SIGTERM (its group frozen here, so the signal
/// stays pending) is killed once the grace has run out, and the lock it
/// leaves in a backup FOLDER is the owner's: the server never removes it. It
+242 -86
View File
@@ -82,7 +82,11 @@
//! the books stop. Lapsed uploads and exports are swept every
//! SWEEP_EVERY. Nothing comes in or goes out once the books stopped.
//! 10. One book opens or closes while the server runs, by admin request,
//! one change at a time (create, adopt and restore among them). Open:
//! one change to a book at a time (create, adopt and restore among
//! them): each book has its own turn (`Books::lives`), so a change to
//! one book waits for no other book's, and a close of one book is
//! never held up by, nor holds up, an open, a restore, an adoption or a
//! create of another. Open:
//! a closed (or failed) book of the root is opened and verified as at
//! the start. Close: from the moment it begins, a call on that book is
//! refused at its door, unrun, and not in its journal; a request not
@@ -114,7 +118,8 @@
//! store backup INVARIANT 5; between targets the flag is looked at
//! too); `books.verify` (once per journal line replayed and per
//! stored file hashed); `books.export_cpa_package` (before it
//! builds, and once per stored file it reads); a drill; and a
//! builds, and once per stored file it reads, unless it has
//! journaled a decision: below); a drill; and a
//! format upgrade not yet journaled. A call stopped this way
//! answers its caller that it was stopped because the books are
//! closing, its access record says `refused: stopped_by_close`, and
@@ -132,37 +137,69 @@
//! one that arrives after that look still upgrades and records
//! success (safe: the books are in this version's format, proven
//! backed up first), and finishes (a line and a database row).
//! - on the admin socket, which hold the one lifecycle lock: restore
//! and its preview, adopt and its preview, create, and open. A
//! close of any book, and the server's close, stops them (a job
//! that starts while a close is under way is refused, and asked
//! again after it). Each is stopped, before its point of no return,
//! at its next look (a phase, a stored file, a journal line, a git
//! command): what it wrote is removed (a clone, a staging folder),
//! and the root is byte for byte as it was. The point of no return
//! of restore and adopt is the rename that puts the books in place;
//! after it they finish, which is a rename or two and the sync of
//! two folders (a restore over books moves them to `legacy/` and
//! renames the copy in, both within the root); then the book is
//! opened, which is itself stopped, left closed (its answer says
//! so). Create's is the making of its folder, after which it makes
//! one empty book. Open has none: it stops anywhere (the book is
//! left closed, intact).
//! And a third: `books.export_cpa_package` that is exporting with
//! a reason (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). The close is looked for once, immediately before the first
//! decision is journaled (a stop then journals nothing); from there
//! to the hand-over nothing looks at it, so a decision on record is
//! a package handed over (tools/reports.rs INVARIANT 4). Its build
//! then runs to its end: it is one of the named exceptions below.
//! - on the admin socket: restore and its preview, adopt and its
//! preview, create, and open. A stop is scoped to what it concerns.
//! A close of the book X stops the work on X only: an open of X, and
//! a restore that replaces X (the stoppable calls on X, above, and
//! X's backups and drill, are stopped by the same close). A create,
//! an adoption and a restore that replaces nothing make a NEW book:
//! no close of any book is a close of that, and none stops them; nor
//! does it stop, fail, refuse or delay an open or a close of another
//! book, nor a job queued for its turn at making books (`books.lock`
//! in the root, one at a time across processes: a deliberate rule,
//! ledger_store::root INVARIANT 5, that a queued job leaves at once
//! when it is asked to stop). Only the server's own close stops
//! every job (`Books::stop_every_job`). A job for a book whose close
//! is under way waits for that book's turn, so for the close to end,
//! and is then asked as any other. Each is stopped, before its
//! point of no return, at its next look (a phase, a stored file, a
//! journal line, a git command): what it wrote is removed (a clone,
//! a staging folder, and the lock file an adoption made in the
//! source folder), and the root is byte for byte as it was. The
//! point of no return of restore and adopt is the rename that puts
//! the books in place; after it they finish, which is a rename or
//! two and the sync of two folders (a restore over books moves them
//! to `legacy/` and renames the copy in, both within the root); then
//! the book is opened, which is itself stopped by the server's close
//! (and, for a restore over X, by a close of X), left closed (its
//! answer says so). Create's is the making of its folder, after which
//! it makes one empty book. Open has none: it stops anywhere (the
//! book is left closed, intact).
//! Every other call does work bounded by the size of one request: its
//! arguments, one entry, one stored file (at most MAX_UPLOAD) read,
//! hashed or extracted, one report or export over the ledger that is
//! already in memory (local CPU, no wait on a client, a disk of
//! another's or the network). A call that is neither stoppable nor
//! bounded by one request's size is a defect to be listed here:
//! `books.import_bank_csv` is one (a file of up to MAX_UPLOAD is
//! rehearsed whole, then written row by row, each row journaled: long
//! for a very large file, and it isn't stopped by a close).
//! hashed or extracted (local CPU, no wait on a client, a disk of
//! another's or the network). Three calls are neither stoppable nor
//! bounded by one request's size, and they are the named exceptions to
//! the close's bound below, each with its worst case, which a close that
//! meets it waits for in full (nothing enforces a bound on them: that is
//! a defect to be closed, not a promise kept):
//! - `books.import_bank_csv`: a file of up to MAX_UPLOAD is rehearsed
//! whole, then written row by row, each row journaled, and a close
//! doesn't stop it. Worst case: a full import of the largest file
//! accepted.
//! - a report or export over the whole journal (`books.verify` apart,
//! which is stoppable): CPU on the ledger already in memory, with no
//! look at a stop. Worst case: one report over the whole book.
//! - `books.export_cpa_package` once it has journaled a decision (above).
//! Worst case: one build of the package over the whole book (every
//! stored file it holds read once).
//! The close is bounded, from its start, by the sum of these named
//! terms, each enforced by code, and nothing else:
//! a. T_calls: the longest ordinary call already running with its
//! whole body (bounded by one request, above; none is cut or
//! killed; nothing a client does lengthens it), or, for a
//! stoppable call, T_stop;
//! stoppable call, T_stop, or, for a call of the three named
//! exceptions above, its worst case (the bound is these terms,
//! with that term unbounded by code while one of them runs);
//! b. ANSWER_GRACE for the answers on their way out, counted from
//! when the door is empty (the cut of a body not yet whole is at
//! ANSWER_GRACE from the START of the close, inside (a): a
@@ -303,10 +340,24 @@
//! and the book is closed: the call is answered, git still stalled,
//! that it was stopped because the books are closing; its record says
//! `refused: stopped_by_close`; the close is answered `closed`.
//! 14. A restore of a large backup is running (an admin job) when another
//! book is closed: the restore is stopped, answers that it was stopped
//! because the books are closing, and the root is byte for byte as it
//! was; asked again it goes through.
//! 14. A restore of a large backup over `beta` is running (an admin job)
//! when `beta` is closed: the restore is stopped, answers that it was
//! stopped because the books are closing, and the root is byte for byte
//! as it was; asked again it goes through. The same restore, with
//! another book (`acme`) closed instead, is not stopped.
//! 15. A restore over `beta`, a create of `epsilon` and an adoption of
//! `delta` are in flight (held inside a phase), and `acme`, whose close
//! is made slow, is closed and opened again over and over: all three
//! finish correctly, none is stopped, none is told of an error, an open
//! and a close of `cedar` during a close of `acme` are answered at once,
//! and the close of `acme` is not answered until its own backup is done.
//! 16. The server is closed with a restore, an adoption, a create and an
//! open in flight: each is stopped, and the root is as it was.
//! 17. An adoption of a folder that has no lock file is stopped, fails, or
//! panics: the folder is, name for name and byte for byte, as it was.
//! 18. A package exported with a reason is held as it begins and the book is
//! closed: stopped, no decision journaled. Held right after its decision
//! is journaled and the book closed: the package is made.
//! ```
use crate::admin::{self, Request, Response};
@@ -762,16 +813,16 @@ struct Books {
/// How long after books are first seen open a drill is first looked
/// for (`--drill-first`, for tests; else DRILL_FIRST).
drill_first: Duration,
/// Held through every change to which books are open or exist (create,
/// adopt, restore, open, close): one at a time (INVARIANT 10).
lifecycle: Mutex<()>,
/// Set while any close of a book is under way, and for good once the
/// server closes: the admin jobs that can run long (restore, create,
/// adopt, open) look at it and stop, before their point of no return,
/// leaving the books as they were (INVARIANT 10). `closers` counts the
/// closes under way; the flag is clear when none is.
job_stop: Arc<std::sync::atomic::AtomicBool>,
closers: Mutex<usize>,
/// What each book's changes share: the lock they are made under, and
/// the stop a close of that book raises (INVARIANT 10). One book's
/// changes wait for one book's; no change to one book waits for, stops
/// or fails a change to another.
lives: Mutex<BTreeMap<String, Arc<Life>>>,
/// Set for good when the server closes: the jobs that make a NEW book
/// (a create, an adoption, a restore that replaces nothing) look at it.
/// A close of one book never raises it: those jobs aren't work on that
/// book (INVARIANT 10).
server_stop: Arc<std::sync::atomic::AtomicBool>,
/// How these books are kept from agents (plan 3.8, P9a): what
/// `books.start` reports (`--isolation`).
isolation: Isolation,
@@ -779,16 +830,36 @@ struct Books {
timers: Timers,
}
/// A close of a book under way (`Books::closing_one`).
struct CloseGuard<'a>(&'a Books);
/// What the changes to ONE book share (`Books::lives`): the lock they are
/// made under, one at a time, and the stop a close of that book raises for
/// the jobs that work on it (INVARIANT 10).
struct Life {
/// Held through every change to this book (open, close, a restore that
/// replaces it; a create or an adoption making it).
lock: Mutex<()>,
/// Set while a close of this book is under way, and for good once the
/// server closes: the admin jobs working on this book (an open, a
/// restore over it) look at it and stop, before their point of no
/// return, leaving the books as they were. `closers` counts the closes
/// under way; the flag is clear when none is (and the server isn't
/// closing). Set and cleared under `closers`.
stop: Arc<std::sync::atomic::AtomicBool>,
closers: Mutex<usize>,
}
impl Drop for CloseGuard<'_> {
/// A close of a book under way (`Books::closing_one`).
struct CloseGuard {
life: Arc<Life>,
closing: CancellationToken,
}
impl Drop for CloseGuard {
fn drop(&mut self) {
let mut closers = self.0.closers.lock().unwrap_or_else(|e| e.into_inner());
let mut closers = self.life.closers.lock().unwrap_or_else(|e| e.into_inner());
*closers -= 1;
if *closers == 0 && !self.0.closing.is_cancelled() {
self.0
.job_stop
if *closers == 0 && !self.closing.is_cancelled() {
self.life
.stop
.store(false, std::sync::atomic::Ordering::SeqCst);
}
}
@@ -815,9 +886,8 @@ impl Books {
session_tokens: Mutex::new(BTreeMap::new()),
backup_quiet,
drill_first,
lifecycle: Mutex::new(()),
job_stop: Arc::default(),
closers: Mutex::new(0),
lives: Mutex::new(BTreeMap::new()),
server_stop: Arc::default(),
isolation,
timers: Timers::default(),
}
@@ -829,29 +899,74 @@ impl Books {
self
}
/// A close of a book begins: the admin jobs that can run long stop
/// (INVARIANT 10) until the returned guard is dropped.
fn closing_one(&self) -> CloseGuard<'_> {
let mut closers = self.closers.lock().unwrap_or_else(|e| e.into_inner());
/// What the changes to the book `id` share: made once, kept while
/// anything holds it. A book first met after the server began closing
/// is born stopped.
fn life(&self, id: &BookId) -> Arc<Life> {
let mut lives = self.lives.lock().unwrap_or_else(|e| e.into_inner());
// Forget the books nothing is changing or closing.
lives.retain(|_, life| Arc::strong_count(life) > 1);
lives
.entry(id.as_str().to_string())
.or_insert_with(|| {
Arc::new(Life {
lock: Mutex::new(()),
stop: Arc::new(std::sync::atomic::AtomicBool::new(
self.closing.is_cancelled(),
)),
closers: Mutex::new(0),
})
})
.clone()
}
/// A close of the book `life` belongs to begins: the admin jobs working
/// on THAT book that can run long stop (INVARIANT 10) until the returned
/// guard is dropped. Nothing else is stopped.
fn closing_one(&self, life: &Arc<Life>) -> CloseGuard {
let mut closers = life.closers.lock().unwrap_or_else(|e| e.into_inner());
*closers += 1;
self.job_stop
life.stop.store(true, std::sync::atomic::Ordering::SeqCst);
drop(closers);
CloseGuard {
life: life.clone(),
closing: self.closing.clone(),
}
}
/// The server closes: every stop is raised, for good (INVARIANT 10).
/// `closing` is cancelled first, so a book first met from now is born
/// stopped, and a close of one book ending now clears nothing.
fn stop_every_job(&self) {
self.server_stop
.store(true, std::sync::atomic::Ordering::SeqCst);
CloseGuard(self)
let lives = self.lives.lock().unwrap_or_else(|e| e.into_inner());
for life in lives.values() {
// Under the lock a close's end clears the flag under.
let _closers = life.closers.lock().unwrap_or_else(|e| e.into_inner());
life.stop.store(true, std::sync::atomic::Ordering::SeqCst);
}
}
/// What an admin job that can run long is asked as it goes whether to
/// stop (ledger_store::root `JobStop`). With the test knob
/// `--timer-hold` a job is held inside a phase named `job:phase` (in
/// `run/timer-hold`) until the name is gone or a stop is asked.
fn job(&self, job: &'static str) -> ledger_store::root::JobStop {
let stop = ledger_store::root::JobStop::new(self.job_stop.clone());
/// stop (ledger_store::root `JobStop`): `flag` is the stop of the book
/// it works on, or the server's (`server_stop`) for a job that makes a
/// new book. With the test knob `--timer-hold` a job is held inside a
/// phase named `job:phase` (in `run/timer-hold`) until the name is gone
/// or a stop is asked.
fn job(
&self,
job: &'static str,
flag: &Arc<std::sync::atomic::AtomicBool>,
) -> ledger_store::root::JobStop {
let stop = ledger_store::root::JobStop::new(flag.clone());
if !self.timers.timer_hold {
return stop;
}
let Ok(run) = self.root.run_dir() else {
return stop;
};
let flag = self.job_stop.clone();
let flag = flag.clone();
stop.with_phase_watch(Arc::new(move |phase: &str| {
let name = format!("{job}:{phase}");
{
@@ -1219,16 +1334,20 @@ impl Books {
"that isn't a currency: give its three-letter ISO code, such as USD".into(),
);
};
let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner());
let life = self.life(&id);
let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner());
if self.held().contains_key(id.as_str()) {
return refused(RootError::Exists(id.to_string()));
}
// Stopped by a close before its folder is made, it makes
// nothing; after that it makes one empty book (INVARIANT 10).
match self
.root
.create_book_stoppable(&id, currency, &self.job("create"))
{
// Stopped by the server's close before its folder is made, it
// makes nothing; after that it makes one empty book. A close
// of another book doesn't stop it: it is no work on that book
// (INVARIANT 10).
match self.root.create_book_stoppable(
&id,
currency,
&self.job("create", &self.server_stop),
) {
Ok(store) => {
// Made: kept whether or not it opens (INVARIANT 3).
let book = self.serve(store).unwrap_or_else(Book::Failed);
@@ -1333,11 +1452,16 @@ impl Books {
Ok(id) => id,
Err(e) => return refused(e),
};
let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner());
let life = self.life(&id);
let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner());
if self.held().contains_key(id.as_str()) {
return refused(RootError::Exists(id.to_string()));
}
let stop = self.job("adopt");
// Making a new book: stopped by the server's close, never by
// a close of another book (INVARIANT 10). Once placed, it is
// opened, which a close of THIS book (asked of the id it is
// making) stops, as it stops an open.
let stop = self.job("adopt", &self.server_stop);
let found = match self.root.adopt_preview_stoppable(&source, &stop) {
Ok(found) => found,
Err(e) => return refused(e),
@@ -1545,7 +1669,10 @@ impl Books {
id: id.to_string(),
outcome,
};
let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner());
// This book's turn only: an open of this book waits for a close or a
// restore of THIS book, never for any other book's (INVARIANT 10).
let life = self.life(&id);
let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner());
if self.closing.is_cancelled() {
return Response::Refused("the books are closing: nothing was done".into());
}
@@ -1564,8 +1691,9 @@ impl Books {
Err(e) => return Response::Refused(self.hide(e.to_string())),
},
}
// Stopped by a close (INVARIANT 10): the book stays as it was.
let stop = self.job("open");
// Stopped by a close of this book, or the server's (INVARIANT 10):
// the book stays as it was.
let stop = self.job("open", &life.stop);
if stop.look("start") {
return said(admin::OpenOutcome::CouldNotOpen(OPEN_STOPPED.into()));
}
@@ -1598,10 +1726,27 @@ impl Books {
id: id.to_string(),
outcome,
};
// From now the admin jobs that can run long stop (INVARIANT 10), so
// the lifecycle lock is not held for long by one of them.
let _closing = self.closing_one();
let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner());
// From now the admin jobs working on THIS book that can run long
// stop (INVARIANT 10), so this book's turn is not held for long by
// one of them; no other book's job is touched, and no other book's
// change is waited for.
let life = self.life(&id);
let closing = self.closing_one(&life);
let one = life.lock.lock().unwrap_or_else(|e| e.into_inner());
let answer = self.close_book_held(&id, said);
// The stop is lowered while the turn is still held: an open of this
// book that was waiting for it is not stopped by a close that is over.
drop(closing);
drop(one);
answer
}
/// [`Self::close_one`], the book's turn held.
fn close_book_held(
&self,
id: &BookId,
said: impl Fn(admin::CloseOutcome) -> Response,
) -> Response {
if self.closing.is_cancelled() {
return Response::Refused("the books are closing: nothing was done".into());
}
@@ -1622,8 +1767,8 @@ impl Books {
let rt = tokio::runtime::Handle::current();
// No new call gets in; the book is listed closed.
parts.gate.shut();
self.hold(&id, Book::Closed);
let backup = rt.block_on(self.release(&id, &parts, true, Instant::now(), None));
self.hold(id, Book::Closed);
let backup = rt.block_on(self.release(id, &parts, true, Instant::now(), None));
eprintln!("wanderbooks server: the books {id} were closed");
said(match backup {
None => admin::CloseOutcome::Closed,
@@ -1844,8 +1989,20 @@ impl Books {
Ok(id) => id,
Err(e) => return said(e.to_string()),
};
let _one = self.lifecycle.lock().unwrap_or_else(|e| e.into_inner());
let stop = self.job("restore");
// This book's turn only (INVARIANT 10). What stops the restore: a
// close of THIS book, if it replaces it (that is work on this book);
// else only the server's close (a preview, or a restore making a new
// book, is no work on any book that is closing).
let life = self.life(&id);
let _one = life.lock.lock().unwrap_or_else(|e| e.into_inner());
let stop = self.job(
"restore",
if confirmed && replace {
&life.stop
} else {
&self.server_stop
},
);
let git = match ledger_store::backup::Git::find() {
Ok(git) => git,
Err(e) => return said(e.to_string()),
@@ -3405,9 +3562,7 @@ async fn serve(
// The admin jobs that can run long stop at their next look, before
// their point of no return (INVARIANT 10): the wait below is for jobs
// that are stopping, not for a restore to run its course.
books
.job_stop
.store(true, std::sync::atomic::Ordering::SeqCst);
books.stop_every_job();
let begun = Instant::now();
let cutters: Vec<_> = books
.gates()
@@ -3435,8 +3590,9 @@ async fn serve(
// for BACKUP_AT_CLOSE at most, and its logs, uploads, exports, backups
// and store are closed. The books are let go together: one slow
// backup doesn't hold the others' (each book's own bound is the same).
// (Every admin job has ended: `admin_jobs.wait()` above. No book's
// changes are in flight to be waited for.)
let open: Vec<(BookId, Parts)> = {
let _one = books.lifecycle.lock().unwrap_or_else(|e| e.into_inner());
let open: Vec<(BookId, Parts)> = books
.held()
.iter()