coven_foundation/locks.rs
1//! Taking a lock whose holder may have panicked (api.md E15).
2//!
3//! A panic while a `Mutex` is held, or an `RwLock` is held for writing,
4//! poisons it: std's way of saying the value may be half-changed. What that
5//! means depends on what the lock guards, so coven takes each lock with the
6//! helper that says it.
7//!
8//! - `lock_unpoisoned`: every change made under the lock is whole before
9//! anything in it can panic, so a poisoned lock holds a whole value and is
10//! used as it is.
11//! - `lock_or_abort`: state the whole process shares, which a change can
12//! leave half-made. No store's handle covers it, so the process ends.
13//! - coven-database's `lock_or_fail_handle`: one open store's state, which a
14//! change can leave half-made. That store's handle fails, and every later
15//! call on it says so.
16
17use std::sync::{Mutex, MutexGuard};
18
19pub use panic_as_error::locks::{
20 into_unpoisoned, lock_unpoisoned, read_unpoisoned, wait_unpoisoned, write_unpoisoned,
21};
22
23/// Lock `mutex`, named `what`: state the whole process shares. A panic while
24/// it was held may have left it half-changed, and nothing narrower than the
25/// process can be failed for it, so the process ends.
26pub fn lock_or_abort<'a, T: ?Sized>(mutex: &'a Mutex<T>, what: &'static str) -> MutexGuard<'a, T> {
27 mutex.lock().unwrap_or_else(|_| abort_on(what))
28}
29
30/// End the process: a panic left `what`, state it shares, half-changed.
31fn abort_on(what: &'static str) -> ! {
32 tracing::error!(what, "a panic left process-wide state half-changed; ending the process");
33 eprintln!("coven: a panic left {what} half-changed; ending the process");
34 std::process::abort()
35}
36
37/// End the process: `what`, state the whole process shares, breaks `rule`.
38/// Nothing narrower than the process can be failed for it, and a drop that
39/// finds it, perhaps during an unwind, must not panic.
40pub(crate) fn abort_broken(what: &'static str, rule: &'static str) -> ! {
41 tracing::error!(what, rule, "process-wide state broke its rule; ending the process");
42 eprintln!("coven: {what} broke its rule that {rule}; ending the process");
43 std::process::abort()
44}
45
46#[cfg(test)]
47#[path = "locks_tests.rs"]
48mod tests;