OXYGENHUB

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

411 of 431 lines run, 130 of 273 functions · run #17 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
    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.
63101×
    pub async fn open(path: &Path, instance: Option<KeyPair>) -> Result<Ledger> {
64101×
        let lock_path = path.with_extension("lock");
65101×
        let lock = std::fs::OpenOptions::new()
66101×
            .create(true)
67101×
            .truncate(false)
68101×
            .write(true)
69101×
            .open(&lock_path)
70101×
            .with_context(|| format!("opening {}", lock_path.display()))?;
71101×
        match lock.try_lock() {
72100×
            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
        }
78100×
        let mut l = Ledger::open_unlocked(path, instance).await?;
7999×
        l._lock = Some(lock);
8099×
        Ok(l)
81101×
    }
82
83
    /// Open for reading and verifying only, while another process may be
84
    /// writing: no lock, and `append` must not be called.
8549×
    pub async fn open_read_only(path: &Path) -> Result<Ledger> {
8649×
        Ledger::open_unlocked(path, None).await
8749×
    }
88
89149×
    async fn open_unlocked(path: &Path, instance: Option<KeyPair>) -> Result<Ledger> {
90149×
        let opts = SqliteConnectOptions::new()
91149×
            .filename(path)
92149×
            .create_if_missing(true)
93149×
            .journal_mode(SqliteJournalMode::Wal)
94149×
            .synchronous(SqliteSynchronous::Normal)
95149×
            .foreign_keys(true)
96149×
            .busy_timeout(std::time::Duration::from_secs(10));
97149×
        let pool =
98149×
            SqlitePoolOptions::new().max_connections(8).connect_with(opts).await.with_context(|| format!("opening {}", path.display()))?;
99149×
        sqlx::migrate!("./migrations").run(&pool).await.context("applying migrations")?;
100149×
        let format: Option<String> = sqlx::query_scalar("SELECT value FROM meta WHERE key = 'ledger_format'").fetch_optional(&pool).await?;
101149×
        match format.as_deref().map(str::parse::<u32>) {
102
            None => {
10341×
                sqlx::query("INSERT INTO meta (key, value) VALUES ('ledger_format', ?)")
10441×
                    .bind(crate::LEDGER_FORMAT.to_string())
10541×
                    .execute(&pool)
10641×
                    .await?;
107
            }
108108×
            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
        }
113148×
        let last =
114148×
            sqlx::query("SELECT seq, hash, hlc_wall, hlc_logical FROM events ORDER BY seq DESC LIMIT 1").fetch_optional(&pool).await?;
115148×
        let (seq, hash, hlc) = match last {
116107×
            Some(r) => (
117107×
                r.get::<i64, _>(0) as u64,
118107×
                to32(r.get::<Vec<u8>, _>(1))?,
119107×
                Hlc { wall_ms: r.get::<i64, _>(2) as u64, logical: r.get::<i64, _>(3) as u32 },
120
            ),
12141×
            None => (0, [0; 32], Hlc::default()),
122
        };
123148×
        let checkpoint_seq: i64 =
124148×
            sqlx::query_scalar("SELECT COALESCE(MAX(seq), 0) FROM events WHERE kind = 'ledger.checkpoint'").fetch_one(&pool).await?;
125148×
        let since = seq.saturating_sub(checkpoint_seq as u64);
126148×
        let (bus, _) = broadcast::channel(4096);
127148×
        Ok(Ledger {
128148×
            pool: pool.clone(),
129148×
            _lock: None,
130148×
            w: Arc::new(Writer {
131148×
                pool,
132148×
                head: Mutex::new(Head { seq, hash, since_checkpoint: since, oldest_unchecked_ms: (since > 0).then(ids::now_ms) }),
133148×
                clock: Clock::starting_at(hlc),
134148×
                bus,
135148×
                instance,
136148×
            }),
137148×
        })
138149×
    }
139
140
    /// The database, for projections' readers.
141433×
    pub fn pool(&self) -> &SqlitePool {
142433×
        &self.pool
143433×
    }
144
145
    /// Every appended event, as it commits.
14618×
    pub fn subscribe(&self) -> broadcast::Receiver<Arc<Event>> {
14718×
        self.w.bus.subscribe()
14818×
    }
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.
15654×
    pub async fn head(&self) -> (u64, [u8; 32]) {
15754×
        let h = self.w.head.lock().await;
15854×
        (h.seq, h.hash)
15954×
    }
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.
1642281×
    pub async fn append(&self, events: Vec<NewEvent>) -> Result<Vec<Arc<Event>>> {
1652281×
        let w = self.w.clone();
1662281×
        tokio::spawn(async move { w.append(events).await }).await.context("the ledger's writer stopped")?
1671981×
    }
168
169
    /// Append one event.
1701800×
    pub async fn append_one(&self, e: NewEvent) -> Result<Arc<Event>> {
1711800×
        Ok(self.append(vec![e]).await?.remove(0))
1721500×
    }
173
174
    /// Write a checkpoint now if any event is not covered by one (at
175
    /// shutdown, and from the ten-minute timer).
17672×
    pub async fn checkpoint(&self) -> Result<Option<Arc<Event>>> {
17772×
        let w = self.w.clone();
17872×
        tokio::spawn(async move { w.checkpoint().await }).await.context("the ledger's writer stopped")?
17972×
    }
180
181
    /// Events from `from` (inclusive), oldest first, at most `limit`.
18273×
    pub async fn events(&self, from: u64, limit: u32) -> Result<Vec<Event>> {
18373×
        let rows = sqlx::query(&format!("{SELECT_EVENT} WHERE seq >= ? ORDER BY seq LIMIT ?"))
18473×
            .bind(from as i64)
18573×
            .bind(limit as i64)
18673×
            .fetch_all(&self.pool)
18773×
            .await?;
18873×
        rows.iter().map(row_to_event).collect()
18973×
    }
190
191
    /// Events of the given kinds from `from` (inclusive), oldest first.
192219×
    pub async fn events_of_kinds(&self, from: u64, kinds: &[&str], limit: u32) -> Result<Vec<Event>> {
193219×
        let marks = vec!["?"; kinds.len()].join(",");
194219×
        let sql = format!("{SELECT_EVENT} WHERE seq >= ? AND kind IN ({marks}) ORDER BY seq LIMIT ?");
195219×
        let mut q = sqlx::query(&sql).bind(from as i64);
1961091×
        for k in kinds {
1971091×
            q = q.bind(*k);
1981091×
        }
199219×
        let rows = q.bind(limit as i64).fetch_all(&self.pool).await?;
200215×
        rows.iter().map(row_to_event).collect()
201215×
    }
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`).
20533×
    pub async fn verify(&self, keys: &mut dyn KeyResolver) -> Result<Verification> {
20633×
        let mut v = Verification::default();
20733×
        let mut prev = [0u8; 32];
20833×
        let mut expect = 1u64;
20933×
        let mut instance: Option<Identity> = None;
21033×
        let mut from = 1;
211
        loop {
21271×
            let batch = self.events(from, 2_000).await?;
21371×
            if batch.is_empty() {
21433×
                break;
21538×
            }
21611073×
            for e in &batch {
21711073×
                v.events += 1;
21811073×
                if e.seq != expect {
2191×
                    v.finding(e.seq, Problem::Gap, format!("expected event {expect}"));
2201×
                    expect = e.seq;
22111072×
                }
22211073×
                if e.prev != prev {
2232×
                    v.finding(e.seq, Problem::ChainBreak, "prev is not the hash of the event before".into());
22411071×
                }
22511073×
                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());
22711071×
                }
22811073×
                if e.kind == "identity.instance" {
22933×
                    instance = e
23033×
                        .json()
23133×
                        .get("identity")
23233×
                        .and_then(|h| h.as_str())
23333×
                        .and_then(|h| hex::decode(h).ok())
23433×
                        .and_then(|b| Identity::decode(&b).ok());
23511040×
                }
23611073×
                if e.kind == "ledger.checkpoint" {
23789×
                    v.checkpoints += 1;
23889×
                    match check_checkpoint(e, prev, instance.as_ref()) {
23987×
                        Ok(()) => v.last_checkpoint = Some(e.seq),
2402×
                        Err(why) => v.finding(e.seq, Problem::BadCheckpoint, why),
241
                    }
24210984×
                } else if let Err(why) = keys.check(e) {
24310×
                    v.finding(e.seq, Problem::BadProof, why);
24410974×
                }
24511073×
                prev = e.hash;
24611073×
                expect += 1;
247
            }
24838×
            from = batch.last().map(|e| e.seq + 1).unwrap_or(from);
249
        }
25033×
        v.head = prev;
25133×
        v.uncovered = v.events.saturating_sub(v.last_checkpoint.unwrap_or(0));
25233×
        Ok(v)
25333×
    }
254
255
    /// Clear every projection and replay the ledger into them.
2562×
    pub async fn rebuild(&self) -> Result<()> {
2572×
        let w = self.w.clone();
2582×
        tokio::spawn(async move { w.rebuild().await }).await.context("the ledger's writer stopped")?
2592×
    }
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.
26311×
    pub async fn check(&self) -> Result<Vec<String>> {
26411×
        let w = self.w.clone();
26511×
        tokio::spawn(async move { w.check().await }).await.context("the ledger's writer stopped")?
26611×
    }
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.
2722281×
    async fn append(&self, events: Vec<NewEvent>) -> Result<Vec<Arc<Event>>> {
2732281×
        let mut head = self.head.lock().await;
2742281×
        let mut tx = self.pool.begin().await?;
2752281×
        let mut out = Vec::with_capacity(events.len() + 1);
2762281×
        let mut h = *head;
27712027×
        for n in events {
27812027×
            let e = self.chain(&mut h, n);
27912027×
            insert(&mut tx, &e).await?;
28012027×
            projections::apply(&mut tx, &e).await?;
28112027×
            h.since_checkpoint += 1;
28212027×
            h.oldest_unchecked_ms.get_or_insert(e.at_ms);
28312027×
            out.push(e);
284
            // Every 256 events exactly, even inside a large batch.
28512027×
            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);
29011983×
            }
291
        }
2922281×
        let due = h.oldest_unchecked_ms.is_some_and(|t| ids::now_ms().saturating_sub(t) >= CHECKPOINT_INTERVAL_MS);
2932281×
        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);
2982281×
        }
2992281×
        tx.commit().await?;
3002281×
        *head = h;
3012281×
        drop(head);
3022281×
        let out: Vec<Arc<Event>> = out.into_iter().map(Arc::new).collect();
30312071×
        for e in &out {
30412071×
            let _ = self.bus.send(e.clone());
30512071×
        }
3062281×
        Ok(out)
3072281×
    }
308
309
    /// Write a checkpoint now if any event is not covered by one (at
310
    /// shutdown, and from the ten-minute timer).
31172×
    async fn checkpoint(&self) -> Result<Option<Arc<Event>>> {
31272×
        let Some(_) = &self.instance else { return Ok(None) };
31372×
        let mut head = self.head.lock().await;
31472×
        if head.since_checkpoint == 0 {
3151×
            return Ok(None);
31671×
        }
31771×
        let mut h = *head;
31871×
        let cp = self.checkpoint_event(&mut h);
31971×
        let mut tx = self.pool.begin().await?;
32071×
        insert(&mut tx, &cp).await?;
32171×
        projections::apply(&mut tx, &cp).await?;
32271×
        tx.commit().await?;
32371×
        *head = h;
32471×
        drop(head);
32571×
        let cp = Arc::new(cp);
32671×
        let _ = self.bus.send(cp.clone());
32771×
        Ok(Some(cp))
32872×
    }
329
33012142×
    fn chain(&self, h: &mut Head, n: NewEvent) -> Event {
33112142×
        let at_ms = ids::now_ms();
33212142×
        let mut e = Event {
33312142×
            seq: h.seq + 1,
33412142×
            id: ids::ulid(),
33512142×
            at_ms,
33612142×
            hlc: self.clock.tick(at_ms),
33712142×
            prev: h.hash,
33812142×
            hash: [0; 32],
33912142×
            auth: n.auth,
34012142×
            kind: n.kind,
34112142×
            actor: n.actor,
34212142×
            session: n.session,
34312142×
            project: n.project,
34412142×
            subject: n.subject,
34512142×
            payload: Some(canonical_json(&n.payload)),
34612142×
            trace: n.trace,
34712142×
        };
34812142×
        e.hash = e.computed_hash();
34912142×
        h.seq = e.seq;
35012142×
        h.hash = e.hash;
35112142×
        e
35212142×
    }
353
354
    /// A checkpoint naming the head `h` holds, signed by the instance key
355
    /// over `"spectra1 checkpoint " || hash || seq` (spec §9.5).
356115×
    fn checkpoint_event(&self, h: &mut Head) -> Event {
357115×
        let instance = self.instance.as_ref().expect("checked by callers");
358115×
        let (seq, hash, count) = (h.seq, h.hash, h.since_checkpoint);
359115×
        let sig = instance.sign(&checkpoint_message(seq, &hash));
360115×
        let n = NewEvent::system("ledger.checkpoint", serde_json::json!({ "seq": seq, "hash": hex::encode(hash), "count": count })).by(
361
            "system",
362115×
            Auth {
363115×
                key: Some(instance.key.0),
364115×
                method: Method::Signature,
365115×
                assurance: 2,
366115×
                proof: Some(oxy_core::cbor::encode(&sig.to_value())),
367115×
            },
368
        );
369115×
        let e = self.chain(h, n);
370115×
        h.since_checkpoint = 0;
371115×
        h.oldest_unchecked_ms = None;
372115×
        e
373115×
    }
374
375
    /// Clear every projection and replay the ledger into them.
3762×
    async fn rebuild(&self) -> Result<()> {
3772×
        let _head = self.head.lock().await;
3782×
        let mut tx = self.pool.begin().await?;
3792×
        replay(&mut tx).await?;
3802×
        tx.commit().await?;
3812×
        Ok(())
3822×
    }
383
384
    /// Whether the projections equal a rebuild from the ledger: rebuild in
385
    /// a transaction, compare, and roll back. Returns the tables that differ.
38611×
    async fn check(&self) -> Result<Vec<String>> {
38711×
        let _head = self.head.lock().await;
38811×
        let mut tx = self.pool.begin().await?;
38911×
        let mut before = Vec::new();
390132×
        for t in projections::TABLES {
391132×
            before.push(dump(&mut tx, t).await?);
392
        }
39311×
        replay(&mut tx).await?;
39411×
        let mut differ = Vec::new();
395132×
        for (t, b) in projections::TABLES.iter().zip(before) {
396132×
            if dump(&mut tx, t).await? != b {
3970×
                differ.push(t.to_string());
398132×
            }
399
        }
40011×
        tx.rollback().await?;
40111×
        Ok(differ)
40211×
    }
403
}
404
405
/// `"spectra1 checkpoint " || hash || seq (8 bytes, big-endian)`.
406204×
pub fn checkpoint_message(seq: u64, hash: &[u8; 32]) -> Vec<u8> {
407204×
    let mut m = CHECKPOINT_DOMAIN.to_vec();
408204×
    m.extend_from_slice(hash);
409204×
    m.extend_from_slice(&seq.to_be_bytes());
410204×
    m
411204×
}
412
41389×
fn check_checkpoint(e: &Event, prev: [u8; 32], instance: Option<&Identity>) -> std::result::Result<(), String> {
41489×
    let p = e.json();
41589×
    let seq = p.get("seq").and_then(|s| s.as_u64()).ok_or("no seq")?;
41689×
    let hash: [u8; 32] =
41789×
        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")?;
41889×
    if seq + 1 != e.seq || hash != prev {
4191×
        return Err("names a head other than the event before it".into());
42088×
    }
42188×
    let instance = instance.ok_or("no instance identity precedes it")?;
42288×
    if e.auth.key != Some(instance.hash().0) {
4230×
        return Err("signed by a key other than the instance's".into());
42488×
    }
42588×
    let proof = e.auth.proof.as_deref().ok_or("unsigned")?;
42688×
    let sig = oxy_core::cbor::decode(proof).ok().and_then(|v| Signature::from_value(&v).ok()).ok_or("malformed signature")?;
42788×
    oxy_core::identity::verify_challenge(instance, &sig, &checkpoint_message(seq, &hash))
42888×
        .map_err(|e| format!("signature does not verify: {e}"))
42989×
}
430
431
/// Checks the proof of a signed event: the identities and delegations that
432
/// say whose key it was (spec §8.5). Principals supply it (`principals`).
433
/// It is given every event but checkpoints, in order, so it can follow
434
/// identities as they are recorded.
435
pub trait KeyResolver: Send {
436
    fn check(&mut self, e: &Event) -> std::result::Result<(), String>;
437
}
438
439
/// A resolver that knows no keys: every signed event is reported.
440
pub struct NoKeys;
441
impl KeyResolver for NoKeys {
44210641×
    fn check(&mut self, e: &Event) -> std::result::Result<(), String> {
44310641×
        match e.auth.method {
4440×
            Method::Signature | Method::Passkey => Err("no identity is known for its key".into()),
44510641×
            _ => Ok(()),
446
        }
44710641×
    }
448
}
449
450
/// What `verify` found.
451
#[derive(Clone, Debug, Default, serde::Serialize)]
452
pub struct Verification {
453
    pub events: u64,
454
    pub checkpoints: u64,
455
    pub last_checkpoint: Option<u64>,
456
    /// Events after the last good checkpoint: chained, not yet signed.
457
    pub uncovered: u64,
458
    #[serde(serialize_with = "ser_hex")]
459
    pub head: [u8; 32],
460
    pub findings: Vec<Finding>,
461
}
462
4639×
fn ser_hex<S: serde::Serializer>(h: &[u8; 32], s: S) -> std::result::Result<S::Ok, S::Error> {
4649×
    s.serialize_str(&hex::encode(h))
4659×
}
466
467
impl Verification {
46826×
    pub fn clean(&self) -> bool {
46926×
        self.findings.is_empty()
47026×
    }
47117×
    fn finding(&mut self, seq: u64, problem: Problem, detail: String) {
47217×
        self.findings.push(Finding { seq, problem, detail });
47317×
    }
474
}
475
476
/// One thing wrong with the ledger.
477
#[derive(Clone, Debug, serde::Serialize)]
478
pub struct Finding {
479
    pub seq: u64,
480
    pub problem: Problem,
481
    pub detail: String,
482
}
483
484
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
485
#[serde(rename_all = "snake_case")]
486
pub enum Problem {
487
    Gap,
488
    ChainBreak,
489
    HashMismatch,
490
    BadCheckpoint,
491
    BadProof,
492
}
493
494
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";
495
49612142×
async fn insert(conn: &mut sqlx::SqliteConnection, e: &Event) -> sqlx::Result<()> {
49712142×
    sqlx::query(
49812142×
        "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) \
49912142×
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
500
    )
50112142×
    .bind(e.seq as i64)
50212142×
    .bind(&e.id)
50312142×
    .bind(e.at_ms as i64)
50412142×
    .bind(e.hlc.wall_ms as i64)
50512142×
    .bind(e.hlc.logical as i64)
50612142×
    .bind(e.prev.to_vec())
50712142×
    .bind(e.hash.to_vec())
50812142×
    .bind(e.auth.key.map(|k| k.to_vec()))
50912142×
    .bind(e.auth.method as i64)
51012142×
    .bind(e.auth.assurance as i64)
51112142×
    .bind(e.auth.proof.clone())
51212142×
    .bind(&e.kind)
51312142×
    .bind(&e.actor)
51412142×
    .bind(&e.session)
51512142×
    .bind(&e.project)
51612142×
    .bind(&e.subject)
51712142×
    .bind(e.payload.clone())
51812142×
    .bind(&e.trace)
51912142×
    .execute(conn)
52012142×
    .await?;
52112142×
    Ok(())
52212142×
}
523
52441840×
fn row_to_event(r: &SqliteRow) -> Result<Event> {
525
    Ok(Event {
52641840×
        seq: r.get::<i64, _>(0) as u64,
52741840×
        id: r.get(1),
52841840×
        at_ms: r.get::<i64, _>(2) as u64,
52941840×
        hlc: Hlc { wall_ms: r.get::<i64, _>(3) as u64, logical: r.get::<i64, _>(4) as u32 },
53041840×
        prev: to32(r.get(5))?,
53141840×
        hash: to32(r.get(6))?,
532
        auth: Auth {
53341840×
            key: r.get::<Option<Vec<u8>>, _>(7).map(to32).transpose()?,
53441840×
            method: Method::from_u8(r.get::<i64, _>(8) as u8).context("unknown auth method")?,
53541840×
            assurance: r.get::<i64, _>(9) as u8,
53641840×
            proof: r.get(10),
537
        },
53841840×
        kind: r.get(11),
53941840×
        actor: r.get(12),
54041840×
        session: r.get(13),
54141840×
        project: r.get(14),
54241840×
        subject: r.get(15),
54341840×
        payload: r.get(16),
54441840×
        trace: r.get(17),
545
    })
54641840×
}
547
54884643×
fn to32(v: Vec<u8>) -> Result<[u8; 32]> {
54984643×
    v.try_into().map_err(|_| anyhow::anyhow!("a stored hash is not 32 bytes"))
55084643×
}
551
55213×
async fn replay(conn: &mut sqlx::SqliteConnection) -> Result<()> {
553156×
    for t in projections::TABLES {
554156×
        sqlx::query(&format!("DELETE FROM {t}")).execute(&mut *conn).await?;
555
    }
55613×
    let mut from = 1i64;
557
    loop {
55841×
        let rows = sqlx::query(&format!("{SELECT_EVENT} WHERE seq >= ? ORDER BY seq LIMIT 2000")).bind(from).fetch_all(&mut *conn).await?;
55941×
        if rows.is_empty() {
56013×
            break;
56128×
        }
56230358×
        for r in &rows {
56330358×
            let e = row_to_event(r)?;
56430358×
            projections::apply(conn, &e).await?;
56530358×
            from = e.seq as i64 + 1;
566
        }
567
    }
56813×
    Ok(())
56913×
}
570
571264×
async fn dump(conn: &mut sqlx::SqliteConnection, table: &str) -> Result<Vec<String>> {
572
    // Every column as text, rows in a fixed order: enough to compare.
573264×
    let rows = sqlx::query(&format!("SELECT * FROM {table} ORDER BY 1, 2")).fetch_all(&mut *conn).await?;
574264×
    Ok(rows
575264×
        .iter()
576426×
        .map(|r| {
577426×
            (0..r.columns().len())
5782264×
                .map(|i| match r.try_get::<Option<String>, _>(i) {
5791608×
                    Ok(v) => format!("{v:?}"),
580656×
                    Err(_) => match r.try_get::<Option<i64>, _>(i) {
581582×
                        Ok(n) => format!("{n:?}"),
58274×
                        Err(_) => format!("{:?}", r.try_get::<Option<Vec<u8>>, _>(i).ok().flatten()),
583
                    },
5842264×
                })
585426×
                .collect::<Vec<_>>()
586426×
                .join("|")
587426×
        })
588264×
        .collect())
589264×
}
590
591
/// The identity of `key` among `identities`, by KeyId.
5920×
pub fn find_identity<'a>(identities: &'a [Identity], key: &KeyId) -> Option<&'a Identity> {
5930×
    identities.iter().find(|i| &i.hash() == key)
5940×
}