OXYGENHUB

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

384 of 404 lines run, 107 of 243 functions · run #5 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.
5333×
    pub async fn open(path: &Path, instance: Option<KeyPair>) -> Result<Ledger> {
5433×
        let lock_path = path.with_extension("lock");
5533×
        let lock = std::fs::OpenOptions::new()
5633×
            .create(true)
5733×
            .truncate(false)
5833×
            .write(true)
5933×
            .open(&lock_path)
6033×
            .with_context(|| format!("opening {}", lock_path.display()))?;
6133×
        match lock.try_lock() {
6232×
            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
        }
6832×
        let mut l = Ledger::open_unlocked(path, instance).await?;
6931×
        l._lock = Some(lock);
7031×
        Ok(l)
7133×
    }
72
73
    /// Open for reading and verifying only, while another process may be
74
    /// writing: no lock, and `append` must not be called.
7511×
    pub async fn open_read_only(path: &Path) -> Result<Ledger> {
7611×
        Ledger::open_unlocked(path, None).await
7711×
    }
78
7943×
    async fn open_unlocked(path: &Path, instance: Option<KeyPair>) -> Result<Ledger> {
8043×
        let opts = SqliteConnectOptions::new()
8143×
            .filename(path)
8243×
            .create_if_missing(true)
8343×
            .journal_mode(SqliteJournalMode::Wal)
8443×
            .synchronous(SqliteSynchronous::Normal)
8543×
            .foreign_keys(true)
8643×
            .busy_timeout(std::time::Duration::from_secs(10));
8743×
        let pool =
8843×
            SqlitePoolOptions::new().max_connections(8).connect_with(opts).await.with_context(|| format!("opening {}", path.display()))?;
8943×
        sqlx::migrate!("./migrations").run(&pool).await.context("applying migrations")?;
9043×
        let format: Option<String> = sqlx::query_scalar("SELECT value FROM meta WHERE key = 'ledger_format'").fetch_optional(&pool).await?;
9143×
        match format.as_deref().map(str::parse::<u32>) {
92
            None => {
9320×
                sqlx::query("INSERT INTO meta (key, value) VALUES ('ledger_format', ?)")
9420×
                    .bind(crate::LEDGER_FORMAT.to_string())
9520×
                    .execute(&pool)
9620×
                    .await?;
97
            }
9823×
            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
        }
10342×
        let last =
10442×
            sqlx::query("SELECT seq, hash, hlc_wall, hlc_logical FROM events ORDER BY seq DESC LIMIT 1").fetch_optional(&pool).await?;
10542×
        let (seq, hash, hlc) = match last {
10622×
            Some(r) => (
10722×
                r.get::<i64, _>(0) as u64,
10822×
                to32(r.get::<Vec<u8>, _>(1))?,
10922×
                Hlc { wall_ms: r.get::<i64, _>(2) as u64, logical: r.get::<i64, _>(3) as u32 },
110
            ),
11120×
            None => (0, [0; 32], Hlc::default()),
112
        };
11342×
        let checkpoint_seq: i64 =
11442×
            sqlx::query_scalar("SELECT COALESCE(MAX(seq), 0) FROM events WHERE kind = 'ledger.checkpoint'").fetch_one(&pool).await?;
11542×
        let since = seq.saturating_sub(checkpoint_seq as u64);
11642×
        let (bus, _) = broadcast::channel(4096);
11742×
        Ok(Ledger {
11842×
            pool,
11942×
            _lock: None,
12042×
            head: Mutex::new(Head { seq, hash, since_checkpoint: since, oldest_unchecked_ms: (since > 0).then(ids::now_ms) }),
12142×
            clock: Clock::starting_at(hlc),
12242×
            bus,
12342×
            instance,
12442×
        })
12543×
    }
126
127
    /// The database, for projections' readers.
1284×
    pub fn pool(&self) -> &SqlitePool {
1294×
        &self.pool
1304×
    }
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.
1501800×
    pub async fn append(&self, events: Vec<NewEvent>) -> Result<Vec<Arc<Event>>> {
1511800×
        let mut head = self.head.lock().await;
1521800×
        let mut tx = self.pool.begin().await?;
1531800×
        let mut out = Vec::with_capacity(events.len() + 1);
1541800×
        let mut h = *head;
15511434×
        for n in events {
15611434×
            let e = self.chain(&mut h, n);
15711434×
            insert(&mut tx, &e).await?;
15811434×
            projections::apply(&mut tx, &e).await?;
15911434×
            h.since_checkpoint += 1;
16011434×
            h.oldest_unchecked_ms.get_or_insert(e.at_ms);
16111434×
            out.push(e);
162
            // Every 256 events exactly, even inside a large batch.
16311434×
            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);
16811391×
            }
169
        }
1701800×
        let due = h.oldest_unchecked_ms.is_some_and(|t| ids::now_ms().saturating_sub(t) >= CHECKPOINT_INTERVAL_MS);
1711800×
        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);
1761800×
        }
1771800×
        tx.commit().await?;
1781800×
        *head = h;
1791800×
        drop(head);
1801800×
        let out: Vec<Arc<Event>> = out.into_iter().map(Arc::new).collect();
18111477×
        for e in &out {
18211477×
            let _ = self.bus.send(e.clone());
18311477×
        }
1841800×
        Ok(out)
1851800×
    }
186
187
    /// Append one event.
1881416×
    pub async fn append_one(&self, e: NewEvent) -> Result<Arc<Event>> {
1891416×
        Ok(self.append(vec![e]).await?.remove(0))
1901416×
    }
191
192
    /// Write a checkpoint now if any event is not covered by one (at
193
    /// shutdown, and from the ten-minute timer).
19411×
    pub async fn checkpoint(&self) -> Result<Option<Arc<Event>>> {
19511×
        let Some(_) = &self.instance else { return Ok(None) };
19611×
        let mut head = self.head.lock().await;
19711×
        if head.since_checkpoint == 0 {
1981×
            return Ok(None);
19910×
        }
20010×
        let mut h = *head;
20110×
        let cp = self.checkpoint_event(&mut h);
20210×
        let mut tx = self.pool.begin().await?;
20310×
        insert(&mut tx, &cp).await?;
20410×
        projections::apply(&mut tx, &cp).await?;
20510×
        tx.commit().await?;
20610×
        *head = h;
20710×
        drop(head);
20810×
        let cp = Arc::new(cp);
20910×
        let _ = self.bus.send(cp.clone());
21010×
        Ok(Some(cp))
21111×
    }
212
21311487×
    fn chain(&self, h: &mut Head, n: NewEvent) -> Event {
21411487×
        let at_ms = ids::now_ms();
21511487×
        let mut e = Event {
21611487×
            seq: h.seq + 1,
21711487×
            id: ids::ulid(),
21811487×
            at_ms,
21911487×
            hlc: self.clock.tick(at_ms),
22011487×
            prev: h.hash,
22111487×
            hash: [0; 32],
22211487×
            auth: n.auth,
22311487×
            kind: n.kind,
22411487×
            actor: n.actor,
22511487×
            session: n.session,
22611487×
            project: n.project,
22711487×
            subject: n.subject,
22811487×
            payload: Some(canonical_json(&n.payload)),
22911487×
            trace: n.trace,
23011487×
        };
23111487×
        e.hash = e.computed_hash();
23211487×
        h.seq = e.seq;
23311487×
        h.hash = e.hash;
23411487×
        e
23511487×
    }
236
237
    /// A checkpoint naming the head `h` holds, signed by the instance key
238
    /// over `"spectra1 checkpoint " || hash || seq` (spec §9.5).
23953×
    fn checkpoint_event(&self, h: &mut Head) -> Event {
24053×
        let instance = self.instance.as_ref().expect("checked by callers");
24153×
        let (seq, hash, count) = (h.seq, h.hash, h.since_checkpoint);
24253×
        let sig = instance.sign(&checkpoint_message(seq, &hash));
24353×
        let n = NewEvent::system("ledger.checkpoint", serde_json::json!({ "seq": seq, "hash": hex::encode(hash), "count": count })).by(
244
            "system",
24553×
            Auth {
24653×
                key: Some(instance.key.0),
24753×
                method: Method::Signature,
24853×
                assurance: 2,
24953×
                proof: Some(oxy_core::cbor::encode(&sig.to_value())),
25053×
            },
251
        );
25253×
        let e = self.chain(h, n);
25353×
        h.since_checkpoint = 0;
25453×
        h.oldest_unchecked_ms = None;
25553×
        e
25653×
    }
257
258
    /// Events from `from` (inclusive), oldest first, at most `limit`.
25944×
    pub async fn events(&self, from: u64, limit: u32) -> Result<Vec<Event>> {
26044×
        let rows = sqlx::query(&format!("{SELECT_EVENT} WHERE seq >= ? ORDER BY seq LIMIT ?"))
26144×
            .bind(from as i64)
26244×
            .bind(limit as i64)
26344×
            .fetch_all(&self.pool)
26444×
            .await?;
26544×
        rows.iter().map(row_to_event).collect()
26644×
    }
267
268
    /// Events of the given kinds from `from` (inclusive), oldest first.
26924×
    pub async fn events_of_kinds(&self, from: u64, kinds: &[&str], limit: u32) -> Result<Vec<Event>> {
27024×
        let marks = vec!["?"; kinds.len()].join(",");
27124×
        let sql = format!("{SELECT_EVENT} WHERE seq >= ? AND kind IN ({marks}) ORDER BY seq LIMIT ?");
27224×
        let mut q = sqlx::query(&sql).bind(from as i64);
273120×
        for k in kinds {
274120×
            q = q.bind(*k);
275120×
        }
27624×
        let rows = q.bind(limit as i64).fetch_all(&self.pool).await?;
27724×
        rows.iter().map(row_to_event).collect()
27824×
    }
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`).
28219×
    pub async fn verify(&self, keys: &mut dyn KeyResolver) -> Result<Verification> {
28319×
        let mut v = Verification::default();
28419×
        let mut prev = [0u8; 32];
28519×
        let mut expect = 1u64;
28619×
        let mut instance: Option<Identity> = None;
28719×
        let mut from = 1;
288
        loop {
28943×
            let batch = self.events(from, 2_000).await?;
29043×
            if batch.is_empty() {
29119×
                break;
29224×
            }
29310523×
            for e in &batch {
29410523×
                v.events += 1;
29510523×
                if e.seq != expect {
2961×
                    v.finding(e.seq, Problem::Gap, format!("expected event {expect}"));
2971×
                    expect = e.seq;
29810522×
                }
29910523×
                if e.prev != prev {
3002×
                    v.finding(e.seq, Problem::ChainBreak, "prev is not the hash of the event before".into());
30110521×
                }
30210523×
                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());
30410521×
                }
30510523×
                if e.kind == "identity.instance" {
30619×
                    instance = e
30719×
                        .json()
30819×
                        .get("identity")
30919×
                        .and_then(|h| h.as_str())
31019×
                        .and_then(|h| hex::decode(h).ok())
31119×
                        .and_then(|b| Identity::decode(&b).ok());
31210504×
                }
31310523×
                if e.kind == "ledger.checkpoint" {
31454×
                    v.checkpoints += 1;
31554×
                    match check_checkpoint(e, prev, instance.as_ref()) {
31652×
                        Ok(()) => v.last_checkpoint = Some(e.seq),
3172×
                        Err(why) => v.finding(e.seq, Problem::BadCheckpoint, why),
318
                    }
31910469×
                } else if let Err(why) = keys.check(e) {
3208×
                    v.finding(e.seq, Problem::BadProof, why);
32110461×
                }
32210523×
                prev = e.hash;
32310523×
                expect += 1;
324
            }
32524×
            from = batch.last().map(|e| e.seq + 1).unwrap_or(from);
326
        }
32719×
        v.head = prev;
32819×
        v.uncovered = v.events.saturating_sub(v.last_checkpoint.unwrap_or(0));
32919×
        Ok(v)
33019×
    }
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.
3435×
    pub async fn check(&self) -> Result<Vec<String>> {
3445×
        let _head = self.head.lock().await;
3455×
        let mut tx = self.pool.begin().await?;
3465×
        let mut before = Vec::new();
34715×
        for t in projections::TABLES {
34815×
            before.push(dump(&mut tx, t).await?);
349
        }
3505×
        replay(&mut tx).await?;
3515×
        let mut differ = Vec::new();
35215×
        for (t, b) in projections::TABLES.iter().zip(before) {
35315×
            if dump(&mut tx, t).await? != b {
3540×
                differ.push(t.to_string());
35515×
            }
356
        }
3575×
        tx.rollback().await?;
3585×
        Ok(differ)
3595×
    }
360
}
361
362
/// `"spectra1 checkpoint " || hash || seq (8 bytes, big-endian)`.
363107×
pub fn checkpoint_message(seq: u64, hash: &[u8; 32]) -> Vec<u8> {
364107×
    let mut m = CHECKPOINT_DOMAIN.to_vec();
365107×
    m.extend_from_slice(hash);
366107×
    m.extend_from_slice(&seq.to_be_bytes());
367107×
    m
368107×
}
369
37054×
fn check_checkpoint(e: &Event, prev: [u8; 32], instance: Option<&Identity>) -> std::result::Result<(), String> {
37154×
    let p = e.json();
37254×
    let seq = p.get("seq").and_then(|s| s.as_u64()).ok_or("no seq")?;
37354×
    let hash: [u8; 32] =
37454×
        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")?;
37554×
    if seq + 1 != e.seq || hash != prev {
3761×
        return Err("names a head other than the event before it".into());
37753×
    }
37853×
    let instance = instance.ok_or("no instance identity precedes it")?;
37953×
    if e.auth.key != Some(instance.hash().0) {
3800×
        return Err("signed by a key other than the instance's".into());
38153×
    }
38253×
    let proof = e.auth.proof.as_deref().ok_or("unsigned")?;
38353×
    let sig = oxy_core::cbor::decode(proof).ok().and_then(|v| Signature::from_value(&v).ok()).ok_or("malformed signature")?;
38453×
    oxy_core::identity::verify_challenge(instance, &sig, &checkpoint_message(seq, &hash))
38553×
        .map_err(|e| format!("signature does not verify: {e}"))
38654×
}
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 {
39910337×
    fn check(&mut self, e: &Event) -> std::result::Result<(), String> {
40010337×
        match e.auth.method {
4010×
            Method::Signature | Method::Passkey => Err("no identity is known for its key".into()),
40210337×
            _ => Ok(()),
403
        }
40410337×
    }
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 {
42512×
    pub fn clean(&self) -> bool {
42612×
        self.findings.is_empty()
42712×
    }
42815×
    fn finding(&mut self, seq: u64, problem: Problem, detail: String) {
42915×
        self.findings.push(Finding { seq, problem, detail });
43015×
    }
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
45311487×
async fn insert(conn: &mut sqlx::SqliteConnection, e: &Event) -> sqlx::Result<()> {
45411487×
    sqlx::query(
45511487×
        "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) \
45611487×
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
457
    )
45811487×
    .bind(e.seq as i64)
45911487×
    .bind(&e.id)
46011487×
    .bind(e.at_ms as i64)
46111487×
    .bind(e.hlc.wall_ms as i64)
46211487×
    .bind(e.hlc.logical as i64)
46311487×
    .bind(e.prev.to_vec())
46411487×
    .bind(e.hash.to_vec())
46511487×
    .bind(e.auth.key.map(|k| k.to_vec()))
46611487×
    .bind(e.auth.method as i64)
46711487×
    .bind(e.auth.assurance as i64)
46811487×
    .bind(e.auth.proof.clone())
46911487×
    .bind(&e.kind)
47011487×
    .bind(&e.actor)
47111487×
    .bind(&e.session)
47211487×
    .bind(&e.project)
47311487×
    .bind(&e.subject)
47411487×
    .bind(e.payload.clone())
47511487×
    .bind(&e.trace)
47611487×
    .execute(conn)
47711487×
    .await?;
47811487×
    Ok(())
47911487×
}
480
48140845×
fn row_to_event(r: &SqliteRow) -> Result<Event> {
482
    Ok(Event {
48340845×
        seq: r.get::<i64, _>(0) as u64,
48440845×
        id: r.get(1),
48540845×
        at_ms: r.get::<i64, _>(2) as u64,
48640845×
        hlc: Hlc { wall_ms: r.get::<i64, _>(3) as u64, logical: r.get::<i64, _>(4) as u32 },
48740845×
        prev: to32(r.get(5))?,
48840845×
        hash: to32(r.get(6))?,
489
        auth: Auth {
49040845×
            key: r.get::<Option<Vec<u8>>, _>(7).map(to32).transpose()?,
49140845×
            method: Method::from_u8(r.get::<i64, _>(8) as u8).context("unknown auth method")?,
49240845×
            assurance: r.get::<i64, _>(9) as u8,
49340845×
            proof: r.get(10),
494
        },
49540845×
        kind: r.get(11),
49640845×
        actor: r.get(12),
49740845×
        session: r.get(13),
49840845×
        project: r.get(14),
49940845×
        subject: r.get(15),
50040845×
        payload: r.get(16),
50140845×
        trace: r.get(17),
502
    })
50340845×
}
504
50582000×
fn to32(v: Vec<u8>) -> Result<[u8; 32]> {
50682000×
    v.try_into().map_err(|_| anyhow::anyhow!("a stored hash is not 32 bytes"))
50782000×
}
508
5097×
async fn replay(conn: &mut sqlx::SqliteConnection) -> Result<()> {
51021×
    for t in projections::TABLES {
51121×
        sqlx::query(&format!("DELETE FROM {t}")).execute(&mut *conn).await?;
512
    }
5137×
    let mut from = 1i64;
514
    loop {
51529×
        let rows = sqlx::query(&format!("{SELECT_EVENT} WHERE seq >= ? ORDER BY seq LIMIT 2000")).bind(from).fetch_all(&mut *conn).await?;
51629×
        if rows.is_empty() {
5177×
            break;
51822×
        }
51930254×
        for r in &rows {
52030254×
            let e = row_to_event(r)?;
52130254×
            projections::apply(conn, &e).await?;
52230254×
            from = e.seq as i64 + 1;
523
        }
524
    }
5257×
    Ok(())
5267×
}
527
52830×
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.
53030×
    let rows = sqlx::query(&format!("SELECT * FROM {table} ORDER BY 1, 2")).fetch_all(&mut *conn).await?;
53130×
    Ok(rows
53230×
        .iter()
53384×
        .map(|r| {
53484×
            (0..r.columns().len())
535322×
                .map(|i| match r.try_get::<Option<String>, _>(i) {
536184×
                    Ok(v) => format!("{v:?}"),
537138×
                    Err(_) => match r.try_get::<Option<i64>, _>(i) {
538116×
                        Ok(n) => format!("{n:?}"),
53922×
                        Err(_) => format!("{:?}", r.try_get::<Option<Vec<u8>>, _>(i).ok().flatten()),
540
                    },
541322×
                })
54284×
                .collect::<Vec<_>>()
54384×
                .join("|")
54484×
        })
54530×
        .collect())
54630×
}
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×
}