OXYGENHUB

Coverage / crates/spectra-core/src/ledger.rs 95.0%

384 of 404 lines run, 107 of 243 functions · run #6 on main · run missed

1
//! The ledger (spec §9, §9.5): the append-only, hash-chained event log in
2
//! SQLite, its checkpoints signed by the instance key, its verification,
3
//! and the bus that tells everything else what was appended.
4
//!
5
//! One writer at a time (a lock around the chain head and SQLite's own),
6
//! so `seq` is gap-free and every `prev` is the hash of the event before.
7
//! Readers never wait for it (WAL).
8
9
use crate::event::{canonical_json, Auth, Event, Method, NewEvent};
10
use crate::hlc::{Clock, Hlc};
11
use crate::keys::KeyPair;
12
use crate::{ids, projections};
13
use anyhow::{bail, Context, Result};
14
use oxy_core::hash::KeyId;
15
use oxy_core::identity::{Identity, Signature};
16
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions, SqliteRow, SqliteSynchronous};
17
use sqlx::{Row, SqlitePool};
18
use std::path::Path;
19
use std::sync::Arc;
20
use tokio::sync::{broadcast, Mutex};
21
22
/// Events between checkpoints (spec §9.5).
23
pub const CHECKPOINT_EVERY: u64 = 256;
24
/// The longest a written event waits for a checkpoint (spec §9.5).
25
pub const CHECKPOINT_INTERVAL_MS: u64 = 10 * 60 * 1000;
26
27
const CHECKPOINT_DOMAIN: &[u8] = b"spectra1 checkpoint ";
28
29
/// The ledger: the database, the chain head, the clock and the bus.
30
pub struct Ledger {
31
    pool: SqlitePool,
32
    /// Held for as long as this ledger may append: one writer per data
33
    /// directory, so the chain never forks (`None` when opened read-only).
34
    _lock: Option<std::fs::File>,
35
    head: Mutex<Head>,
36
    clock: Clock,
37
    bus: broadcast::Sender<Arc<Event>>,
38
    instance: Option<KeyPair>,
39
}
40
41
#[derive(Clone, Copy, Debug)]
42
struct Head {
43
    seq: u64,
44
    hash: [u8; 32],
45
    since_checkpoint: u64,
46
    oldest_unchecked_ms: Option<u64>,
47
}
48
49
impl Ledger {
50
    /// Open (or create) `path`, apply migrations, and refuse a ledger
51
    /// written by a newer format. Checkpoints are signed with `instance`;
52
    /// without one (tests, read-only tools) none are made.
5346×
    pub async fn open(path: &Path, instance: Option<KeyPair>) -> Result<Ledger> {
5446×
        let lock_path = path.with_extension("lock");
5546×
        let lock = std::fs::OpenOptions::new()
5646×
            .create(true)
5746×
            .truncate(false)
5846×
            .write(true)
5946×
            .open(&lock_path)
6046×
            .with_context(|| format!("opening {}", lock_path.display()))?;
6146×
        match lock.try_lock() {
6245×
            Ok(()) => {}
63
            Err(std::fs::TryLockError::WouldBlock) => {
641×
                bail!("another process is writing to {} (is `spectra serve` running? stop it, or do this through it)", path.display())
65
            }
660×
            Err(std::fs::TryLockError::Error(e)) => return Err(e).with_context(|| format!("locking {}", lock_path.display())),
67
        }
6845×
        let mut l = Ledger::open_unlocked(path, instance).await?;
6944×
        l._lock = Some(lock);
7044×
        Ok(l)
7146×
    }
72
73
    /// Open for reading and verifying only, while another process may be
74
    /// writing: no lock, and `append` must not be called.
7516×
    pub async fn open_read_only(path: &Path) -> Result<Ledger> {
7616×
        Ledger::open_unlocked(path, None).await
7716×
    }
78
7961×
    async fn open_unlocked(path: &Path, instance: Option<KeyPair>) -> Result<Ledger> {
8061×
        let opts = SqliteConnectOptions::new()
8161×
            .filename(path)
8261×
            .create_if_missing(true)
8361×
            .journal_mode(SqliteJournalMode::Wal)
8461×
            .synchronous(SqliteSynchronous::Normal)
8561×
            .foreign_keys(true)
8661×
            .busy_timeout(std::time::Duration::from_secs(10));
8761×
        let pool =
8861×
            SqlitePoolOptions::new().max_connections(8).connect_with(opts).await.with_context(|| format!("opening {}", path.display()))?;
8961×
        sqlx::migrate!("./migrations").run(&pool).await.context("applying migrations")?;
9061×
        let format: Option<String> = sqlx::query_scalar("SELECT value FROM meta WHERE key = 'ledger_format'").fetch_optional(&pool).await?;
9161×
        match format.as_deref().map(str::parse::<u32>) {
92
            None => {
9324×
                sqlx::query("INSERT INTO meta (key, value) VALUES ('ledger_format', ?)")
9424×
                    .bind(crate::LEDGER_FORMAT.to_string())
9524×
                    .execute(&pool)
9624×
                    .await?;
97
            }
9837×
            Some(Ok(f)) if f <= crate::LEDGER_FORMAT => {}
99
            Some(_) => {
1001×
                bail!("{} was written by a newer Spectra (ledger format {}): upgrade spectra", path.display(), format.unwrap_or_default())
101
            }
102
        }
10360×
        let last =
10460×
            sqlx::query("SELECT seq, hash, hlc_wall, hlc_logical FROM events ORDER BY seq DESC LIMIT 1").fetch_optional(&pool).await?;
10560×
        let (seq, hash, hlc) = match last {
10636×
            Some(r) => (
10736×
                r.get::<i64, _>(0) as u64,
10836×
                to32(r.get::<Vec<u8>, _>(1))?,
10936×
                Hlc { wall_ms: r.get::<i64, _>(2) as u64, logical: r.get::<i64, _>(3) as u32 },
110
            ),
11124×
            None => (0, [0; 32], Hlc::default()),
112
        };
11360×
        let checkpoint_seq: i64 =
11460×
            sqlx::query_scalar("SELECT COALESCE(MAX(seq), 0) FROM events WHERE kind = 'ledger.checkpoint'").fetch_one(&pool).await?;
11560×
        let since = seq.saturating_sub(checkpoint_seq as u64);
11660×
        let (bus, _) = broadcast::channel(4096);
11760×
        Ok(Ledger {
11860×
            pool,
11960×
            _lock: None,
12060×
            head: Mutex::new(Head { seq, hash, since_checkpoint: since, oldest_unchecked_ms: (since > 0).then(ids::now_ms) }),
12160×
            clock: Clock::starting_at(hlc),
12260×
            bus,
12360×
            instance,
12460×
        })
12561×
    }
126
127
    /// The database, for projections' readers.
12842×
    pub fn pool(&self) -> &SqlitePool {
12942×
        &self.pool
13042×
    }
131
132
    /// Every appended event, as it commits.
1331×
    pub fn subscribe(&self) -> broadcast::Receiver<Arc<Event>> {
1341×
        self.bus.subscribe()
1351×
    }
136
137
    /// The instance key, when this ledger signs checkpoints.
1380×
    pub fn instance(&self) -> Option<&KeyPair> {
1390×
        self.instance.as_ref()
1400×
    }
141
142
    /// The newest event's sequence number and hash.
14318×
    pub async fn head(&self) -> (u64, [u8; 32]) {
14418×
        let h = self.head.lock().await;
14518×
        (h.seq, h.hash)
14618×
    }
147
148
    /// Append `events` in one transaction, chained and projected, then
149
    /// publish them; a checkpoint follows when one is due.
1501827×
    pub async fn append(&self, events: Vec<NewEvent>) -> Result<Vec<Arc<Event>>> {
1511827×
        let mut head = self.head.lock().await;
1521827×
        let mut tx = self.pool.begin().await?;
1531827×
        let mut out = Vec::with_capacity(events.len() + 1);
1541827×
        let mut h = *head;
15511452×
        for n in events {
15611452×
            let e = self.chain(&mut h, n);
15711452×
            insert(&mut tx, &e).await?;
15811452×
            projections::apply(&mut tx, &e).await?;
15911452×
            h.since_checkpoint += 1;
16011452×
            h.oldest_unchecked_ms.get_or_insert(e.at_ms);
16111452×
            out.push(e);
162
            // Every 256 events exactly, even inside a large batch.
16311452×
            if h.since_checkpoint >= CHECKPOINT_EVERY && self.instance.is_some() {
16443×
                let cp = self.checkpoint_event(&mut h);
16543×
                insert(&mut tx, &cp).await?;
16643×
                projections::apply(&mut tx, &cp).await?;
16743×
                out.push(cp);
16811409×
            }
169
        }
1701827×
        let due = h.oldest_unchecked_ms.is_some_and(|t| ids::now_ms().saturating_sub(t) >= CHECKPOINT_INTERVAL_MS);
1711827×
        if due && self.instance.is_some() {
1720×
            let cp = self.checkpoint_event(&mut h);
1730×
            insert(&mut tx, &cp).await?;
1740×
            projections::apply(&mut tx, &cp).await?;
1750×
            out.push(cp);
1761827×
        }
1771827×
        tx.commit().await?;
1781827×
        *head = h;
1791827×
        drop(head);
1801827×
        let out: Vec<Arc<Event>> = out.into_iter().map(Arc::new).collect();
18111495×
        for e in &out {
18211495×
            let _ = self.bus.send(e.clone());
18311495×
        }
1841827×
        Ok(out)
1851827×
    }
186
187
    /// Append one event.
1881426×
    pub async fn append_one(&self, e: NewEvent) -> Result<Arc<Event>> {
1891426×
        Ok(self.append(vec![e]).await?.remove(0))
1901426×
    }
191
192
    /// Write a checkpoint now if any event is not covered by one (at
193
    /// shutdown, and from the ten-minute timer).
19420×
    pub async fn checkpoint(&self) -> Result<Option<Arc<Event>>> {
19520×
        let Some(_) = &self.instance else { return Ok(None) };
19620×
        let mut head = self.head.lock().await;
19720×
        if head.since_checkpoint == 0 {
1981×
            return Ok(None);
19919×
        }
20019×
        let mut h = *head;
20119×
        let cp = self.checkpoint_event(&mut h);
20219×
        let mut tx = self.pool.begin().await?;
20319×
        insert(&mut tx, &cp).await?;
20419×
        projections::apply(&mut tx, &cp).await?;
20519×
        tx.commit().await?;
20619×
        *head = h;
20719×
        drop(head);
20819×
        let cp = Arc::new(cp);
20919×
        let _ = self.bus.send(cp.clone());
21019×
        Ok(Some(cp))
21120×
    }
212
21311514×
    fn chain(&self, h: &mut Head, n: NewEvent) -> Event {
21411514×
        let at_ms = ids::now_ms();
21511514×
        let mut e = Event {
21611514×
            seq: h.seq + 1,
21711514×
            id: ids::ulid(),
21811514×
            at_ms,
21911514×
            hlc: self.clock.tick(at_ms),
22011514×
            prev: h.hash,
22111514×
            hash: [0; 32],
22211514×
            auth: n.auth,
22311514×
            kind: n.kind,
22411514×
            actor: n.actor,
22511514×
            session: n.session,
22611514×
            project: n.project,
22711514×
            subject: n.subject,
22811514×
            payload: Some(canonical_json(&n.payload)),
22911514×
            trace: n.trace,
23011514×
        };
23111514×
        e.hash = e.computed_hash();
23211514×
        h.seq = e.seq;
23311514×
        h.hash = e.hash;
23411514×
        e
23511514×
    }
236
237
    /// A checkpoint naming the head `h` holds, signed by the instance key
238
    /// over `"spectra1 checkpoint " || hash || seq` (spec §9.5).
23962×
    fn checkpoint_event(&self, h: &mut Head) -> Event {
24062×
        let instance = self.instance.as_ref().expect("checked by callers");
24162×
        let (seq, hash, count) = (h.seq, h.hash, h.since_checkpoint);
24262×
        let sig = instance.sign(&checkpoint_message(seq, &hash));
24362×
        let n = NewEvent::system("ledger.checkpoint", serde_json::json!({ "seq": seq, "hash": hex::encode(hash), "count": count })).by(
244
            "system",
24562×
            Auth {
24662×
                key: Some(instance.key.0),
24762×
                method: Method::Signature,
24862×
                assurance: 2,
24962×
                proof: Some(oxy_core::cbor::encode(&sig.to_value())),
25062×
            },
251
        );
25262×
        let e = self.chain(h, n);
25362×
        h.since_checkpoint = 0;
25462×
        h.oldest_unchecked_ms = None;
25562×
        e
25662×
    }
257
258
    /// Events from `from` (inclusive), oldest first, at most `limit`.
25950×
    pub async fn events(&self, from: u64, limit: u32) -> Result<Vec<Event>> {
26050×
        let rows = sqlx::query(&format!("{SELECT_EVENT} WHERE seq >= ? ORDER BY seq LIMIT ?"))
26150×
            .bind(from as i64)
26250×
            .bind(limit as i64)
26350×
            .fetch_all(&self.pool)
26450×
            .await?;
26550×
        rows.iter().map(row_to_event).collect()
26650×
    }
267
268
    /// Events of the given kinds from `from` (inclusive), oldest first.
26938×
    pub async fn events_of_kinds(&self, from: u64, kinds: &[&str], limit: u32) -> Result<Vec<Event>> {
27038×
        let marks = vec!["?"; kinds.len()].join(",");
27138×
        let sql = format!("{SELECT_EVENT} WHERE seq >= ? AND kind IN ({marks}) ORDER BY seq LIMIT ?");
27238×
        let mut q = sqlx::query(&sql).bind(from as i64);
273190×
        for k in kinds {
274190×
            q = q.bind(*k);
275190×
        }
27638×
        let rows = q.bind(limit as i64).fetch_all(&self.pool).await?;
27738×
        rows.iter().map(row_to_event).collect()
27838×
    }
279
280
    /// Recompute the chain and check every checkpoint and every proof it
281
    /// can, from the ledger alone (spec §9.5, `spectra admin verify`).
28222×
    pub async fn verify(&self, keys: &mut dyn KeyResolver) -> Result<Verification> {
28322×
        let mut v = Verification::default();
28422×
        let mut prev = [0u8; 32];
28522×
        let mut expect = 1u64;
28622×
        let mut instance: Option<Identity> = None;
28722×
        let mut from = 1;
288
        loop {
28949×
            let batch = self.events(from, 2_000).await?;
29049×
            if batch.is_empty() {
29122×
                break;
29227×
            }
29310547×
            for e in &batch {
29410547×
                v.events += 1;
29510547×
                if e.seq != expect {
2961×
                    v.finding(e.seq, Problem::Gap, format!("expected event {expect}"));
2971×
                    expect = e.seq;
29810546×
                }
29910547×
                if e.prev != prev {
3002×
                    v.finding(e.seq, Problem::ChainBreak, "prev is not the hash of the event before".into());
30110545×
                }
30210547×
                if e.payload.is_some() && e.computed_hash() != e.hash {
3032×
                    v.finding(e.seq, Problem::HashMismatch, "the event's fields do not give its hash: it was edited".into());
30410545×
                }
30510547×
                if e.kind == "identity.instance" {
30622×
                    instance = e
30722×
                        .json()
30822×
                        .get("identity")
30922×
                        .and_then(|h| h.as_str())
31022×
                        .and_then(|h| hex::decode(h).ok())
31122×
                        .and_then(|b| Identity::decode(&b).ok());
31210525×
                }
31310547×
                if e.kind == "ledger.checkpoint" {
31462×
                    v.checkpoints += 1;
31562×
                    match check_checkpoint(e, prev, instance.as_ref()) {
31660×
                        Ok(()) => v.last_checkpoint = Some(e.seq),
3172×
                        Err(why) => v.finding(e.seq, Problem::BadCheckpoint, why),
318
                    }
31910485×
                } else if let Err(why) = keys.check(e) {
32010×
                    v.finding(e.seq, Problem::BadProof, why);
32110475×
                }
32210547×
                prev = e.hash;
32310547×
                expect += 1;
324
            }
32527×
            from = batch.last().map(|e| e.seq + 1).unwrap_or(from);
326
        }
32722×
        v.head = prev;
32822×
        v.uncovered = v.events.saturating_sub(v.last_checkpoint.unwrap_or(0));
32922×
        Ok(v)
33022×
    }
331
332
    /// Clear every projection and replay the ledger into them.
3332×
    pub async fn rebuild(&self) -> Result<()> {
3342×
        let _head = self.head.lock().await;
3352×
        let mut tx = self.pool.begin().await?;
3362×
        replay(&mut tx).await?;
3372×
        tx.commit().await?;
3382×
        Ok(())
3392×
    }
340
341
    /// Whether the projections equal a rebuild from the ledger: rebuild in
342
    /// a transaction, compare, and roll back. Returns the tables that differ.
3437×
    pub async fn check(&self) -> Result<Vec<String>> {
3447×
        let _head = self.head.lock().await;
3457×
        let mut tx = self.pool.begin().await?;
3467×
        let mut before = Vec::new();
34749×
        for t in projections::TABLES {
34849×
            before.push(dump(&mut tx, t).await?);
349
        }
3507×
        replay(&mut tx).await?;
3517×
        let mut differ = Vec::new();
35249×
        for (t, b) in projections::TABLES.iter().zip(before) {
35349×
            if dump(&mut tx, t).await? != b {
3540×
                differ.push(t.to_string());
35549×
            }
356
        }
3577×
        tx.rollback().await?;
3587×
        Ok(differ)
3597×
    }
360
}
361
362
/// `"spectra1 checkpoint " || hash || seq (8 bytes, big-endian)`.
363124×
pub fn checkpoint_message(seq: u64, hash: &[u8; 32]) -> Vec<u8> {
364124×
    let mut m = CHECKPOINT_DOMAIN.to_vec();
365124×
    m.extend_from_slice(hash);
366124×
    m.extend_from_slice(&seq.to_be_bytes());
367124×
    m
368124×
}
369
37062×
fn check_checkpoint(e: &Event, prev: [u8; 32], instance: Option<&Identity>) -> std::result::Result<(), String> {
37162×
    let p = e.json();
37262×
    let seq = p.get("seq").and_then(|s| s.as_u64()).ok_or("no seq")?;
37362×
    let hash: [u8; 32] =
37462×
        p.get("hash").and_then(|h| h.as_str()).and_then(|h| hex::decode(h).ok()).and_then(|b| b.try_into().ok()).ok_or("no hash")?;
37562×
    if seq + 1 != e.seq || hash != prev {
3761×
        return Err("names a head other than the event before it".into());
37761×
    }
37861×
    let instance = instance.ok_or("no instance identity precedes it")?;
37961×
    if e.auth.key != Some(instance.hash().0) {
3800×
        return Err("signed by a key other than the instance's".into());
38161×
    }
38261×
    let proof = e.auth.proof.as_deref().ok_or("unsigned")?;
38361×
    let sig = oxy_core::cbor::decode(proof).ok().and_then(|v| Signature::from_value(&v).ok()).ok_or("malformed signature")?;
38461×
    oxy_core::identity::verify_challenge(instance, &sig, &checkpoint_message(seq, &hash))
38561×
        .map_err(|e| format!("signature does not verify: {e}"))
38662×
}
387
388
/// Checks the proof of a signed event: the identities and delegations that
389
/// say whose key it was (spec §8.5). Principals supply it (`principals`).
390
/// It is given every event but checkpoints, in order, so it can follow
391
/// identities as they are recorded.
392
pub trait KeyResolver: Send {
393
    fn check(&mut self, e: &Event) -> std::result::Result<(), String>;
394
}
395
396
/// A resolver that knows no keys: every signed event is reported.
397
pub struct NoKeys;
398
impl KeyResolver for NoKeys {
39910339×
    fn check(&mut self, e: &Event) -> std::result::Result<(), String> {
40010339×
        match e.auth.method {
4010×
            Method::Signature | Method::Passkey => Err("no identity is known for its key".into()),
40210339×
            _ => Ok(()),
403
        }
40410339×
    }
405
}
406
407
/// What `verify` found.
408
#[derive(Clone, Debug, Default, serde::Serialize)]
409
pub struct Verification {
410
    pub events: u64,
411
    pub checkpoints: u64,
412
    pub last_checkpoint: Option<u64>,
413
    /// Events after the last good checkpoint: chained, not yet signed.
414
    pub uncovered: u64,
415
    #[serde(serialize_with = "ser_hex")]
416
    pub head: [u8; 32],
417
    pub findings: Vec<Finding>,
418
}
419
4204×
fn ser_hex<S: serde::Serializer>(h: &[u8; 32], s: S) -> std::result::Result<S::Ok, S::Error> {
4214×
    s.serialize_str(&hex::encode(h))
4224×
}
423
424
impl Verification {
42516×
    pub fn clean(&self) -> bool {
42616×
        self.findings.is_empty()
42716×
    }
42817×
    fn finding(&mut self, seq: u64, problem: Problem, detail: String) {
42917×
        self.findings.push(Finding { seq, problem, detail });
43017×
    }
431
}
432
433
/// One thing wrong with the ledger.
434
#[derive(Clone, Debug, serde::Serialize)]
435
pub struct Finding {
436
    pub seq: u64,
437
    pub problem: Problem,
438
    pub detail: String,
439
}
440
441
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
442
#[serde(rename_all = "snake_case")]
443
pub enum Problem {
444
    Gap,
445
    ChainBreak,
446
    HashMismatch,
447
    BadCheckpoint,
448
    BadProof,
449
}
450
451
const SELECT_EVENT: &str = "SELECT seq, id, at_ms, hlc_wall, hlc_logical, prev, hash, auth_key, auth_method, auth_assurance, auth_proof, kind, actor, session, project, subject, payload, trace FROM events";
452
45311514×
async fn insert(conn: &mut sqlx::SqliteConnection, e: &Event) -> sqlx::Result<()> {
45411514×
    sqlx::query(
45511514×
        "INSERT INTO events (seq, id, at_ms, hlc_wall, hlc_logical, prev, hash, auth_key, auth_method, auth_assurance, auth_proof, kind, actor, session, project, subject, payload, trace) \
45611514×
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
457
    )
45811514×
    .bind(e.seq as i64)
45911514×
    .bind(&e.id)
46011514×
    .bind(e.at_ms as i64)
46111514×
    .bind(e.hlc.wall_ms as i64)
46211514×
    .bind(e.hlc.logical as i64)
46311514×
    .bind(e.prev.to_vec())
46411514×
    .bind(e.hash.to_vec())
46511514×
    .bind(e.auth.key.map(|k| k.to_vec()))
46611514×
    .bind(e.auth.method as i64)
46711514×
    .bind(e.auth.assurance as i64)
46811514×
    .bind(e.auth.proof.clone())
46911514×
    .bind(&e.kind)
47011514×
    .bind(&e.actor)
47111514×
    .bind(&e.session)
47211514×
    .bind(&e.project)
47311514×
    .bind(&e.subject)
47411514×
    .bind(e.payload.clone())
47511514×
    .bind(&e.trace)
47611514×
    .execute(conn)
47711514×
    .await?;
47811514×
    Ok(())
47911514×
}
480
48140905×
fn row_to_event(r: &SqliteRow) -> Result<Event> {
482
    Ok(Event {
48340905×
        seq: r.get::<i64, _>(0) as u64,
48440905×
        id: r.get(1),
48540905×
        at_ms: r.get::<i64, _>(2) as u64,
48640905×
        hlc: Hlc { wall_ms: r.get::<i64, _>(3) as u64, logical: r.get::<i64, _>(4) as u32 },
48740905×
        prev: to32(r.get(5))?,
48840905×
        hash: to32(r.get(6))?,
489
        auth: Auth {
49040905×
            key: r.get::<Option<Vec<u8>>, _>(7).map(to32).transpose()?,
49140905×
            method: Method::from_u8(r.get::<i64, _>(8) as u8).context("unknown auth method")?,
49240905×
            assurance: r.get::<i64, _>(9) as u8,
49340905×
            proof: r.get(10),
494
        },
49540905×
        kind: r.get(11),
49640905×
        actor: r.get(12),
49740905×
        session: r.get(13),
49840905×
        project: r.get(14),
49940905×
        subject: r.get(15),
50040905×
        payload: r.get(16),
50140905×
        trace: r.get(17),
502
    })
50340905×
}
504
50582184×
fn to32(v: Vec<u8>) -> Result<[u8; 32]> {
50682184×
    v.try_into().map_err(|_| anyhow::anyhow!("a stored hash is not 32 bytes"))
50782184×
}
508
5099×
async fn replay(conn: &mut sqlx::SqliteConnection) -> Result<()> {
51063×
    for t in projections::TABLES {
51163×
        sqlx::query(&format!("DELETE FROM {t}")).execute(&mut *conn).await?;
512
    }
5139×
    let mut from = 1i64;
514
    loop {
51533×
        let rows = sqlx::query(&format!("{SELECT_EVENT} WHERE seq >= ? ORDER BY seq LIMIT 2000")).bind(from).fetch_all(&mut *conn).await?;
51633×
        if rows.is_empty() {
5179×
            break;
51824×
        }
51930276×
        for r in &rows {
52030276×
            let e = row_to_event(r)?;
52130276×
            projections::apply(conn, &e).await?;
52230276×
            from = e.seq as i64 + 1;
523
        }
524
    }
5259×
    Ok(())
5269×
}
527
52898×
async fn dump(conn: &mut sqlx::SqliteConnection, table: &str) -> Result<Vec<String>> {
529
    // Every column as text, rows in a fixed order: enough to compare.
53098×
    let rows = sqlx::query(&format!("SELECT * FROM {table} ORDER BY 1, 2")).fetch_all(&mut *conn).await?;
53198×
    Ok(rows
53298×
        .iter()
533148×
        .map(|r| {
534148×
            (0..r.columns().len())
535510×
                .map(|i| match r.try_get::<Option<String>, _>(i) {
536304×
                    Ok(v) => format!("{v:?}"),
537206×
                    Err(_) => match r.try_get::<Option<i64>, _>(i) {
538180×
                        Ok(n) => format!("{n:?}"),
53926×
                        Err(_) => format!("{:?}", r.try_get::<Option<Vec<u8>>, _>(i).ok().flatten()),
540
                    },
541510×
                })
542148×
                .collect::<Vec<_>>()
543148×
                .join("|")
544148×
        })
54598×
        .collect())
54698×
}
547
548
/// The identity of `key` among `identities`, by KeyId.
5490×
pub fn find_identity<'a>(identities: &'a [Identity], key: &KeyId) -> Option<&'a Identity> {
5500×
    identities.iter().find(|i| &i.hash() == key)
5510×
}