Skip to main content

kevy_embedded/
store_persist.rs

1//! Durability methods on [`Store`] — `BGREWRITEAOF` and `SAVE` — plus
2//! their per-shard helpers. Extracted from `store.rs` to keep that file
3//! under the 500-LOC project ceiling. Behaviour is unchanged from the
4//! pre-split layout; this module hosts long-running disk paths
5//! separately from the hot lock/dispatch surface in `store.rs`.
6
7use std::io;
8use std::sync::RwLock;
9use std::time::Instant;
10
11use kevy_persist::RewriteStats;
12
13use crate::metric::KevyMetric;
14use crate::store::{Inner, Store, lock_write};
15
16impl Store {
17    /// `BGREWRITEAOF`: rebuild every shard's AOF from current state.
18    /// Synchronous. Returns the summed stats (`None` if persistence is off /
19    /// no shard rewrote).
20    /// Durability barrier (v2.1): flush + `fdatasync` every shard's
21    /// AOF now, regardless of the configured `appendfsync` policy. On
22    /// `Ok(())`, every write acknowledged before this call is on
23    /// stable storage. The `EverySec` serving-store idiom:
24    ///
25    /// ```ignore
26    /// store.atomic(|c| { /* critical write */ Ok(()) })?;
27    /// store.fsync_aof()?; // durable-on-ack for THIS block only
28    /// ```
29    ///
30    /// Cost: one `fdatasync` per dirty shard; a no-op on clean shards.
31    /// Under `appendfsync = always` it is a no-op (already durable).
32    pub fn fsync_aof(&self) -> io::Result<()> {
33        for shard in self.shards.iter() {
34            let mut g = lock_write(shard);
35            if let Some(aof) = &mut g.aof {
36                aof.sync_now()?;
37            }
38        }
39        Ok(())
40    }
41
42    pub fn rewrite_aof(&self) -> io::Result<Option<RewriteStats>> {
43        let mut agg: Option<RewriteStats> = None;
44        for shard in self.shards.iter() {
45            let start = Instant::now();
46            // Phase 1 (locked): freeze the COW view + start the tee —
47            // O(n)-shallow, no serialization under the lock.
48            let (view, tmp, before_bytes) = {
49                let mut g = lock_write(shard);
50                let Inner { store, aof, .. } = &mut *g;
51                let Some(aof) = aof else { continue };
52                if aof.is_rewriting() {
53                    continue;
54                }
55                let before = aof.size_bytes();
56                let view = store.collect_snapshot();
57                (view, aof.begin_view_rewrite()?, before)
58            };
59            // Phase 2 (unlocked): serialize + fsync the compacted log.
60            let keys = match kevy_persist::dump_aof(&tmp, &view) {
61                Ok((keys, _)) => keys,
62                Err(e) => {
63                    let mut g = lock_write(shard);
64                    if let Some(aof) = &mut g.aof {
65                        aof.abort_concurrent_rewrite();
66                    }
67                    let _ = std::fs::remove_file(&tmp);
68                    return Err(e);
69                }
70            };
71            // Phase 3 (locked): append the tee'd diff and swap.
72            let mut g = lock_write(shard);
73            let Some(aof) = &mut g.aof else { continue };
74            let stats = match aof.finish_concurrent_rewrite(&tmp, keys) {
75                Ok(s) => s,
76                Err(e) => {
77                    aof.abort_concurrent_rewrite();
78                    let _ = std::fs::remove_file(&tmp);
79                    return Err(e);
80                }
81            };
82            if let Some(sink) = &self.config.metric_sink {
83                sink.emit(KevyMetric::Rewrite {
84                    keys: stats.keys,
85                    before_bytes,
86                    after_bytes: stats.bytes,
87                    elapsed_ms: start.elapsed().as_millis() as u64,
88                });
89            }
90            let acc = agg.get_or_insert(RewriteStats { keys: 0, bytes: 0 });
91            acc.keys += stats.keys;
92            acc.bytes += stats.bytes;
93        }
94        Ok(agg)
95    }
96
97    /// Snapshot every shard to its `dump-{i}.rdb` (single shard: the configured
98    /// name), atomically. `Ok(false)` when persistence is disabled.
99    pub fn save_snapshot(&self) -> io::Result<bool> {
100        let Some(dir) = self.config.data_dir.as_ref() else {
101            return Ok(false);
102        };
103        let n = self.shards.len();
104        for (i, shard) in self.shards.iter().enumerate() {
105            let name = if n == 1 {
106                self.config.snapshot_filename.clone()
107            } else {
108                kevy_persist::layout::snapshot_file(i)
109            };
110            save_shard_snapshot(shard, &dir.join(name))?;
111        }
112        Ok(true)
113    }
114}
115
116/// Save one shard's snapshot with the snapshot+log contract intact:
117/// after a successful save the AOF holds **only post-collect writes**,
118/// so a restart replays them over the snapshot without double-applying
119/// history (non-idempotent commands like RPUSH duplicated before this).
120///
121/// Phase 1 (write lock): freeze the COW view + start the AOF tee — no
122/// write may land between the two (the tee atomicity contract). Phase 2
123/// (unlocked): serialize the view to the snapshot's durable tmp.
124/// Phase 3 (write lock): commit — snapshot rename and tee'd AOF reset
125/// adjacent, so the snapshot/log commit window stays microseconds.
126pub(crate) fn save_shard_snapshot(
127    shard: &RwLock<Inner>,
128    path: &std::path::Path,
129) -> io::Result<()> {
130    let (view, reset_tmp) = freeze_for_save(shard)?;
131    let tmp = match kevy_persist::write_snapshot_tmp(&view, path) {
132        Ok(t) => t,
133        Err(e) => {
134            if reset_tmp.is_some()
135                && let Some(aof) = &mut lock_write(shard).aof
136            {
137                aof.abort_concurrent_rewrite();
138            }
139            return Err(e);
140        }
141    };
142    let mut g = lock_write(shard);
143    std::fs::rename(&tmp, path)?;
144    if let (Some(reset), Some(aof)) = (reset_tmp, &mut g.aof) {
145        let swap = kevy_persist::write_aof_base(&reset)
146            .and_then(|()| aof.finish_concurrent_rewrite(&reset, 0));
147        if let Err(e) = swap {
148            aof.abort_concurrent_rewrite();
149            let _ = std::fs::remove_file(&reset);
150            return Err(e);
151        }
152    }
153    Ok(())
154}
155
156/// Phase-1 helper: collect the view and start the tee under one write
157/// lock. A racing background auto-rewrite owns the tee; it runs its
158/// slow half off-lock and finishes in milliseconds, so wait it out
159/// (bounded) rather than saving a snapshot whose log would double-
160/// apply on replay.
161fn freeze_for_save(
162    shard: &RwLock<Inner>,
163) -> io::Result<(kevy_store::SnapshotView, Option<std::path::PathBuf>)> {
164    for _ in 0..2000 {
165        {
166            let mut g = lock_write(shard);
167            let Inner { store, aof, .. } = &mut *g;
168            match aof {
169                Some(a) if a.is_rewriting() => {} // racing rewrite — retry
170                Some(a) => {
171                    let view = store.collect_snapshot();
172                    return Ok((view, Some(a.begin_view_rewrite()?)));
173                }
174                None => return Ok((store.collect_snapshot(), None)),
175            }
176        }
177        std::thread::sleep(std::time::Duration::from_millis(5));
178    }
179    Err(io::Error::new(
180        io::ErrorKind::TimedOut,
181        "kevy-embedded: AOF rewrite still in flight after 10s; snapshot aborted",
182    ))
183}