kevy_embedded/ops_snapshot_view.rs
1//! v2.4 — public point-in-time snapshot view.
2//!
3//! [`Store::snapshot`] freezes a consistent COW view of the WHOLE
4//! keyspace: all shard write locks are taken in shard order (the same
5//! deterministic-order discipline as `atomic_all_shards`, so the two
6//! can't deadlock against each other), every shard's O(n)-shallow
7//! view is collected inside that single window, then the locks drop.
8//! Writers block only for the collection (~8 ns/entry), not for the
9//! caller's subsequent iteration.
10//!
11//! The primary consumer: rebuilding derived state after a
12//! `FeedError::Resync` — freeze a view, note `changes_tail()`, scan
13//! your prefix from the view, resume the feed from the noted cursor.
14
15use kevy_store::SnapshotView;
16
17use crate::store::{Store, lock_write};
18
19/// A frozen, consistent point-in-time view of the whole store.
20pub struct Snapshot {
21 views: Vec<SnapshotView>,
22}
23
24/// One entry from [`Snapshot::each_prefix`] / [`Snapshot::keys_prefix`].
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub struct SnapshotEntry {
27 /// The key.
28 pub key: Vec<u8>,
29 /// Remaining TTL in ms at freeze time (`None` = no expiry).
30 pub ttl_ms: Option<u64>,
31}
32
33impl Snapshot {
34 /// Visit every entry under `prefix` as `(key, value, ttl_ms)` —
35 /// the raw [`kevy_store::Value`] borrow, for callers that want the
36 /// typed payload without copies.
37 pub fn each_prefix<F: FnMut(&[u8], &kevy_store::Value, Option<u64>)>(
38 &self,
39 prefix: &[u8],
40 mut f: F,
41 ) {
42 for view in &self.views {
43 view.each(|k, v, ttl| {
44 if k.starts_with(prefix) {
45 f(k, v, ttl);
46 }
47 });
48 }
49 }
50
51 /// Collect the keys (+ TTLs) under `prefix`, unordered across
52 /// shards.
53 pub fn keys_prefix(&self, prefix: &[u8]) -> Vec<SnapshotEntry> {
54 let mut out = Vec::new();
55 self.each_prefix(prefix, |k, _, ttl| {
56 out.push(SnapshotEntry { key: k.to_vec(), ttl_ms: ttl });
57 });
58 out
59 }
60
61 /// Total entries in the view.
62 pub fn len(&self) -> usize {
63 let mut n = 0;
64 for view in &self.views {
65 view.each(|_, _, _| n += 1);
66 }
67 n
68 }
69
70 /// Whether the view is empty.
71 pub fn is_empty(&self) -> bool {
72 self.len() == 0
73 }
74}
75
76impl Store {
77 /// Freeze a consistent point-in-time [`Snapshot`] of the whole
78 /// keyspace (see the module doc for the locking discipline).
79 pub fn snapshot(&self) -> Snapshot {
80 // Deterministic shard order (same as atomic_all_shards) — hold
81 // ALL write locks across the collection so no write lands
82 // between shard freezes.
83 let guards: Vec<_> = self.shards.iter().map(|s| lock_write(s)).collect();
84 let views = guards.iter().map(|g| g.store.collect_snapshot()).collect();
85 drop(guards);
86 Snapshot { views }
87 }
88}