OXYGENHUB

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

405 of 425 lines run, 131 of 272 functions · run #32 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::identity::KeyId;
12
use crate::identity::{Identity, Signature};
13
use crate::keys::KeyPair;
14
use crate::{ids, projections};
15
use anyhow::{bail, Context, Result};
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
    w: Arc<Writer>,
36
}
37
38
/// What writing needs, shared with the task that does it. Every write runs
39
/// in a task of its own, so a caller that goes away (a client that hangs up
40
/// mid-request) can never leave a transaction half done: a cancelled
41
/// transaction on a pooled connection would swallow every later commit
42
/// made on that connection.
43
struct Writer {
44
    pool: SqlitePool,
45
    head: Mutex<Head>,
46
    clock: Clock,
47
    bus: broadcast::Sender<Arc<Event>>,
48
    instance: Option<KeyPair>,
49
}
50
51
#[derive(Clone, Copy, Debug)]
52
struct Head {
53
    seq: u64,
54
    hash: [u8; 32],
55
    since_checkpoint: u64,
56
    oldest_unchecked_ms: Option<u64>,
57
}
58
59
impl Ledger {
60
    /// Open (or create) `path`, apply migrations, and refuse a ledger
61
    /// written by a newer format. Checkpoints are signed with `instance`;
62
    /// without one (tests, read-only tools) none are made.
63153×
    pub async fn open(path: &Path, instance: Option<KeyPair>) -> Result<Ledger> {
64153×
        let lock_path = path.with_extension("lock");
65153×
        let lock = std::fs::OpenOptions::new()
66153×
            .create(true)
67153×
            .truncate(false)
68153×
            .write(true)
69153×
            .open(&lock_path)
70153×
            .with_context(|| format!("opening {}", lock_path.display()))?;
71153×
        match lock.try_lock() {
72152×
            Ok(()) => {}
73
            Err(std::fs::TryLockError::WouldBlock) => {
741×
                bail!("another process is writing to {} (is `spectra serve` running? stop it, or do this through it)", path.display())
75
            }
760×
            Err(std::fs::TryLockError::Error(e)) => return Err(e).with_context(|| format!("locking {}", lock_path.display())),
77
        }
78152×
        let mut l = Ledger::open_unlocked(path, instance).await?;
79151×
        l._lock = Some(lock);
80151×
        Ok(l)
81153×
    }
82
83
    /// Open for reading and verifying only, while another process may be
84
    /// writing: no lock, and `append` must not be called.
8576×
    pub async fn open_read_only(path: &Path) -> Result<Ledger> {
8676×
        Ledger::open_unlocked(path, None).await
8776×
    }
88
89228×
    async fn open_unlocked(path: &Path, instance: Option<KeyPair>) -> Result<Ledger> {
90228×
        let opts = SqliteConnectOptions::new()
91228×
            .filename(path)
92228×
            .create_if_missing(true)
93228×
            .journal_mode(SqliteJournalMode::Wal)
94228×
            .synchronous(SqliteSynchronous::Normal)
95228×
            .foreign_keys(true)
96228×
            .busy_timeout(std::time::Duration::from_secs(10));
97228×
        let pool =
98228×
            SqlitePoolOptions::new().max_connections(8).connect_with(opts).await.with_context(|| format!("opening {}", path.display()))?;
99228×
        sqlx::migrate!("./migrations").run(&pool).await.context("applying migrations")?;
100228×
        let format: Option<String> = sqlx::query_scalar("SELECT value FROM meta WHERE key = 'ledger_format'").fetch_optional(&pool).await?;
101228×
        match format.as_deref().map(str::parse::<u32>) {
102
            None => {
10353×
                sqlx::query("INSERT INTO meta (key, value) VALUES ('ledger_format', ?)")
10453×
                    .bind(crate::LEDGER_FORMAT.to_string())
10553×
                    .execute(&pool)
10653×
                    .await?;
107
            }
108175×
            Some(Ok(f)) if f <= crate::LEDGER_FORMAT => {}
109
            Some(_) => {
1101×
                bail!("{} was written by a newer Spectra (ledger format {}): upgrade spectra", path.display(), format.unwrap_or_default())
111
            }
112
        }
113227×
        let last =
114227×
            sqlx::query("SELECT seq, hash, hlc_wall, hlc_logical FROM events ORDER BY seq DESC LIMIT 1").fetch_optional(&pool).await?;
115227×
        let (seq, hash, hlc) = match last {
116174×
            Some(r) => (
117174×
                r.get::<i64, _>(0) as u64,
118174×
                to32(r.get::<Vec<u8>, _>(1))?,
119174×
                Hlc { wall_ms: r.get::<i64, _>(2) as u64, logical: r.get::<i64, _>(3) as u32 },
120
            ),
12153×
            None => (0, [0; 32], Hlc::default()),
122
        };
123227×
        let checkpoint_seq: i64 =
124227×
            sqlx::query_scalar("SELECT COALESCE(MAX(seq), 0) FROM events WHERE kind = 'ledger.checkpoint'").fetch_one(&pool).await?;
125227×
        let since = seq.saturating_sub(checkpoint_seq as u64);
126227×
        let (bus, _) = broadcast::channel(4096);
127227×
        Ok(Ledger {
128227×
            pool: pool.clone(),
129227×
            _lock: None,
130227×
            w: Arc::new(Writer {
131227×
                pool,
132227×
                head: Mutex::new(Head { seq, hash, since_checkpoint: since, oldest_unchecked_ms: (since > 0).then(ids::now_ms) }),
133227×
                clock: Clock::starting_at(hlc),
134227×
                bus,
135227×
                instance,
136227×
            }),
137227×
        })
138228×
    }
139
140
    /// The database, for projections' readers.
141776×
    pub fn pool(&self) -> &SqlitePool {
142776×
        &self.pool
143776×
    }
144
145
    /// Every appended event, as it commits.
14631×
    pub fn subscribe(&self) -> broadcast::Receiver<Arc<Event>> {
14731×
        self.w.bus.subscribe()
14831×
    }
149
150
    /// The instance key, when this ledger signs checkpoints.
1510×
    pub fn instance(&self) -> Option<&KeyPair> {
1520×
        self.w.instance.as_ref()
1530×
    }
154
155
    /// The newest event's sequence number and hash.
15695×
    pub async fn head(&self) -> (u64, [u8; 32]) {
15795×
        let h = self.w.head.lock().await;
15895×
        (h.seq, h.hash)
15995×
    }
160
161
    /// Append `events` in one transaction, chained and projected, then
162
    /// publish them; a checkpoint follows when one is due. The work runs to
163
    /// completion even if the caller is dropped.
1642391×
    pub async fn append(&self, events: Vec<NewEvent>) -> Result<Vec<Arc<Event>>> {
1652391×
        let w = self.w.clone();
1662391×
        tokio::spawn(async move { w.append(events).await }).await.context("the ledger's writer stopped")?
1672091×
    }
168
169
    /// Append one event.
1701850×
    pub async fn append_one(&self, e: NewEvent) -> Result<Arc<Event>> {
1711850×
        Ok(self.append(vec![e]).await?.remove(0))
1721550×
    }
173
174
    /// Write a checkpoint now if any event is not covered by one (at
175
    /// shutdown, and from the ten-minute timer).
176132×
    pub async fn checkpoint(&self) -> Result<Option<Arc<Event>>> {
177132×
        let w = self.w.clone();
178132×
        tokio::spawn(async move { w.checkpoint().await }).await.context("the ledger's writer stopped")?
179132×
    }
180
181
    /// Events from `from` (inclusive), oldest first, at most `limit`.
18291×
    pub async fn events(&self, from: u64, limit: u32) -> Result<Vec<Event>> {
18391×
        let rows = sqlx::query(&format!("{SELECT_EVENT} WHERE seq >= ? ORDER BY seq LIMIT ?"))
18491×
            .bind(from as i64)
18591×
            .bind(limit as i64)
18691×
            .fetch_all(&self.pool)
18791×
            .await?;
18891×
        rows.iter().map(row_to_event).collect()
18991×
    }
190
191
    /// Events of the given kinds from `from` (inclusive), oldest first.
192485×
    pub async fn events_of_kinds(&self, from: u64, kinds: &[&str], limit: u32) -> Result<Vec<Event>> {
193485×
        let marks = vec!["?"; kinds.len()].join(",");
194485×
        let sql = format!("{SELECT_EVENT} WHERE seq >= ? AND kind IN ({marks}) ORDER BY seq LIMIT ?");
195485×
        let mut q = sqlx::query(&sql).bind(from as i64);
1962535×
        for k in kinds {
1972535×
            q = q.bind(*k);
1982535×
        }
199485×
        let rows = q.bind(limit as i64).fetch_all(&self.pool).await?;
200481×
        rows.iter().map(row_to_event).collect()
201481×
    }
202
203
    /// Recompute the chain and check every checkpoint and every proof it
204
    /// can, from the ledger alone (spec §9.5, `spectra admin verify`).
20542×
    pub async fn verify(&self, keys: &mut dyn KeyResolver) -> Result<Verification> {
20642×
        let mut v = Verification::default();
20742×
        let mut prev = [0u8; 32];
20842×
        let mut expect = 1u64;
20942×
        let mut instance: Option<Identity> = None;
21042×
        let mut from = 1;
211
        loop {
21289×
            let batch = self.events(from, 2_000).await?;
21389×
            if batch.is_empty() {
21442×
                break;
21547×
            }
21611273×
            for e in &batch {
21711273×
                v.events += 1;
21811273×
                if e.seq != expect {
2191×
                    v.finding(e.seq, Problem::Gap, format!("expected event {expect}"));
2201×
                    expect = e.seq;
22111272×
                }
22211273×
                if e.prev != prev {
2232×
                    v.finding(e.seq, Problem::ChainBreak, "prev is not the hash of the event before".into());
22411271×
                }
22511273×
                if e.payload.is_some() && e.computed_hash() != e.hash {
2262×
                    v.finding(e.seq, Problem::HashMismatch, "the event's fields do not give its hash: it was edited".into());
22711271×
                }
22811273×
                if e.kind == "identity.instance" {
22942×
                    instance = e
23042×
                        .json()
23142×
                        .get("identity")
23242×
                        .and_then(|h| h.as_str())
23342×
                        .and_then(|h| hex::decode(h).ok())
23442×
                        .and_then(|b| Identity::decode(&b).ok());
23511231×
                }
23611273×
                if e.kind == "ledger.checkpoint" {
237140×
                    v.checkpoints += 1;
238140×
                    match check_checkpoint(e, prev, instance.as_ref()) {
239138×
                        Ok(()) => v.last_checkpoint = Some(e.seq),
2402×
                        Err(why) => v.finding(e.seq, Problem::BadCheckpoint, why),
241
                    }
24211133×
                } else if let Err(why) = keys.check(e) {
24310×
                    v.finding(e.seq, Problem::BadProof, why);
24411123×
                }
24511273×
                prev = e.hash;
24611273×
                expect += 1;
247
            }
24847×
            from = batch.last().map(|e| e.seq + 1).unwrap_or(from);
249
        }
25042×
        v.head = prev;
25142×
        v.uncovered = v.events.saturating_sub(v.last_checkpoint.unwrap_or(0));
25242×
        Ok(v)
25342×
    }
254
255
    /// Clear every projection and replay the ledger into them.
2565×
    pub async fn rebuild(&self) -> Result<()> {
2575×
        let w = self.w.clone();
2585×
        tokio::spawn(async move { w.rebuild().await }).await.context("the ledger's writer stopped")?
2595×
    }
260
261
    /// Whether the projections equal a rebuild from the ledger: rebuild in
262
    /// a transaction, compare, and roll back. Returns the tables that differ.
26313×
    pub async fn check(&self) -> Result<Vec<String>> {
26413×
        let w = self.w.clone();
26513×
        tokio::spawn(async move { w.check().await }).await.context("the ledger's writer stopped")?
26613×
    }
267
}
268
269
impl Writer {
270
    /// Append `events` in one transaction, chained and projected, then
271
    /// publish them; a checkpoint follows when one is due.
2722391×
    async fn append(&self, events: Vec<NewEvent>) -> Result<Vec<Arc<Event>>> {
2732391×
        let mut head = self.head.lock().await;
2742391×
        let mut tx = self.pool.begin().await?;
2752391×
        let mut out = Vec::with_capacity(events.len() + 1);
2762391×
        let mut h = *head;
27712192×
        for n in events {
27812192×
            let e = self.chain(&mut h, n);
27912192×
            insert(&mut tx, &e).await?;
28012192×
            projections::apply(&mut tx, &e).await?;
28112192×
            h.since_checkpoint += 1;
28212192×
            h.oldest_unchecked_ms.get_or_insert(e.at_ms);
28312192×
            out.push(e);
284
            // Every 256 events exactly, even inside a large batch.
28512192×
            if h.since_checkpoint >= CHECKPOINT_EVERY && self.instance.is_some() {
28644×
                let cp = self.checkpoint_event(&mut h);
28744×
                insert(&mut tx, &cp).await?;
28844×
                projections::apply(&mut tx, &cp).await?;
28944×
                out.push(cp);
29012148×
            }
291
        }
2922391×
        let due = h.oldest_unchecked_ms.is_some_and(|t| ids::now_ms().saturating_sub(t) >= CHECKPOINT_INTERVAL_MS);
2932391×
        if due && self.instance.is_some() {
2940×
            let cp = self.checkpoint_event(&mut h);
2950×
            insert(&mut tx, &cp).await?;
2960×
            projections::apply(&mut tx, &cp).await?;
2970×
            out.push(cp);
2982391×
        }
2992391×
        tx.commit().await?;
3002391×
        *head = h;
3012391×
        drop(head);
3022391×
        let out: Vec<Arc<Event>> = out.into_iter().map(Arc::new).collect();
30312236×
        for e in &out {
30412236×
            let _ = self.bus.send(e.clone());
30512236×
        }
3062391×
        Ok(out)
3072391×
    }
308
309
    /// Write a checkpoint now if any event is not covered by one (at
310
    /// shutdown, and from the ten-minute timer).
311132×
    async fn checkpoint(&self) -> Result<Option<Arc<Event>>> {
312132×
        let Some(_) = &self.instance else { return Ok(None) };
313132×
        let mut head = self.head.lock().await;
314132×
        if head.since_checkpoint == 0 {
3154×
            return Ok(None);
316128×
        }
317128×
        let mut h = *head;
318128×
        let cp = self.checkpoint_event(&mut h);
319128×
        let mut tx = self.pool.begin().await?;
320128×
        insert(&mut tx, &cp).await?;
321128×
        projections::apply(&mut tx, &cp).await?;
322128×
        tx.commit().await?;
323128×
        *head = h;
324128×
        drop(head);
325128×
        let cp = Arc::new(cp);
326128×
        let _ = self.bus.send(cp.clone());
327128×
        Ok(Some(cp))
328132×
    }
329
33012364×
    fn chain(&self, h: &mut Head, n: NewEvent) -> Event {
33112364×
        let at_ms = ids::now_ms();
33212364×
        let mut e = Event {
33312364×
            seq: h.seq + 1,
33412364×
            id: ids::ulid(),
33512364×
            at_ms,
33612364×
            hlc: self.clock.tick(at_ms),
33712364×
            prev: h.hash,
33812364×
            hash: [0; 32],
33912364×
            auth: n.auth,
34012364×
            kind: n.kind,
34112364×
            actor: n.actor,
34212364×
            session: n.session,
34312364×
            project: n.project,
34412364×
            subject: n.subject,
34512364×
            payload: Some(canonical_json(&n.payload)),
34612364×
            trace: n.trace,
34712364×
        };
34812364×
        e.hash = e.computed_hash();
34912364×
        h.seq = e.seq;
35012364×
        h.hash = e.hash;
35112364×
        e
35212364×
    }
353
354
    /// A checkpoint naming the head `h` holds, signed by the instance key
355
    /// over `"spectra1 checkpoint " || hash || seq` (spec §9.5).
356172×
    fn checkpoint_event(&self, h: &mut Head) -> Event {
357172×
        let instance = self.instance.as_ref().expect("checked by callers");
358172×
        let (seq, hash, count) = (h.seq, h.hash, h.since_checkpoint);
359172×
        let sig = instance.sign(&checkpoint_message(seq, &hash));
360172×
        let n = NewEvent::system("ledger.checkpoint", serde_json::json!({ "seq": seq, "hash": hex::encode(hash), "count": count })).by(
361
            "system",
362172×
            Auth { key: Some(instance.key.0), method: Method::Signature, assurance: 2, proof: Some(crate::cbor::encode(&sig.to_value())) },
363
        );
364172×
        let e = self.chain(h, n);
365172×
        h.since_checkpoint = 0;
366172×
        h.oldest_unchecked_ms = None;
367172×
        e
368172×
    }
369
370
    /// Clear every projection and replay the ledger into them.
3715×
    async fn rebuild(&self) -> Result<()> {
3725×
        let _head = self.head.lock().await;
3735×
        let mut tx = self.pool.begin().await?;
3745×
        replay(&mut tx).await?;
3755×
        tx.commit().await?;
3765×
        Ok(())
3775×
    }
378
379
    /// Whether the projections equal a rebuild from the ledger: rebuild in
380
    /// a transaction, compare, and roll back. Returns the tables that differ.
38113×
    async fn check(&self) -> Result<Vec<String>> {
38213×
        let _head = self.head.lock().await;
38313×
        let mut tx = self.pool.begin().await?;
38413×
        let mut before = Vec::new();
385169×
        for t in projections::TABLES {
386169×
            before.push(dump(&mut tx, t).await?);
387
        }
38813×
        replay(&mut tx).await?;
38913×
        let mut differ = Vec::new();
390169×
        for (t, b) in projections::TABLES.iter().zip(before) {
391169×
            if dump(&mut tx, t).await? != b {
3920×
                differ.push(t.to_string());
393169×
            }
394
        }
39513×
        tx.rollback().await?;
39613×
        Ok(differ)
39713×
    }
398
}
399
400
/// `"spectra1 checkpoint " || hash || seq (8 bytes, big-endian)`.
401312×
pub fn checkpoint_message(seq: u64, hash: &[u8; 32]) -> Vec<u8> {
402312×
    let mut m = CHECKPOINT_DOMAIN.to_vec();
403312×
    m.extend_from_slice(hash);
404312×
    m.extend_from_slice(&seq.to_be_bytes());
405312×
    m
406312×
}
407
408140×
fn check_checkpoint(e: &Event, prev: [u8; 32], instance: Option<&Identity>) -> std::result::Result<(), String> {
409140×
    let p = e.json();
410140×
    let seq = p.get("seq").and_then(|s| s.as_u64()).ok_or("no seq")?;
411140×
    let hash: [u8; 32] =
412140×
        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")?;
413140×
    if seq + 1 != e.seq || hash != prev {
4141×
        return Err("names a head other than the event before it".into());
415139×
    }
416139×
    let instance = instance.ok_or("no instance identity precedes it")?;
417139×
    if e.auth.key != Some(instance.hash().0) {
4180×
        return Err("signed by a key other than the instance's".into());
419139×
    }
420139×
    let proof = e.auth.proof.as_deref().ok_or("unsigned")?;
421139×
    let sig = crate::cbor::decode(proof).ok().and_then(|v| Signature::from_value(&v).ok()).ok_or("malformed signature")?;
422139×
    crate::identity::verify(instance, &sig, &checkpoint_message(seq, &hash)).map_err(|e| format!("signature does not verify: {e}"))
423140×
}
424
425
/// Checks the proof of a signed event: the identities and delegations that
426
/// say whose key it was (spec §8.5). Principals supply it (`principals`).
427
/// It is given every event but checkpoints, in order, so it can follow
428
/// identities as they are recorded.
429
pub trait KeyResolver: Send {
430
    fn check(&mut self, e: &Event) -> std::result::Result<(), String>;
431
}
432
433
/// A resolver that knows no keys: every signed event is reported.
434
pub struct NoKeys;
435
impl KeyResolver for NoKeys {
43610641×
    fn check(&mut self, e: &Event) -> std::result::Result<(), String> {
43710641×
        match e.auth.method {
4380×
            Method::Signature | Method::Passkey => Err("no identity is known for its key".into()),
43910641×
            _ => Ok(()),
440
        }
44110641×
    }
442
}
443
444
/// What `verify` found.
445
#[derive(Clone, Debug, Default, serde::Serialize)]
446
pub struct Verification {
447
    pub events: u64,
448
    pub checkpoints: u64,
449
    pub last_checkpoint: Option<u64>,
450
    /// Events after the last good checkpoint: chained, not yet signed.
451
    pub uncovered: u64,
452
    #[serde(serialize_with = "ser_hex")]
453
    pub head: [u8; 32],
454
    pub findings: Vec<Finding>,
455
}
456
45722×
fn ser_hex<S: serde::Serializer>(h: &[u8; 32], s: S) -> std::result::Result<S::Ok, S::Error> {
45822×
    s.serialize_str(&hex::encode(h))
45922×
}
460
461
impl Verification {
4629×
    pub fn clean(&self) -> bool {
4639×
        self.findings.is_empty()
4649×
    }
46517×
    fn finding(&mut self, seq: u64, problem: Problem, detail: String) {
46617×
        self.findings.push(Finding { seq, problem, detail });
46717×
    }
468
}
469
470
/// One thing wrong with the ledger.
471
#[derive(Clone, Debug, serde::Serialize)]
472
pub struct Finding {
473
    pub seq: u64,
474
    pub problem: Problem,
475
    pub detail: String,
476
}
477
478
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
479
#[serde(rename_all = "snake_case")]
480
pub enum Problem {
481
    Gap,
482
    ChainBreak,
483
    HashMismatch,
484
    BadCheckpoint,
485
    BadProof,
486
}
487
488
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";
489
49012364×
async fn insert(conn: &mut sqlx::SqliteConnection, e: &Event) -> sqlx::Result<()> {
49112364×
    sqlx::query(
49212364×
        "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) \
49312364×
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
494
    )
49512364×
    .bind(e.seq as i64)
49612364×
    .bind(&e.id)
49712364×
    .bind(e.at_ms as i64)
49812364×
    .bind(e.hlc.wall_ms as i64)
49912364×
    .bind(e.hlc.logical as i64)
50012364×
    .bind(e.prev.to_vec())
50112364×
    .bind(e.hash.to_vec())
50212364×
    .bind(e.auth.key.map(|k| k.to_vec()))
50312364×
    .bind(e.auth.method as i64)
50412364×
    .bind(e.auth.assurance as i64)
50512364×
    .bind(e.auth.proof.clone())
50612364×
    .bind(&e.kind)
50712364×
    .bind(&e.actor)
50812364×
    .bind(&e.session)
50912364×
    .bind(&e.project)
51012364×
    .bind(&e.subject)
51112364×
    .bind(e.payload.clone())
51212364×
    .bind(&e.trace)
51312364×
    .execute(conn)
51412364×
    .await?;
51512364×
    Ok(())
51612364×
}
517
51842613×
fn row_to_event(r: &SqliteRow) -> Result<Event> {
519
    Ok(Event {
52042613×
        seq: r.get::<i64, _>(0) as u64,
52142613×
        id: r.get(1),
52242613×
        at_ms: r.get::<i64, _>(2) as u64,
52342613×
        hlc: Hlc { wall_ms: r.get::<i64, _>(3) as u64, logical: r.get::<i64, _>(4) as u32 },
52442613×
        prev: to32(r.get(5))?,
52542613×
        hash: to32(r.get(6))?,
526
        auth: Auth {
52742613×
            key: r.get::<Option<Vec<u8>>, _>(7).map(to32).transpose()?,
52842613×
            method: Method::from_u8(r.get::<i64, _>(8) as u8).context("unknown auth method")?,
52942613×
            assurance: r.get::<i64, _>(9) as u8,
53042613×
            proof: r.get(10),
531
        },
53242613×
        kind: r.get(11),
53342613×
        actor: r.get(12),
53442613×
        session: r.get(13),
53542613×
        project: r.get(14),
53642613×
        subject: r.get(15),
53742613×
        payload: r.get(16),
53842613×
        trace: r.get(17),
539
    })
54042613×
}
541
54286959×
fn to32(v: Vec<u8>) -> Result<[u8; 32]> {
54386959×
    v.try_into().map_err(|_| anyhow::anyhow!("a stored hash is not 32 bytes"))
54486959×
}
545
54618×
async fn replay(conn: &mut sqlx::SqliteConnection) -> Result<()> {
547234×
    for t in projections::TABLES {
548234×
        sqlx::query(&format!("DELETE FROM {t}")).execute(&mut *conn).await?;
549
    }
55018×
    let mut from = 1i64;
551
    loop {
55251×
        let rows = sqlx::query(&format!("{SELECT_EVENT} WHERE seq >= ? ORDER BY seq LIMIT 2000")).bind(from).fetch_all(&mut *conn).await?;
55351×
        if rows.is_empty() {
55418×
            break;
55533×
        }
55630505×
        for r in &rows {
55730505×
            let e = row_to_event(r)?;
55830505×
            projections::apply(conn, &e).await?;
55930505×
            from = e.seq as i64 + 1;
560
        }
561
    }
56218×
    Ok(())
56318×
}
564
565338×
async fn dump(conn: &mut sqlx::SqliteConnection, table: &str) -> Result<Vec<String>> {
566
    // Every column as text, rows in a fixed order: enough to compare.
567338×
    let rows = sqlx::query(&format!("SELECT * FROM {table} ORDER BY 1, 2")).fetch_all(&mut *conn).await?;
568338×
    Ok(rows
569338×
        .iter()
570538×
        .map(|r| {
571538×
            (0..r.columns().len())
5722816×
                .map(|i| match r.try_get::<Option<String>, _>(i) {
5731980×
                    Ok(v) => format!("{v:?}"),
574836×
                    Err(_) => match r.try_get::<Option<i64>, _>(i) {
575738×
                        Ok(n) => format!("{n:?}"),
57698×
                        Err(_) => format!("{:?}", r.try_get::<Option<Vec<u8>>, _>(i).ok().flatten()),
577
                    },
5782816×
                })
579538×
                .collect::<Vec<_>>()
580538×
                .join("|")
581538×
        })
582338×
        .collect())
583338×
}
584
585
/// The identity of `key` among `identities`, by KeyId.
5860×
pub fn find_identity<'a>(identities: &'a [Identity], key: &KeyId) -> Option<&'a Identity> {
5870×
    identities.iter().find(|i| &i.hash() == key)
5880×
}