diff --git a/crates/voelin-store/src/keystore.rs b/crates/voelin-store/src/keystore.rs index 185433b..b36da42 100644 --- a/crates/voelin-store/src/keystore.rs +++ b/crates/voelin-store/src/keystore.rs @@ -35,44 +35,99 @@ //! the trait's [`KeyStore::sign_out`] starts with it and then reads the account //! record and the device key with [`KeyStore::get`]: one damaged row, the //! record's own included, would otherwise keep a sign-out from ever finishing, -//! and with it the deletion of the key the user asked to forget. Unbound is the -//! reading that never deletes on a guess: a sign-out neither deletes such a row -//! as a synced copy nor writes it, it stays as it is until a `put` of it writes -//! four good binding columns. A `data` column that is not text (a BLOB, or text -//! of bytes that are no UTF-8) is read as text with the odd bytes replaced, so -//! that a record that cannot be read is deleted by the sign-out, as the trait -//! says, instead of its read failing. A [`KeyStore::put`] of the text that +//! and with it the deletion of the synced copies and of the record, and the +//! forgetting of the key the user asked to forget. Unbound is the reading that +//! never deletes on a guess: a sign-out neither deletes such a row as a synced +//! copy nor writes it, it stays as it is until a `put` of it writes four good +//! binding columns. A `data` column that is not text (a BLOB, or text of bytes +//! that are no UTF-8) is read as text with the odd bytes replaced, so that a +//! record that cannot be read is deleted by the sign-out, as the trait says, +//! instead of its read failing. A [`KeyStore::put`] of the text that //! [`KeyStore::get`] returned for such a row is taken for the data that is //! there: it changes the binding and keeps the stored bytes, where any other //! text replaces them (a TeamSpeak blob still has to be an identity). A row //! whose `kind` or `uid` is not text cannot be addressed, and the list leaves it //! out with a warning. //! +//! # Signing out keeps every key +//! +//! [`KeyStore::sign_out`] is the trait's own, run on this table, and since +//! Phase 2 task 34 of the protocol repository (open question 10 of its accounts +//! design, answered by the owner on 2026-10-24) it keeps every key of the +//! device. The device key stays, unbound and byte for byte, whether it was in +//! use before the account existed or the client made it for the account: +//! `AccountRecord::bound_existing_key` only records which, for the client's +//! wording, and no rule reads it. At every host without accounts that the user +//! reached with it, either key is the user's identity, and deleting it would +//! lose their servers, roles and memberships there. The identities that only +//! this device holds (a TeamSpeak identity of custody `DEVICE`, one the user +//! kept local) are unbound and kept as well. +//! +//! What a sign-out deletes is not a key of the device: the synced copies of +//! integration secrets, which the account service holds and every device can +//! fetch again (a copy of a TeamSpeak identity is a private key, and is deleted +//! like one, see below), and the account record, which holds no secret. A +//! sign-out does not release the device key at the account service either: the +//! key stays registered with the account there. The release is its own +//! operation, see below. +//! +//! # Forgetting the device's identity +//! +//! "Forget this device's identity" is the user's explicit choice and the only +//! deletion of a key of the device; the UI offers to export the key first and +//! asks before it deletes. +//! +//! - Signed in, it is a sign-out with [`DeviceKeyChoice::Forget`] and the uid of +//! the device key. The caller names the key, because the key goes before the +//! record is read: a record that cannot be read does not keep it. +//! - Signed out, or with a key that no account ever bound, it is +//! [`KeyStore::remove`] of `(KIND_VOELIN, uid)`; a TeamSpeak identity is +//! [`Store::delete_identity`]. Neither looks at an account record, so a UI +//! that forgets the device key of the account it is signed in to does it +//! through the sign-out, not through `remove`. +//! +//! The store has no call that exports, because it would only wrap what the +//! caller can read before it deletes: a Voelin key is +//! `KeyStore::voelin_key(uid)` followed by `IdentityKey::to_pkcs8` (the DER that +//! `voelin_identity::FileSigner` reads back; the buffer is zeroized when it is +//! dropped), and a TeamSpeak identity is `Store::identity(id)` followed by +//! `voelin_core::ts::identity::export` or `write_export`. The same two calls, +//! with [`KeyStore::list`] for the `voelin` rows, serve the dialog that deletes +//! the account: it offers an export of the device keys before the service is +//! asked. +//! +//! # Deleted keys leave no trace +//! //! The rows are private keys, so a removed row is not left behind in the file: //! every connection sets `secure_delete`, which makes SQLite overwrite what it //! deletes, and [`KeyStore::remove`] truncates the write-ahead log after it, as //! [`Store::delete_identity`] does, so that the frame of the log that held the -//! page with the key is gone too. [`KeyStore::sign_out`], which deletes with -//! `remove`, truncates the log once, after its last step, not after each -//! removal. The checkpoint waits for another connection for a moment at most -//! (`Store::truncate_wal`): one that keeps reading an old snapshot blocks it, -//! and then the removal still succeeds and a warning says that the deleted -//! bytes may stay in the log file, until a later checkpoint truncates the log, -//! later writes overwrite those frames, or the last connection to the database -//! closes and the log is deleted. +//! page with the key is gone too. A forgotten key needs exactly that. So does +//! the one deletion a sign-out still makes of a key: a synced copy of a +//! TeamSpeak identity, and with `Forget` the device key itself. The sign-out +//! deletes with `remove` on a `SignOutPass` and truncates the log once, after +//! its last step, not after each removal; one that deletes nothing (the record +//! was gone, no copies) truncates nothing. The checkpoint waits for another +//! connection for a moment at most (`Store::truncate_wal`): one that keeps +//! reading an old snapshot blocks it, and then the removal still succeeds and a +//! warning says that the deleted bytes may stay in the log file, until a later +//! checkpoint truncates the log, later writes overwrite those frames, or the +//! last connection to the database closes and the log is deleted. //! -//! The device key is never a synced copy. The account record names the Voelin key -//! that is the installation's device key, and [`KeyStore::sign_out`] deletes -//! every identity bound with `synced = true` in its first step, before it reads -//! the record, so a key stored that way would be deleted whatever the record -//! says (a key that predates the account is to be kept). The store therefore -//! refuses, with an error that says why, a [`KeyStore::put`] of a `voelin` blob -//! with `synced = true` while an account record names its uid as the device, or -//! while a record cannot be read, because then it cannot tell; and a put of an +//! # The device key is never a synced copy +//! +//! A sign-out keeps the device key, but its first step deletes every identity +//! bound with `synced = true`, before it reads the account record that names +//! the device key. A device key stored that way would be deleted by that step, +//! whether it predates the account or not, which is what the rule that a +//! sign-out keeps every device key forbids. The store therefore refuses, with an +//! error that says why, a [`KeyStore::put`] of a `voelin` blob with +//! `synced = true` while an account record names its uid as the device, or while +//! a record cannot be read, because then it cannot tell; and a put of an //! account record that names a key which is stored as a synced copy. A binding -//! with `synced = false` is accepted: a sign-out unbinds such a key and then -//! follows the record. The check and the write are done under the store's lock; -//! a second process writing the same file at the same moment is not covered. +//! with `synced = false` is accepted: a sign-out unbinds such a key and keeps +//! it. The check and the write are done under the store's lock; a second +//! process writing the same file at the same moment is not covered. //! //! A TeamSpeak blob that is refused says why in words that carry none of its //! input: its `data` is the identity's private key, and an error reaches log @@ -136,8 +191,10 @@ const PUT: &str = "INSERT INTO identities /// access to the TeamSpeak methods of the same connection. /// /// [`KeyStore::sign_out`] and the rest of the trait's provided methods work as -/// `voelin-identity` defines them, on top of the five methods here; the -/// sign-out only truncates the write-ahead log once, at its end. +/// `voelin-identity` defines them, on top of the five methods here: a sign-out +/// keeps every key of the device (only [`DeviceKeyChoice::Forget`] deletes the +/// device key), and only truncates the write-ahead log once, at its end, when +/// it deleted something. pub struct SqliteKeyStore { store: Mutex, } @@ -270,10 +327,13 @@ impl KeyStore for SqliteKeyStore { /// The trait's sign-out, with the log truncated once after its last step /// instead of after each of its removals: it removes up to a handful of - /// rows, and a checkpoint that another connection blocks costs a moment + /// rows (the synced copies, the account record and, with + /// [`DeviceKeyChoice::Forget`], the device key; every other key stays), and + /// a checkpoint that another connection blocks costs a moment /// (`Store::truncate_wal`) each time. The steps are the trait's own; they /// run on a `SignOutPass`, which deletes like [`Self::remove`] and leaves - /// the checkpoint to this method. + /// the checkpoint to this method. A sign-out that deleted nothing does not + /// checkpoint. fn sign_out(&self, account: &Uid, device_key: DeviceKeyChoice) -> KsResult { let pass = SignOutPass { store: self, deleted: AtomicBool::new(false) }; let outcome = KeyStore::sign_out(&pass, account, device_key); @@ -299,7 +359,10 @@ fn delete_row(store: &Store, kind: &str, uid: &str) -> KsResult { /// A [`SqliteKeyStore`] for the length of one [`KeyStore::sign_out`]: the same /// rows, but `remove` only notes that it deleted something, so that the sign-out -/// truncates the log once at its end. +/// truncates the log once at its end. What a sign-out removes is the synced +/// copies of integration secrets, the account record and, when the user chose +/// to forget it, the device key; unbinding goes through `put`, which deletes +/// nothing. struct SignOutPass<'a> { store: &'a SqliteKeyStore, /// Whether a row was deleted. @@ -470,26 +533,28 @@ enum Refused { /// `uid` is unique across kinds in this table. #[error("the uid {uid:?} is already stored as an identity of kind {kind:?}")] UidHeld { uid: String, kind: String }, - /// The Voelin key is the device key of an account record. A sign-out - /// deletes a synced copy without reading the record, so the key the record - /// says to keep would be deleted. + /// The Voelin key is the device key of an account record. A sign-out keeps + /// the device key, but it deletes a synced copy without reading the record, + /// so a device key stored as one would be deleted all the same. #[error( "the Voelin key {uid:?} is the device key of the account record {record:?} and cannot be \ - stored as a synced copy (synced = true): a sign-out would delete it whatever the record says" + stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \ + reads the record, so it would delete the device key that it keeps" )] SyncedDeviceKey { uid: String, record: String }, /// An account record cannot be read, so the store cannot tell whether the /// Voelin key is its device key. #[error( "the Voelin key {uid:?} cannot be stored as a synced copy (synced = true): the account \ - record {record:?} cannot be read, so it may name this key as the device key" + record {record:?} cannot be read, so it may name this key as the device key, which a \ + sign-out keeps but would delete as a synced copy" )] UnreadableRecord { uid: String, record: String }, /// The device key of the record is stored as a synced copy already. #[error( "the account record {record:?} names the Voelin key {device:?} as the device key, which is \ - stored as a synced copy (synced = true): a sign-out would delete it whatever the record \ - says" + stored as a synced copy (synced = true): a sign-out deletes every synced copy before it \ + reads the record, so it would delete the device key that it keeps" )] RecordNamesSyncedKey { record: String, device: String }, } diff --git a/crates/voelin-store/tests/keystore.rs b/crates/voelin-store/tests/keystore.rs index 4bc5eec..88c63ab 100644 --- a/crates/voelin-store/tests/keystore.rs +++ b/crates/voelin-store/tests/keystore.rs @@ -31,6 +31,8 @@ use voelin_identity::{ }; use voelin_store::{IdentityOrigin, SqliteKeyStore, Store}; +mod support; + /// What `serde_json::to_string(&tsproto::Identity)` writes for the test /// identity of tsproto's own `identity_tests`. const TEAMSPEAK_JSON: &str = r#"{"key":"YTyJofmztcTBjq3KZcDdxu+G4RPVwE5vg8VaN2jbQao=","counter":2792354,"max_counter":2792354}"#; @@ -1734,7 +1736,7 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer( assert_eq!(rows, 4); let stop = AtomicBool::new(false); - let (done, elapsed, writes, errors) = std::thread::scope(|scope| { + let (done, elapsed, writes, errors, lines) = std::thread::scope(|scope| { let writer = scope.spawn(|| { // Its own connection, which gives up on a lock after one second. let db = Connection::open(scratch.db()).unwrap(); @@ -1751,11 +1753,13 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer( (writes, errors) }); let started = Instant::now(); - let done = store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid())); + let (done, lines) = support::at_trace(|| { + store.sign_out(&binding().account, DeviceKeyChoice::Forget(key().uid())) + }); let elapsed = started.elapsed(); stop.store(true, Ordering::Relaxed); let (writes, errors) = writer.join().unwrap(); - (done.unwrap(), elapsed, writes, errors) + (done.unwrap(), elapsed, writes, errors, lines) }); // Four removals: the two copies, the device key the user forgot, the record. @@ -1764,6 +1768,8 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer( assert!(writes > 0, "the writer never ran"); assert!(errors.is_empty(), "a concurrent writer failed: {errors:?}"); assert!(elapsed < Duration::from_secs(1), "the sign-out took {elapsed:?}"); + // One checkpoint for the four removals: each one that is blocked says so. + assert_eq!(support::blocked_checkpoints(&lines), 1, "{lines:?}"); // Nothing is lost by the wait: once the reader is gone, the next removal // truncates the log. @@ -1773,6 +1779,183 @@ fn a_reader_that_blocks_the_checkpoint_costs_milliseconds_and_starves_no_writer( assert!(RawFiles::read(&scratch).wal.is_empty(), "the log is truncated again"); } +// ------------------------- the keys a sign-out keeps, and the one the user forgets +// +// Open question 10 of the accounts design (Phase 2 task 34): a sign-out keeps +// every device key, and "Forget this device's identity" is the only deletion. + +/// Every column of the row of this `(kind, uid)` as SQLite holds it, by name. +fn named_row(db: &Connection, kind: &str, uid: &str) -> Vec<(String, rusqlite::types::Value)> { + db.query_row( + "SELECT * FROM identities WHERE kind = ?1 AND uid = ?2", + params![kind, uid], + |row| { + let names: Vec = + row.as_ref().column_names().iter().map(|n| n.to_string()).collect(); + names + .into_iter() + .enumerate() + .map(|(index, name)| Ok((name, row.get(index)?))) + .collect::>>() + }, + ) + .unwrap() +} + +#[test] +fn the_device_key_survives_a_sign_out_byte_for_byte_in_the_file() { + // Whether it predates the account or the client made it for the account, no + // column of its row changes: the key never carried a binding, and a sign-out + // writes nothing to it. + for bound_existing_key in [true, false] { + let install = signed_in_install_on_file(bound_existing_key); + let uid = key().uid().to_base32(); + let db = Connection::open(install.scratch.db()).unwrap(); + let before = named_row(&db, KIND_VOELIN, &uid); + assert!(before.len() >= 8, "{before:?}"); + + let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + assert_eq!(named_row(&db, KIND_VOELIN, &uid), before, "{bound_existing_key}"); + let kept = install.store.voelin_key(&key().uid()).unwrap().unwrap(); + assert_eq!(&kept.to_pkcs8().unwrap()[..], &key().to_pkcs8().unwrap()[..]); + } +} + +#[test] +fn a_device_key_that_carries_a_binding_is_unbound_and_keeps_the_rest_of_its_row() { + // The store accepts a binding with `synced = false` on the device key (a + // binding with `synced = true` is refused, see the last section). A sign-out + // unbinds it and keeps it: the four binding columns are the only ones that + // change. + const BINDING_COLUMNS: [&str; 4] = ["account", "integration", "integration_rev", "synced"]; + for bound_existing_key in [true, false] { + let install = signed_in_install_on_file(bound_existing_key); + let uid = key().uid().to_base32(); + let device_only = AccountBinding { synced: false, ..binding() }; + install + .store + .put(&IdentityBlob::voelin(&key()).unwrap().with_binding(device_only)) + .unwrap(); + let db = Connection::open(install.scratch.db()).unwrap(); + let before = named_row(&db, KIND_VOELIN, &uid); + let bound = |row: &[(String, rusqlite::types::Value)]| { + row.iter().any(|(name, value)| { + name == "account" && !matches!(value, rusqlite::types::Value::Null) + }) + }; + assert!(bound(&before), "the setup binds the key"); + + let done = install.store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + assert!(done.unbound.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + assert!(!done.removed.contains(&device_key_info()), "{bound_existing_key}: {done:?}"); + + let after = named_row(&db, KIND_VOELIN, &uid); + assert!(!bound(&after), "{bound_existing_key}: unbound"); + assert_eq!(before.len(), after.len()); + for ((name, was), (_, is)) in before.iter().zip(&after) { + if !BINDING_COLUMNS.contains(&name.as_str()) { + assert_eq!(is, was, "{bound_existing_key}: column {name} is not a binding column"); + } + } + let stored = install.store.get(KIND_VOELIN, &uid).unwrap().unwrap(); + assert_eq!(stored, IdentityBlob::voelin(&key()).unwrap()); + assert!(install.store.bound_to(&binding().account).unwrap().is_empty()); + } +} + +#[test] +fn a_sign_out_scrubs_the_copies_it_deletes_and_leaves_the_kept_keys_in_the_file() { + // What a sign-out still deletes is a synced copy (a private key, which + // the service holds again) and the record: those are gone from the file and + // its log. The device key and the device-only secret are kept, so their text + // is still there. + let scratch = Scratch::new("scrub-keeps"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let device = IdentityBlob::voelin(&key()).unwrap(); + let synced = fresh_teamspeak(binding()); + let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() }); + let device_text = key_text(&device.json, "pkcs8"); + let (synced_text, device_only_text) = + (key_text(&synced.json, "key"), key_text(&device_only.json, "key")); + for blob in [&device, &synced, &device_only] { + store.put(blob).unwrap(); + } + store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap(); + let neighbour = Store::open(&scratch.db()).unwrap(); + let before = RawFiles::read(&scratch); + assert!(before.holds(&device_text) && before.holds(&synced_text)); + + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + let after = RawFiles::read(&scratch); + assert_eq!(after.where_is(&synced_text), (false, false), "the synced copy"); + assert!(after.holds(&device_text), "the device key is kept"); + assert!(after.holds(&device_only_text), "the device-only secret is kept"); + assert!(after.wal.is_empty(), "the log is truncated"); + drop(neighbour); +} + +#[test] +fn a_sign_out_that_deletes_nothing_does_not_checkpoint() { + // With no record and no synced copy a sign-out only unbinds. The checkpoint + // belongs to deletions: with a reader that blocks it, a deletion says so, and + // the sign-out does not. + let scratch = Scratch::new("no-deletion"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + let device_only = fresh_teamspeak(AccountBinding { synced: false, ..binding() }); + store.put(&device_only).unwrap(); + let reader = Connection::open(scratch.db()).unwrap(); + reader.execute_batch("BEGIN").unwrap(); + let rows: i64 = reader.query_row("SELECT count(*) FROM identities", [], |r| r.get(0)).unwrap(); + assert_eq!(rows, 1); + + let (done, lines) = + support::at_trace(|| store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap()); + assert!(done.removed.is_empty(), "{done:?}"); + assert_eq!(done.unbound, vec![info_of(&device_only.clone().with_binding(None))]); + assert_eq!(support::blocked_checkpoints(&lines), 0, "{lines:?}"); + + // The same reader does block the checkpoint of a deletion, so the count above + // would have shown one. + store.put_voelin_key(&key()).unwrap(); + let (removed, lines) = + support::at_trace(|| store.remove(KIND_VOELIN, &key().uid().to_base32()).unwrap()); + assert!(removed); + assert_eq!(support::blocked_checkpoints(&lines), 1, "{lines:?}"); + reader.execute_batch("COMMIT").unwrap(); +} + +#[test] +fn a_key_kept_by_a_sign_out_is_exported_and_then_forgotten_without_a_trace() { + // The flow of "Forget this device's identity" after a sign-out: the key is + // still there, unbound; the UI exports it, then deletes it. The export is + // what `voelin_key` and `to_pkcs8` give, and it restores the key. + let scratch = Scratch::new("export-forget"); + let store = SqliteKeyStore::open(&scratch.db()).unwrap(); + store.put_voelin_key(&key()).unwrap(); + store.put_account_record(&AccountRecord { bound_existing_key: false, ..record() }).unwrap(); + store.sign_out(&binding().account, DeviceKeyChoice::Auto).unwrap(); + let uid = key().uid(); + let stored = store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(); + let text = key_text(&stored.json, "pkcs8"); + + let exported = store.voelin_key(&uid).unwrap().expect("the key is there").to_pkcs8().unwrap(); + assert!(RawFiles::read(&scratch).holds(&text)); + assert!(store.remove(KIND_VOELIN, &uid.to_base32()).unwrap()); + assert!(store.voelin_key(&uid).unwrap().is_none()); + let after = RawFiles::read(&scratch); + assert_eq!(after.where_is(&text), (false, false), "nothing of the key is left"); + assert!(after.wal.is_empty(), "the log is truncated"); + + // The export brings the same key back. + let restored = IdentityKey::from_pkcs8(&exported).unwrap(); + assert_eq!(restored.uid(), uid); + assert_eq!(restored.sign(b"the exported key"), key().sign(b"the exported key")); + store.put_voelin_key(&restored).unwrap(); + assert_eq!(store.get(KIND_VOELIN, &uid.to_base32()).unwrap().unwrap(), stored); +} + // -------------------------------------- the device key is never a synced copy // // `KeyStore::sign_out` deletes everything bound with `synced = true` in its diff --git a/crates/voelin-store/tests/support/mod.rs b/crates/voelin-store/tests/support/mod.rs new file mode 100644 index 0000000..9da2602 --- /dev/null +++ b/crates/voelin-store/tests/support/mod.rs @@ -0,0 +1,84 @@ +//! Helpers the integration tests of this crate share. + +use std::fmt::{self, Write as _}; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; + +use tracing::field::{Field, Visit}; +use tracing::level_filters::LevelFilter; +use tracing::span::{Attributes, Id, Record}; +use tracing::{Event, Metadata, Subscriber}; + +/// A subscriber that keeps every event and span it sees as one line of text +/// each: level, target and every field with its `Debug` text, as a log line +/// would show them. +struct Capture { + lines: Arc>>, + spans: AtomicU64, +} + +impl Capture { + fn push(&self, line: String) { + self.lines.lock().unwrap_or_else(PoisonError::into_inner).push(line); + } +} + +/// The fields of an event or a span as ` name=value` text. +struct Fields<'a>(&'a mut String); + +impl Visit for Fields<'_> { + fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) { + let _ = write!(self.0, " {}={value:?}", field.name()); + } +} + +impl Subscriber for Capture { + fn enabled(&self, _: &Metadata<'_>) -> bool { + true + } + + fn max_level_hint(&self) -> Option { + Some(LevelFilter::TRACE) + } + + fn new_span(&self, attributes: &Attributes<'_>) -> Id { + let mut line = format!("span {}", attributes.metadata().name()); + attributes.record(&mut Fields(&mut line)); + self.push(line); + Id::from_u64(self.spans.fetch_add(1, Ordering::Relaxed) + 1) + } + + fn record(&self, _: &Id, values: &Record<'_>) { + let mut line = String::from("span record"); + values.record(&mut Fields(&mut line)); + self.push(line); + } + + fn record_follows_from(&self, _: &Id, _: &Id) {} + + fn event(&self, event: &Event<'_>) { + let metadata = event.metadata(); + let mut line = format!("{} {}:", metadata.level(), metadata.target()); + event.record(&mut Fields(&mut line)); + self.push(line); + } + + fn enter(&self, _: &Id) {} + + fn exit(&self, _: &Id) {} +} + +/// Run `f` on this thread with a subscriber that takes in everything logged at +/// TRACE and above, and return what `f` returned with the lines logged. +pub fn at_trace(f: impl FnOnce() -> R) -> (R, Vec) { + let lines = Arc::new(Mutex::new(Vec::new())); + let subscriber = Capture { lines: Arc::clone(&lines), spans: AtomicU64::new(0) }; + let out = tracing::subscriber::with_default(subscriber, f); + let lines = std::mem::take(&mut *lines.lock().unwrap_or_else(PoisonError::into_inner)); + (out, lines) +} + +/// How many of the lines say that a checkpoint was blocked. +pub fn blocked_checkpoints(lines: &[String]) -> usize { + lines.iter().filter(|line| line.contains("another connection blocked the checkpoint")).count() +}