Skip to main content

kevy_embedded/
store.rs

1//! [`Store`] — the embedded entry point. Wraps `kevy_store::Store` with
2//! a mutex (for cross-thread access), optional AOF auto-logging, an
3//! optional background TTL reaper, and an in-process pub/sub bus.
4
5use std::io;
6use std::path::PathBuf;
7use std::sync::atomic::{AtomicBool, Ordering};
8use std::sync::{Arc, Mutex, MutexGuard, Weak};
9use std::thread::JoinHandle;
10use std::time::Duration;
11
12use kevy_persist::{Aof, Argv, RewriteStats, load_snapshot, replay_aof, save_snapshot};
13use kevy_store::{ExpireStats, StoreError};
14
15use crate::config::{Config, TtlReaperMode};
16use crate::pubsub::PubsubBus;
17
18/// The embedded keyspace.
19///
20/// **`Store` is `Clone`** (since v1.1.0). A clone is a cheap `Arc` bump:
21/// every clone reaches the same underlying `kevy_store::Store` + AOF +
22/// reaper + pub/sub bus. The reaper thread is joined and the AOF is
23/// flushed exactly once, when the **last** clone is dropped.
24///
25/// ```
26/// use kevy_embedded::{Config, Store};
27///
28/// # fn main() -> std::io::Result<()> {
29/// let s = Store::open(Config::default().with_ttl_reaper_manual())?;
30/// let s2 = s.clone();
31/// std::thread::spawn(move || {
32///     s2.set(b"from-thread", b"v").unwrap();
33/// }).join().unwrap();
34/// assert_eq!(s.get(b"from-thread")?, Some(b"v".to_vec()));
35/// # Ok(())
36/// # }
37/// ```
38///
39/// Every method takes `&self`. The internal `Arc<Mutex<Inner>>` is what
40/// makes shared access safe under contention.
41#[derive(Clone)]
42pub struct Store {
43    inner: Arc<Mutex<Inner>>,
44    /// Shared drop guard: signals + joins reaper and flushes AOF when the
45    /// LAST `Store` clone (or `Subscription`) holding a strong ref drops.
46    guard: Arc<DropGuard>,
47    config: Config,
48}
49
50/// Weak handle to a `Store` — does not keep the underlying keyspace alive.
51///
52/// Used by the URL-keyed registry in `kevy-client` so that multiple
53/// `Connection::open("mem://name")` calls share the same backing store
54/// without leaking it when all strong handles go away.
55pub struct WeakStore {
56    inner: Weak<Mutex<Inner>>,
57    guard: Weak<DropGuard>,
58    config: Config,
59}
60
61impl WeakStore {
62    /// Try to upgrade back to a `Store`. Returns `None` if the last strong
63    /// reference has already been dropped.
64    pub fn upgrade(&self) -> Option<Store> {
65        Some(Store {
66            inner: self.inner.upgrade()?,
67            guard: self.guard.upgrade()?,
68            config: self.config.clone(),
69        })
70    }
71}
72
73pub(crate) struct Inner {
74    pub(crate) store: kevy_store::Store,
75    pub(crate) aof: Option<Aof>,
76    pub(crate) bus: PubsubBus,
77}
78
79/// Owns the reaper-thread handle + a back-reference to `Inner` for the
80/// final AOF flush. Lives in an `Arc<DropGuard>` shared across every
81/// `Store` clone; the actual drop logic fires only when the last clone
82/// goes away. `JoinHandle` is wrapped in `Mutex<Option>` so `Drop` can
83/// `.take()` it while only having `&self`.
84pub(crate) struct DropGuard {
85    reaper_stop: Option<Arc<AtomicBool>>,
86    reaper_join: Mutex<Option<JoinHandle<()>>>,
87    inner_for_flush: Arc<Mutex<Inner>>,
88}
89
90impl Store {
91    /// Open an embedded keyspace per `config`.
92    ///
93    /// - Pure in-memory when `config.data_dir` is `None`.
94    /// - With persistence: loads `<data_dir>/<snapshot_filename>` first,
95    ///   then replays `<data_dir>/<aof_filename>`. Both are best-effort —
96    ///   missing files are fine, a truncated AOF tail is silently dropped.
97    /// - Spawns a background TTL reaper thread when
98    ///   `config.ttl_reaper == Background` (the default).
99    pub fn open(config: Config) -> io::Result<Self> {
100        let (store, aof) = init_persistent_store(&config)?;
101        let inner = Arc::new(Mutex::new(Inner {
102            store,
103            aof,
104            bus: PubsubBus::new(),
105        }));
106        let (reaper_stop, reaper_join) = spawn_reaper(&config, &inner)?;
107        let guard = Arc::new(DropGuard {
108            reaper_stop,
109            reaper_join: Mutex::new(reaper_join),
110            inner_for_flush: inner.clone(),
111        });
112        Ok(Store {
113            inner,
114            guard,
115            config,
116        })
117    }
118
119    /// Get a weak handle that does not keep the keyspace alive.
120    /// `upgrade()` returns `None` once the last strong `Store` is dropped.
121    pub fn downgrade(&self) -> WeakStore {
122        WeakStore {
123            inner: Arc::downgrade(&self.inner),
124            guard: Arc::downgrade(&self.guard),
125            config: self.config.clone(),
126        }
127    }
128
129    /// The active config (a clone — modifying it has no effect on the
130    /// running store). Useful for introspection / `INFO`-style telemetry.
131    pub fn config(&self) -> &Config {
132        &self.config
133    }
134
135    // ---- escape hatches -------------------------------------------------
136
137    /// Run `f` against the underlying `kevy_store::Store` under the
138    /// embedded mutex. Use for direct access to methods this crate hasn't
139    /// wrapped (snapshot iteration, ZRANGE, raw collect_keys, …). The
140    /// closure can mutate, but *does not auto-log to the AOF* — call
141    /// [`Self::log`] yourself if the mutation must survive a crash.
142    pub fn with<F, R>(&self, f: F) -> R
143    where
144        F: FnOnce(&mut kevy_store::Store) -> R,
145    {
146        let mut g = self.lock();
147        f(&mut g.store)
148    }
149
150    /// Append a raw RESP-frame argument list to the AOF. Pairs with
151    /// [`Self::with`] when the closure performed a write you want to make
152    /// crash-safe. No-op when persistence is disabled.
153    pub fn log(&self, parts: &[&[u8]]) -> io::Result<()> {
154        let mut g = self.lock();
155        if let Some(aof) = &mut g.aof {
156            let argv = Argv::from(parts.iter().map(|p| p.to_vec()).collect::<Vec<_>>());
157            aof.append(&argv)?;
158        }
159        Ok(())
160    }
161
162    // ---- maintenance ----------------------------------------------------
163
164    /// Run one TTL-reaper tick. Required call cadence in `Manual` mode
165    /// (call ~10× per second to match Redis's `hz=10`); no-op cost is
166    /// one mutex lock + map-emptiness check when nothing has TTL.
167    pub fn tick(&self) -> ExpireStats {
168        let mut g = self.lock();
169        g.store
170            .tick_expire(self.config.reaper_samples, self.config.reaper_max_rounds)
171    }
172
173    /// `BGREWRITEAOF`: rebuild the AOF from current state. Synchronous —
174    /// blocks until the rewrite + atomic rename completes. Returns
175    /// `Ok(None)` when persistence is disabled.
176    pub fn rewrite_aof(&self) -> io::Result<Option<RewriteStats>> {
177        let mut g = self.lock();
178        // Disjoint-field split-borrow: destructure the guard so the borrow
179        // checker sees `store` and `aof` as independent borrows, not two
180        // claims on the same `&mut Inner`.
181        let Inner { store, aof, bus: _ } = &mut *g;
182        let Some(aof) = aof else { return Ok(None) };
183        Ok(Some(aof.rewrite_from(store)?))
184    }
185
186    /// Snapshot the store to `<data_dir>/<snapshot_filename>`, atomically.
187    /// `Ok(false)` when persistence is disabled (caller can decide to
188    /// surface that or no-op).
189    pub fn save_snapshot(&self) -> io::Result<bool> {
190        let g = self.lock();
191        let Some(dir) = self.config.data_dir.as_ref() else {
192            return Ok(false);
193        };
194        let path: PathBuf = dir.join(&self.config.snapshot_filename);
195        save_snapshot(&g.store, &path)?;
196        Ok(true)
197    }
198
199    // String / hash / list / set / zset / pub-sub data-type methods live
200    // in `crate::ops` (kept under the 500-LOC file cap). Look there for
201    // e.g. `Store::set` / `Store::hset` / `Store::publish`.
202
203    /// Crate-internal: clone the shared `Arc<Mutex<Inner>>` handle, used
204    /// by `ops.rs::Store::subscribe` to hand the bus to a `Subscription`.
205    pub(crate) fn inner_handle(&self) -> Arc<Mutex<Inner>> {
206        self.inner.clone()
207    }
208
209    /// Crate-internal: clone the shared `Arc<DropGuard>` so a live
210    /// `Subscription` keeps the reaper + AOF flush alive until it drops.
211    pub(crate) fn guard_handle(&self) -> Arc<DropGuard> {
212        self.guard.clone()
213    }
214
215    /// Crate-internal: acquire the embedded mutex. Recovers from poison
216    /// because every method's critical section is short — a panic in one
217    /// doesn't corrupt the keyspace.
218    pub(crate) fn lock(&self) -> MutexGuard<'_, Inner> {
219        match self.inner.lock() {
220            Ok(g) => g,
221            Err(poison) => poison.into_inner(),
222        }
223    }
224}
225
226/// Build the `kevy_store::Store` and (optionally) its `Aof`. Loads any
227/// pre-existing snapshot and replays any pre-existing AOF before
228/// returning. `data_dir = None` ⇒ pure in-memory (both return values
229/// are the empty store + `None`).
230fn init_persistent_store(config: &Config) -> io::Result<(kevy_store::Store, Option<Aof>)> {
231    let mut store = kevy_store::Store::new();
232    store.set_max_memory(config.maxmemory, config.eviction_policy);
233    let aof = if let Some(dir) = &config.data_dir {
234        std::fs::create_dir_all(dir)?;
235        let snap_path = dir.join(&config.snapshot_filename);
236        if snap_path.exists() {
237            load_snapshot(&mut store, &snap_path)?;
238        }
239        let aof_path = dir.join(&config.aof_filename);
240        if aof_path.exists() {
241            replay_aof(&aof_path, |args| crate::replay::apply(&mut store, &args))?;
242        }
243        if config.aof {
244            Some(Aof::open(&aof_path, config.appendfsync)?)
245        } else {
246            None
247        }
248    } else {
249        None
250    };
251    Ok((store, aof))
252}
253
254/// Start the background TTL reaper thread, returning its stop signal +
255/// join handle. `TtlReaperMode::Manual` returns `(None, None)` so the
256/// caller-driven reap is in charge instead.
257#[allow(clippy::type_complexity)] // inline tuple keeps the pair colocated
258fn spawn_reaper(
259    config: &Config,
260    inner: &Arc<Mutex<Inner>>,
261) -> io::Result<(Option<Arc<AtomicBool>>, Option<JoinHandle<()>>)> {
262    match config.ttl_reaper {
263        TtlReaperMode::Manual => Ok((None, None)),
264        TtlReaperMode::Background => {
265            let stop = Arc::new(AtomicBool::new(false));
266            let stop_t = stop.clone();
267            let inner_t = inner.clone();
268            let interval = config.reaper_interval;
269            let samples = config.reaper_samples;
270            let rounds = config.reaper_max_rounds;
271            let handle = std::thread::Builder::new()
272                .name(String::from("kevy-embedded-reaper"))
273                .spawn(move || reaper_loop(inner_t, stop_t, interval, samples, rounds))?;
274            Ok((Some(stop), Some(handle)))
275        }
276    }
277}
278
279// ─────────────────────────────────────────────────────────────────────────
280// DELETION MARKER (replaced below): everything from the original `set`
281// method through the closing brace of `impl Store` previously lived here.
282// They've been moved to `crate::ops` — see crates/kevy-embedded/src/ops.rs.
283// ─────────────────────────────────────────────────────────────────────────
284
285fn log_argv(aof: &mut Option<Aof>, parts: &[&[u8]]) -> io::Result<()> {
286    if let Some(aof) = aof {
287        let argv = Argv::from(parts.iter().map(|p| p.to_vec()).collect::<Vec<_>>());
288        aof.append(&argv)?;
289    }
290    Ok(())
291}
292
293/// Complete a write: AOF-log the canonical RESP command, then run the
294/// store's post-write eviction sweep. Single helper so every write wrapper
295/// stays in lockstep — forgetting to evict means a maxmemory budget would
296/// grow without bound.
297pub(crate) fn commit_write(inner: &mut Inner, parts: &[&[u8]]) -> io::Result<()> {
298    log_argv(&mut inner.aof, parts)?;
299    inner.store.try_evict_after_write();
300    Ok(())
301}
302
303pub(crate) fn store_err(e: StoreError) -> io::Error {
304    io::Error::new(io::ErrorKind::InvalidInput, format!("kevy-store: {e:?}"))
305}
306
307fn reaper_loop(
308    inner: Arc<Mutex<Inner>>,
309    stop: Arc<AtomicBool>,
310    interval: Duration,
311    samples: usize,
312    rounds: u32,
313) {
314    while !stop.load(Ordering::Relaxed) {
315        std::thread::sleep(interval);
316        if stop.load(Ordering::Relaxed) {
317            break;
318        }
319        let mut g = match inner.lock() {
320            Ok(g) => g,
321            Err(poison) => poison.into_inner(),
322        };
323        let _ = g.store.tick_expire(samples, rounds);
324        // EverySec AOF fsync window check — embedded mode runs this from
325        // the same reaper tick rather than a separate timer.
326        if let Some(aof) = &mut g.aof {
327            let _ = aof.maybe_sync();
328        }
329    }
330}
331
332impl Drop for DropGuard {
333    fn drop(&mut self) {
334        // Last `Store` clone is going away — stop the reaper, join it, then
335        // flush the AOF so EverySec users don't lose the last sub-second of
336        // writes. Poison recovery: a method panic earlier shouldn't strand
337        // the AOF unflushed; the writes already landed in-memory.
338        if let Some(stop) = &self.reaper_stop {
339            stop.store(true, Ordering::Relaxed);
340        }
341        if let Some(j) = self
342            .reaper_join
343            .lock()
344            .unwrap_or_else(|p| p.into_inner())
345            .take()
346        {
347            let _ = j.join();
348        }
349        let mut g = match self.inner_for_flush.lock() {
350            Ok(g) => g,
351            Err(poison) => poison.into_inner(),
352        };
353        if let Some(aof) = &mut g.aof {
354            let _ = aof.maybe_sync();
355        }
356    }
357}
358
359#[cfg(test)]
360#[path = "store_tests.rs"]
361mod tests;