Skip to main content

lean_ctx_cloud/replica/
store.rs

1// SPDX-License-Identifier: Apache-2.0
2//! The local replica of one place (SPEC-ENGINE §3.4.1):
3//! `<data>/cloud/replica/<place_id>/replica.db`, SQLite in WAL mode with
4//! `secure_delete`, every text column encrypted under the place's replica
5//! key `rk` ([`super::crypt`]). Ids, node types and edge structure stay
6//! plaintext so folding and graph queries never decrypt.
7//!
8//! Keys that could confirm a guessed statement (`dedupe_keys`,
9//! `purge_deny`) are stored as `blake3_keyed(rk, dk)`, so a copied
10//! `replica.db` without `mk` reveals nothing about known statements.
11
12use std::path::{Path, PathBuf};
13
14use rusqlite::{Connection, OptionalExtension as _, params};
15
16use super::crypt::{self, Key};
17use crate::CloudError;
18use crate::capture::dedupe::Signature;
19
20/// Schema version this engine writes (`PRAGMA user_version`).
21pub const SCHEMA_VERSION: i64 = 1;
22
23const SCHEMA_V1: &str = "
24CREATE TABLE events (
25    seq INTEGER PRIMARY KEY,
26    event_id TEXT NOT NULL UNIQUE,
27    op TEXT NOT NULL,
28    target TEXT NOT NULL,
29    hlc_wall INTEGER NOT NULL,
30    hlc_ctr INTEGER NOT NULL,
31    provenance TEXT,
32    review_state TEXT,
33    reviewed_by TEXT,
34    batch_id TEXT,
35    purged INTEGER NOT NULL DEFAULT 0,
36    sig_invalid INTEGER NOT NULL DEFAULT 0,
37    withheld INTEGER NOT NULL DEFAULT 0,
38    key_lost INTEGER NOT NULL DEFAULT 0,
39    converted INTEGER NOT NULL DEFAULT 0,
40    body_ct BLOB,
41    ck_ct BLOB,
42    worker_id_ct BLOB,
43    envelope_ct BLOB,
44    leaf_ct BLOB
45);
46CREATE TABLE pending (
47    event_id TEXT PRIMARY KEY,
48    hlc_wall INTEGER NOT NULL,
49    hlc_ctr INTEGER NOT NULL,
50    outbox_id TEXT,
51    event_ct BLOB NOT NULL
52);
53CREATE TABLE nodes (
54    node_id TEXT PRIMARY KEY,
55    node_type TEXT NOT NULL,
56    last_seq INTEGER NOT NULL,
57    retracted INTEGER NOT NULL DEFAULT 0,
58    bucket TEXT,
59    provenance TEXT,
60    review_state TEXT,
61    reviewed_by TEXT,
62    fields_ct BLOB
63);
64CREATE TABLE edges (
65    edge_id TEXT PRIMARY KEY,
66    kind TEXT NOT NULL,
67    from_id TEXT NOT NULL,
68    to_id TEXT NOT NULL,
69    last_seq INTEGER NOT NULL,
70    retracted INTEGER NOT NULL DEFAULT 0
71);
72CREATE INDEX edges_from ON edges(from_id);
73CREATE INDEX edges_to ON edges(to_id);
74CREATE TABLE dedupe_keys (key BLOB PRIMARY KEY, node_id TEXT NOT NULL);
75CREATE TABLE minhash (node_id TEXT PRIMARY KEY, sig_ct BLOB NOT NULL);
76CREATE TABLE purge_deny (key BLOB PRIMARY KEY, reason TEXT NOT NULL);
77CREATE TABLE bus_cache (
78    bus_kind TEXT NOT NULL,
79    bus_ws TEXT NOT NULL,
80    bus_id TEXT NOT NULL,
81    seq INTEGER NOT NULL,
82    fetched_at INTEGER NOT NULL,
83    msg_ct BLOB NOT NULL,
84    PRIMARY KEY (bus_kind, bus_ws, bus_id, seq)
85);
86CREATE TABLE own_sources (
87    node_id TEXT PRIMARY KEY,
88    source_kind TEXT NOT NULL,
89    source_ref_ct BLOB NOT NULL
90);
91CREATE TABLE meta (k TEXT PRIMARY KEY, v BLOB NOT NULL);
92";
93
94/// The four purge reasons (owner decision 23.10.).
95pub const PURGE_REASONS: [&str; 4] = [
96    "leaked_secret",
97    "gdpr_erasure",
98    "retention_schedule",
99    "illegal_content",
100];
101
102/// Where an own-authored node's text came from (for the local-store purge).
103pub const SOURCE_KINDS: [&str; 4] = ["fact", "diary", "session_finding", "episode"];
104
105/// Meta keys; every value is encrypted except the wrapped `rk`.
106const META_RK: &str = "rk_wrapped";
107pub const META_CURSOR: &str = "cursor";
108pub const META_SNAPSHOT_REV: &str = "snapshot_rev";
109pub const META_PLACE_NAME: &str = "place_name";
110pub const META_ID_SALT: &str = "id_salt";
111pub const META_EPOCH: &str = "epoch";
112const META_PURGE_ACKS: &str = "purge_acks";
113
114/// Purge acknowledgements of a place (E9 / `purge_acks[]` on E5).
115#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
116pub struct PurgeAcks {
117    /// Made and not yet accepted: `(purge_id, seq, applied_at)`.
118    pub pending: Vec<(String, u64, u64)>,
119    /// Accepted by the place: `(purge_id, seq)`.
120    pub sent: std::collections::BTreeSet<(String, u64)>,
121}
122
123/// How a replica came to be open.
124#[derive(Debug, Clone, Copy, PartialEq, Eq)]
125pub enum Opened {
126    Existing,
127    Created,
128    /// `rk` no longer unwrapped (`replica_key_missing`): the place was
129    /// deleted and starts empty; the next sync clones it again.
130    RebuiltKeyMissing,
131}
132
133/// An open replica.
134pub struct Replica {
135    pub(super) conn: Connection,
136    place_id: String,
137    rk: Key,
138    dir: PathBuf,
139}
140
141impl std::fmt::Debug for Replica {
142    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
143        f.debug_struct("Replica")
144            .field("place_id", &self.place_id)
145            .finish_non_exhaustive()
146    }
147}
148
149#[allow(clippy::needless_pass_by_value)] // used as `map_err(db_err)`
150pub(super) fn db_err(e: rusqlite::Error) -> CloudError {
151    CloudError::Local(format!("replica: {e}"))
152}
153
154/// A place id is a path segment here: letters, digits, `_` and `-` only.
155fn place_ok(place_id: &str) -> bool {
156    (1..=64).contains(&place_id.len())
157        && place_id
158            .bytes()
159            .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
160}
161
162/// `<data>/cloud/replica/<place_id>`.
163pub fn place_dir(data_dir: &Path, place_id: &str) -> PathBuf {
164    data_dir.join("replica").join(place_id)
165}
166
167fn private_dir(dir: &Path) -> Result<(), CloudError> {
168    std::fs::create_dir_all(dir).map_err(|e| CloudError::Local(e.to_string()))?;
169    #[cfg(unix)]
170    {
171        use std::os::unix::fs::PermissionsExt as _;
172        std::fs::set_permissions(dir, std::fs::Permissions::from_mode(0o700))
173            .map_err(|e| CloudError::Local(e.to_string()))?;
174    }
175    Ok(())
176}
177
178impl Replica {
179    /// Open (or create) the replica of `place_id` with the machine key `mk`.
180    pub fn open(
181        data_dir: &Path,
182        place_id: &str,
183        mk: &[u8; 32],
184    ) -> Result<(Self, Opened), CloudError> {
185        if !place_ok(place_id) {
186            return Err(CloudError::Protocol(format!("place id {place_id:?}")));
187        }
188        let dir = place_dir(data_dir, place_id);
189        let existed = dir.join("replica.db").exists();
190        if let Some(replica) = Self::open_at(&dir, place_id, mk)? {
191            let opened = if existed {
192                Opened::Existing
193            } else {
194                Opened::Created
195            };
196            return Ok((replica, opened));
197        }
198        std::fs::remove_dir_all(&dir).map_err(|e| CloudError::Local(e.to_string()))?;
199        let replica = Self::open_at(&dir, place_id, mk)?
200            .ok_or_else(|| CloudError::Local("replica: fresh key does not open".into()))?;
201        Ok((replica, Opened::RebuiltKeyMissing))
202    }
203
204    /// `None` when the stored `rk` does not unwrap under `mk`.
205    fn open_at(dir: &Path, place_id: &str, mk: &[u8; 32]) -> Result<Option<Self>, CloudError> {
206        private_dir(dir)?;
207        let path = dir.join("replica.db");
208        let mut conn = Connection::open(&path).map_err(db_err)?;
209        #[cfg(unix)]
210        {
211            use std::os::unix::fs::PermissionsExt as _;
212            std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))
213                .map_err(|e| CloudError::Local(e.to_string()))?;
214        }
215        conn.pragma_update(None, "journal_mode", "WAL")
216            .map_err(db_err)?;
217        conn.pragma_update(None, "secure_delete", "ON")
218            .map_err(db_err)?;
219        conn.pragma_update(None, "foreign_keys", "ON")
220            .map_err(db_err)?;
221        let version: i64 = conn
222            .pragma_query_value(None, "user_version", |r| r.get(0))
223            .map_err(db_err)?;
224        if version > SCHEMA_VERSION {
225            return Err(CloudError::Config(format!(
226                "engine_too_old: replica schema {version}, this instance knows {SCHEMA_VERSION}"
227            )));
228        }
229        if version == 0 {
230            let rk = crypt::new_replica_key()?;
231            let wrapped = crypt::wrap(mk, place_id, &rk)?;
232            // Schema, wrapped key and version in one transaction: a crash in
233            // between leaves version 0 and the next open starts over.
234            let tx = conn.transaction().map_err(db_err)?;
235            tx.execute_batch(SCHEMA_V1).map_err(db_err)?;
236            tx.execute_batch(super::history::SCHEMA).map_err(db_err)?;
237            tx.execute(
238                "INSERT INTO meta (k, v) VALUES (?1, ?2)",
239                params![META_RK, wrapped],
240            )
241            .map_err(db_err)?;
242            tx.pragma_update(None, "user_version", SCHEMA_VERSION)
243                .map_err(db_err)?;
244            tx.commit().map_err(db_err)?;
245            return Ok(Some(Self {
246                conn,
247                place_id: place_id.to_string(),
248                rk,
249                dir: dir.to_path_buf(),
250            }));
251        }
252        let wrapped: Option<Vec<u8>> = conn
253            .query_row("SELECT v FROM meta WHERE k = ?1", [META_RK], |r| r.get(0))
254            .optional()
255            .map_err(db_err)?;
256        let Some(rk) = wrapped.and_then(|w| crypt::unwrap(mk, place_id, &w)) else {
257            return Ok(None);
258        };
259        // Tables added within schema 1 before any replica was live.
260        conn.execute_batch(super::history::SCHEMA).map_err(db_err)?;
261        Ok(Some(Self {
262            conn,
263            place_id: place_id.to_string(),
264            rk,
265            dir: dir.to_path_buf(),
266        }))
267    }
268
269    pub fn place_id(&self) -> &str {
270        &self.place_id
271    }
272
273    pub fn dir(&self) -> &Path {
274        &self.dir
275    }
276
277    pub(super) fn seal(
278        &self,
279        table: &str,
280        row: &str,
281        column: &str,
282        plain: &[u8],
283    ) -> Result<Vec<u8>, CloudError> {
284        crypt::seal(
285            &self.rk,
286            &crypt::aad(&self.place_id, table, row, column),
287            plain,
288        )
289    }
290
291    pub(super) fn open_value(
292        &self,
293        table: &str,
294        row: &str,
295        column: &str,
296        sealed: &[u8],
297    ) -> Result<zeroize::Zeroizing<Vec<u8>>, CloudError> {
298        crypt::open(
299            &self.rk,
300            &crypt::aad(&self.place_id, table, row, column),
301            sealed,
302        )
303    }
304
305    /// `blake3_keyed(rk, dk)`: the stored form of a dedupe or purge key.
306    pub(super) fn keyed(&self, dk: &[u8; 32]) -> [u8; 32] {
307        *blake3::keyed_hash(&self.rk, dk).as_bytes()
308    }
309
310    // ---- meta -----------------------------------------------------------
311
312    pub fn set_meta(&self, key: &str, value: &[u8]) -> Result<(), CloudError> {
313        if key == META_RK {
314            return Err(CloudError::Local("replica: rk is not meta data".into()));
315        }
316        let ct = self.seal("meta", key, "v", value)?;
317        self.conn
318            .execute(
319                "INSERT INTO meta (k, v) VALUES (?1, ?2) ON CONFLICT(k) DO UPDATE SET v = ?2",
320                params![key, ct],
321            )
322            .map_err(db_err)?;
323        Ok(())
324    }
325
326    pub fn meta(&self, key: &str) -> Result<Option<zeroize::Zeroizing<Vec<u8>>>, CloudError> {
327        if key == META_RK {
328            return Ok(None);
329        }
330        let ct: Option<Vec<u8>> = self
331            .conn
332            .query_row("SELECT v FROM meta WHERE k = ?1", [key], |r| r.get(0))
333            .optional()
334            .map_err(db_err)?;
335        ct.map(|ct| self.open_value("meta", key, "v", &ct))
336            .transpose()
337    }
338
339    fn meta_u64(&self, key: &str) -> Result<Option<u64>, CloudError> {
340        Ok(self.meta(key)?.and_then(|v| {
341            let bytes: [u8; 8] = v.as_slice().try_into().ok()?;
342            Some(u64::from_le_bytes(bytes))
343        }))
344    }
345
346    /// Last server `seq` folded (`None` before the first clone).
347    pub fn cursor(&self) -> Result<Option<u64>, CloudError> {
348        self.meta_u64(META_CURSOR)
349    }
350
351    /// Move the cursor; it never goes back.
352    pub fn set_cursor(&self, seq: u64) -> Result<(), CloudError> {
353        if self.cursor()?.is_some_and(|at| at > seq) {
354            return Err(CloudError::Protocol(format!(
355                "replica cursor would move back to {seq}"
356            )));
357        }
358        self.set_meta(META_CURSOR, &seq.to_le_bytes())
359    }
360
361    pub fn epoch(&self) -> Result<Option<u64>, CloudError> {
362        self.meta_u64(META_EPOCH)
363    }
364
365    pub fn set_epoch(&self, epoch: u64) -> Result<(), CloudError> {
366        self.set_meta(META_EPOCH, &epoch.to_le_bytes())
367    }
368
369    /// The place's dedupe key `pk_id` once the server delivered `id_salt`.
370    pub fn id_salt(&self) -> Result<Option<[u8; 32]>, CloudError> {
371        Ok(self
372            .meta(META_ID_SALT)?
373            .and_then(|v| v.as_slice().try_into().ok()))
374    }
375
376    pub fn set_id_salt(&self, salt: &[u8; 32]) -> Result<(), CloudError> {
377        self.set_meta(META_ID_SALT, salt)
378    }
379
380    // ---- dedupe and purge deny -----------------------------------------
381
382    pub fn add_dedupe_key(&self, dk: &[u8; 32], node_id: &str) -> Result<(), CloudError> {
383        self.conn
384            .execute(
385                "INSERT OR IGNORE INTO dedupe_keys (key, node_id) VALUES (?1, ?2)",
386                params![self.keyed(dk).as_slice(), node_id],
387            )
388            .map_err(db_err)?;
389        Ok(())
390    }
391
392    /// The node an exact dedupe key belongs to.
393    pub fn dedupe_node(&self, dk: &[u8; 32]) -> Result<Option<String>, CloudError> {
394        self.conn
395            .query_row(
396                "SELECT node_id FROM dedupe_keys WHERE key = ?1",
397                [self.keyed(dk).as_slice()],
398                |r| r.get(0),
399            )
400            .optional()
401            .map_err(db_err)
402    }
403
404    pub fn deny_purged(&self, dk: &[u8; 32], reason: &str) -> Result<(), CloudError> {
405        if !PURGE_REASONS.contains(&reason) {
406            return Err(CloudError::Protocol(format!("purge reason {reason:?}")));
407        }
408        self.conn
409            .execute(
410                "INSERT OR REPLACE INTO purge_deny (key, reason) VALUES (?1, ?2)",
411                params![self.keyed(dk).as_slice(), reason],
412            )
413            .map_err(db_err)?;
414        Ok(())
415    }
416
417    /// Whether a statement with this exact key was purged (capture step 3c).
418    pub fn is_purged(&self, dk: &[u8; 32]) -> Result<bool, CloudError> {
419        self.conn
420            .query_row(
421                "SELECT 1 FROM purge_deny WHERE key = ?1",
422                [self.keyed(dk).as_slice()],
423                |_| Ok(()),
424            )
425            .optional()
426            .map(|r| r.is_some())
427            .map_err(db_err)
428    }
429
430    /// A purge removed `node_id` (SPEC-ENGINE §3.4.6 step 3): its dedupe
431    /// keys move to `purge_deny` (same keyed digest, so the statement is
432    /// never captured again) and its MinHash signature is deleted.
433    pub fn deny_node(&mut self, node_id: &str, reason: &str) -> Result<(), CloudError> {
434        if !PURGE_REASONS.contains(&reason) {
435            return Err(CloudError::Protocol(format!("purge reason {reason:?}")));
436        }
437        let tx = self.conn.transaction().map_err(db_err)?;
438        tx.execute(
439            "INSERT OR REPLACE INTO purge_deny (key, reason)
440             SELECT key, ?2 FROM dedupe_keys WHERE node_id = ?1",
441            params![node_id, reason],
442        )
443        .map_err(db_err)?;
444        tx.execute("DELETE FROM dedupe_keys WHERE node_id = ?1", [node_id])
445            .map_err(db_err)?;
446        tx.execute("DELETE FROM minhash WHERE node_id = ?1", [node_id])
447            .map_err(db_err)?;
448        tx.commit().map_err(db_err)
449    }
450
451    /// Purge acknowledgements not yet accepted by the place:
452    /// `(purge_id, tombstone seq, applied_at ms)`, plus the ones already
453    /// sent (an ack is made once per tombstone, its first `applied_at` kept).
454    pub fn purge_acks(&self) -> Result<PurgeAcks, CloudError> {
455        Ok(self
456            .meta(META_PURGE_ACKS)?
457            .and_then(|v| serde_json::from_slice(&v).ok())
458            .unwrap_or_default())
459    }
460
461    pub fn set_purge_acks(&self, acks: &PurgeAcks) -> Result<(), CloudError> {
462        let bytes = serde_json::to_vec(acks).map_err(|e| CloudError::Local(e.to_string()))?;
463        self.set_meta(META_PURGE_ACKS, &bytes)
464    }
465
466    // ---- minhash ---------------------------------------------------------
467
468    pub fn put_signature(&self, node_id: &str, sig: &Signature) -> Result<(), CloudError> {
469        let bytes: Vec<u8> = sig.iter().flat_map(|v| v.to_le_bytes()).collect();
470        let ct = self.seal("minhash", node_id, "sig", &bytes)?;
471        self.conn
472            .execute(
473                "INSERT OR REPLACE INTO minhash (node_id, sig_ct) VALUES (?1, ?2)",
474                params![node_id, ct],
475            )
476            .map_err(db_err)?;
477        Ok(())
478    }
479
480    /// Every stored signature, decrypted, in node-id order.
481    pub fn signatures(&self) -> Result<Vec<(String, Signature)>, CloudError> {
482        let mut stmt = self
483            .conn
484            .prepare("SELECT node_id, sig_ct FROM minhash ORDER BY node_id")
485            .map_err(db_err)?;
486        let rows = stmt
487            .query_map([], |r| {
488                Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?))
489            })
490            .map_err(db_err)?;
491        let mut out = Vec::new();
492        for row in rows {
493            let (node, ct) = row.map_err(db_err)?;
494            let plain = self.open_value("minhash", &node, "sig", &ct)?;
495            let mut sig: Signature = [0; 64];
496            if plain.len() != sig.len() * 8 {
497                return Err(CloudError::Local("replica: minhash signature size".into()));
498            }
499            let (chunks, _) = plain.as_chunks::<8>();
500            for (slot, chunk) in sig.iter_mut().zip(chunks) {
501                *slot = u64::from_le_bytes(*chunk);
502            }
503            out.push((node, sig));
504        }
505        Ok(out)
506    }
507
508    // ---- pending (offline queue) ----------------------------------------
509
510    /// An own event waiting for the server log (offline or not yet tailed).
511    pub fn add_pending(
512        &self,
513        event_id: &str,
514        hlc_wall: u64,
515        hlc_ctr: u16,
516        outbox_id: Option<&str>,
517        event: &[u8],
518    ) -> Result<(), CloudError> {
519        let ct = self.seal("pending", event_id, "event", event)?;
520        let wall = i64::try_from(hlc_wall).map_err(|_| CloudError::Protocol("hlc wall".into()))?;
521        self.conn
522            .execute(
523                "INSERT OR REPLACE INTO pending (event_id, hlc_wall, hlc_ctr, outbox_id, event_ct)
524                 VALUES (?1, ?2, ?3, ?4, ?5)",
525                params![event_id, wall, hlc_ctr, outbox_id, ct],
526            )
527            .map_err(db_err)?;
528        Ok(())
529    }
530
531    /// Pending events in HLC order: `(event_id, event bytes)`.
532    pub fn pending(&self) -> Result<Vec<(String, zeroize::Zeroizing<Vec<u8>>)>, CloudError> {
533        let mut stmt = self
534            .conn
535            .prepare("SELECT event_id, event_ct FROM pending ORDER BY hlc_wall, hlc_ctr, event_id")
536            .map_err(db_err)?;
537        let rows = stmt
538            .query_map([], |r| {
539                Ok((r.get::<_, String>(0)?, r.get::<_, Vec<u8>>(1)?))
540            })
541            .map_err(db_err)?;
542        let mut out = Vec::new();
543        for row in rows {
544            let (id, ct) = row.map_err(db_err)?;
545            let plain = self.open_value("pending", &id, "event", &ct)?;
546            out.push((id, plain));
547        }
548        Ok(out)
549    }
550
551    /// The server log delivered `event_id`: it is no longer pending.
552    pub fn settle_pending(&self, event_id: &str) -> Result<bool, CloudError> {
553        self.conn
554            .execute("DELETE FROM pending WHERE event_id = ?1", [event_id])
555            .map(|n| n > 0)
556            .map_err(db_err)
557    }
558
559    // ---- own sources -------------------------------------------------------
560
561    /// Where an own-authored node's text came from (capture step 6).
562    pub fn put_own_source(
563        &self,
564        node_id: &str,
565        source_kind: &str,
566        source_ref: &serde_json::Value,
567    ) -> Result<(), CloudError> {
568        if !SOURCE_KINDS.contains(&source_kind) {
569            return Err(CloudError::Local(format!("source kind {source_kind:?}")));
570        }
571        let json = serde_json::to_vec(source_ref).map_err(|e| CloudError::Local(e.to_string()))?;
572        let ct = self.seal("own_sources", node_id, "source_ref", &json)?;
573        self.conn
574            .execute(
575                "INSERT OR REPLACE INTO own_sources (node_id, source_kind, source_ref_ct)
576                 VALUES (?1, ?2, ?3)",
577                params![node_id, source_kind, ct],
578            )
579            .map_err(db_err)?;
580        Ok(())
581    }
582
583    pub fn own_source(
584        &self,
585        node_id: &str,
586    ) -> Result<Option<(String, serde_json::Value)>, CloudError> {
587        let row: Option<(String, Vec<u8>)> = self
588            .conn
589            .query_row(
590                "SELECT source_kind, source_ref_ct FROM own_sources WHERE node_id = ?1",
591                [node_id],
592                |r| Ok((r.get(0)?, r.get(1)?)),
593            )
594            .optional()
595            .map_err(db_err)?;
596        let Some((kind, ct)) = row else {
597            return Ok(None);
598        };
599        let plain = self.open_value("own_sources", node_id, "source_ref", &ct)?;
600        let value = serde_json::from_slice(&plain).map_err(|e| CloudError::Local(e.to_string()))?;
601        Ok(Some((kind, value)))
602    }
603
604    /// Every own-authored node with its source, in node id order: what the
605    /// capture lifecycle compares with the knowledge store.
606    pub fn own_sources(&self) -> Result<Vec<(String, String, serde_json::Value)>, CloudError> {
607        let mut stmt = self
608            .conn
609            .prepare("SELECT node_id, source_kind, source_ref_ct FROM own_sources ORDER BY node_id")
610            .map_err(db_err)?;
611        let rows = stmt
612            .query_map([], |r| {
613                Ok((
614                    r.get::<_, String>(0)?,
615                    r.get::<_, String>(1)?,
616                    r.get::<_, Vec<u8>>(2)?,
617                ))
618            })
619            .map_err(db_err)?;
620        let mut out = Vec::new();
621        for row in rows {
622            let (node_id, kind, ct) = row.map_err(db_err)?;
623            let plain = self.open_value("own_sources", &node_id, "source_ref", &ct)?;
624            let value =
625                serde_json::from_slice(&plain).map_err(|e| CloudError::Local(e.to_string()))?;
626            out.push((node_id, kind, value));
627        }
628        Ok(out)
629    }
630
631    /// `hex(blake3_keyed(rk, value))`, the `value_digest` of a source ref.
632    pub fn value_digest(&self, value: &str) -> String {
633        blake3::keyed_hash(&self.rk, value.as_bytes())
634            .to_hex()
635            .to_string()
636    }
637}
638
639#[cfg(test)]
640#[path = "store_tests.rs"]
641mod tests;