Skip to main content

kevy_embedded/
config.rs

1//! Embedded-store configuration. Builder-style — every knob has a sane
2//! default so `Config::default()` works for the simplest use case
3//! (in-memory, no persistence, background TTL reaper).
4
5use std::path::PathBuf;
6use std::time::Duration;
7
8pub use kevy_persist::Fsync as AppendFsync;
9pub use kevy_store::EvictionPolicy;
10
11/// How the active TTL reaper runs.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum TtlReaperMode {
14    /// Spawn a background thread that ticks at the configured interval
15    /// (default 100 ms / 10 Hz, matching Redis's `hz=10`). Default.
16    Background,
17    /// Caller-driven via [`crate::Store::tick`]. Required for WASM
18    /// targets (no threads) and single-threaded apps that don't want a
19    /// background worker.
20    Manual,
21}
22
23/// Embedded-store config. Build by chaining `with_*` methods on
24/// [`Config::default`].
25#[derive(Debug, Clone)]
26pub struct Config {
27    /// Soft memory ceiling in bytes. `0` (default) = unlimited.
28    pub maxmemory: u64,
29    /// Eviction policy when over `maxmemory`. Default `NoEviction`.
30    pub eviction_policy: EvictionPolicy,
31    /// Persistence directory. `None` = pure in-memory (no AOF, no snapshot).
32    pub data_dir: Option<PathBuf>,
33    /// AOF on/off when `data_dir` is set. Defaults to `true` (on) when
34    /// `with_persist` was called; ignored if `data_dir` is `None`.
35    pub aof: bool,
36    /// AOF fsync policy. Default `EverySec` (matches Redis: ≤ 1 s loss).
37    pub appendfsync: AppendFsync,
38    /// Snapshot file name inside `data_dir` (single-shard only; `n > 1`
39    /// always uses `dump-{i}.rdb`). Default `"dump-0.rdb"`. A custom name
40    /// opts the dir out of server interop: no `shards.meta` is recorded,
41    /// and a `kevy` server opening the same dir won't find the files.
42    pub snapshot_filename: String,
43    /// AOF file name inside `data_dir` (single-shard only; `n > 1` always
44    /// uses `aof-{i}.aof`). Default `"aof-0.aof"`. Same interop opt-out as
45    /// [`Self::snapshot_filename`].
46    pub aof_filename: String,
47    /// TTL reaper mode. Default `Background`.
48    pub ttl_reaper: TtlReaperMode,
49    /// Reaper tick interval. Default 100 ms (10 Hz).
50    pub reaper_interval: Duration,
51    /// `tick_expire` samples per round. Default 20 (matches Redis).
52    pub reaper_samples: usize,
53    /// Max sample rounds per tick. Default 16.
54    pub reaper_max_rounds: u32,
55    /// Auto-`BGREWRITEAOF` trigger: rewrite when the live AOF has grown by at
56    /// least this percent over its size at the previous rewrite. `0` disables
57    /// (call [`crate::Store::rewrite_aof`] manually). Default `100` (Redis).
58    pub auto_aof_rewrite_pct: u32,
59    /// Floor below which auto-rewrite is skipped. Default `64 MiB` (Redis).
60    pub auto_aof_rewrite_min_size: u64,
61    /// Optional push-style metric callback (replay / rewrite events). Default
62    /// `None`. Set via [`Self::with_metric_sink`]; not part of `Debug` output.
63    pub(crate) metric_sink: Option<crate::metric::MetricSink>,
64    /// Keyspace shard count (`hash(key) % shards`), each a fully independent
65    /// lock + keyspace + AOF (shared-nothing) — concurrent access scales across
66    /// cores. **Default `1`** (single shard = the original single-lock /
67    /// single-`aof-0.aof` layout, zero migration). Set `> 1` via
68    /// [`Self::with_shards`]; the first open with `> 1` re-shards an existing
69    /// single AOF into per-shard files.
70    pub shards: usize,
71    /// Replication upstream. `Some("host:port")` makes this store a
72    /// read-replica that streams writes from the named primary; `None`
73    /// (default) is a normal primary store. Configured via
74    /// [`Self::with_replica_upstream`] or the convenience constructor
75    /// [`crate::Store::open_replica`].
76    pub replica_upstream: Option<String>,
77    /// Replica identity string sent to the primary at handshake
78    /// (`REPLICATE FROM <offset> ID <replica_id>`). Default
79    /// `"kevy-embedded-replica"`. Override per-process when multiple
80    /// embed replicas connect to the same primary (they'd otherwise
81    /// share the slot and clobber each other's session state on the
82    /// primary side).
83    pub replica_id: String,
84    /// Replica reconnect backoff: lower bound. Default 100 ms. The
85    /// runner sleeps this long after the first connection failure;
86    /// each subsequent failure doubles the wait up to
87    /// [`Self::replica_reconnect_max`].
88    pub replica_reconnect_min: Duration,
89    /// Replica reconnect backoff: upper bound. Default 5 s — matches
90    /// the server-side replica reconnect default so embed replicas and
91    /// server replicas behave identically when the same primary
92    /// disappears.
93    pub replica_reconnect_max: Duration,
94    /// Embed-as-writer bind address (`"host:port"` or
95    /// `"0.0.0.0:port"`) for the replication source listener. When
96    /// `Some`, every commit on this store pushes its argv into a
97    /// process-local `ReplicationSource` backlog, and replicas (other
98    /// embeds, server-as-replicas) connect to this port to stream the
99    /// writes. `None` (default) keeps the embed in pure-local mode.
100    /// Mutually exclusive in spirit with `replica_upstream` (a single
101    /// store should be either a writer source or a reader sink, not
102    /// both); the builder does not reject the combo so tests can
103    /// exercise the guard rails.
104    pub embed_writer_listen_addr: Option<String>,
105    /// Backlog byte budget for the embed-as-writer source. Default
106    /// `1 MiB` (matches the v1.18 server replication default).
107    /// Set higher when consumers may disconnect for longer than
108    /// the backlog can buffer (otherwise reconnects hit `TooOld`
109    /// and v1.21 closes the link — snapshot-ship from embed is a
110    /// follow-up).
111    pub embed_writer_backlog_bytes: usize,
112}
113
114impl Default for Config {
115    fn default() -> Self {
116        Self {
117            maxmemory: 0,
118            eviction_policy: EvictionPolicy::NoEviction,
119            data_dir: None,
120            aof: true,
121            appendfsync: AppendFsync::EverySec,
122            snapshot_filename: String::from("dump-0.rdb"),
123            aof_filename: String::from("aof-0.aof"),
124            ttl_reaper: TtlReaperMode::Background,
125            reaper_interval: Duration::from_millis(100),
126            reaper_samples: 20,
127            reaper_max_rounds: 16,
128            auto_aof_rewrite_pct: 100,
129            auto_aof_rewrite_min_size: 64 * 1024 * 1024,
130            metric_sink: None,
131            shards: 1,
132            replica_upstream: None,
133            replica_id: String::from("kevy-embedded-replica"),
134            replica_reconnect_min: Duration::from_millis(100),
135            replica_reconnect_max: Duration::from_secs(5),
136            embed_writer_listen_addr: None,
137            embed_writer_backlog_bytes: 1024 * 1024,
138        }
139    }
140}
141
142impl Config {
143    /// Enable persistence under `dir` — snapshot file + AOF land inside.
144    /// AOF defaults on; turn it off with [`Self::without_aof`] for pure
145    /// snapshot-only durability.
146    #[must_use]
147    pub fn with_persist(mut self, dir: impl Into<PathBuf>) -> Self {
148        self.data_dir = Some(dir.into());
149        self
150    }
151
152    /// Disable the AOF (snapshot-only persistence — explicit `save_snapshot`
153    /// calls are the only way data survives restart).
154    #[must_use]
155    pub fn without_aof(mut self) -> Self {
156        self.aof = false;
157        self
158    }
159
160    /// Soft memory ceiling in bytes. `0` keeps the default (unlimited).
161    #[must_use]
162    pub fn with_max_memory(mut self, bytes: u64) -> Self {
163        self.maxmemory = bytes;
164        self
165    }
166
167    /// Eviction policy when over [`Self::with_max_memory`].
168    #[must_use]
169    pub fn with_eviction(mut self, policy: EvictionPolicy) -> Self {
170        self.eviction_policy = policy;
171        self
172    }
173
174    /// AOF fsync policy. Default [`AppendFsync::EverySec`].
175    #[must_use]
176    pub fn with_appendfsync(mut self, fsync: AppendFsync) -> Self {
177        self.appendfsync = fsync;
178        self
179    }
180
181    /// Auto-`BGREWRITEAOF` thresholds: rewrite once the AOF has grown `pct`
182    /// percent past its size at the last rewrite AND is at least `min_size`
183    /// bytes. In `Background` reaper mode the check runs on the reaper tick;
184    /// in `Manual` mode it runs when you call [`crate::Store::tick`]. Pass
185    /// `pct = 0` to disable auto-rewrite (you can still call
186    /// [`crate::Store::rewrite_aof`] yourself). Defaults: 100 % / 64 MiB.
187    #[must_use]
188    pub fn with_auto_aof_rewrite(mut self, pct: u32, min_size: u64) -> Self {
189        self.auto_aof_rewrite_pct = pct;
190        self.auto_aof_rewrite_min_size = min_size;
191        self
192    }
193
194    /// Shard the keyspace into `n` shared-nothing partitions (`hash(key) % n`),
195    /// each with its own lock + keyspace + AOF, so concurrent access scales
196    /// across cores. `n` clamps to ≥ 1; `1` (default) is the original
197    /// single-shard layout. Going from a single-AOF store to `n > 1`
198    /// re-shards the existing `aof-0.aof` into `aof-0..aof-{n-1}` on the next
199    /// open (the old file is backed up to `aof-0.aof.premigration.<ts>` first).
200    /// Pub/sub is process-wide (handled on shard 0), not sharded.
201    #[must_use]
202    pub fn with_shards(mut self, n: usize) -> Self {
203        self.shards = n.max(1);
204        self
205    }
206
207    /// Register a push-style metric callback. It receives a [`crate::KevyMetric`] for
208    /// each AOF replay (startup) and AOF rewrite (compaction) — wire it to
209    /// Prometheus / a log line / a counter. The callback runs synchronously on
210    /// the emitting thread (reaper thread for background rewrites), so keep it
211    /// fast and non-blocking. Replaces any previously-set sink.
212    #[must_use]
213    pub fn with_metric_sink(
214        mut self,
215        sink: impl Fn(crate::KevyMetric) + Send + Sync + 'static,
216    ) -> Self {
217        self.metric_sink = Some(crate::metric::MetricSink::new(sink));
218        self
219    }
220
221    /// Caller-driven TTL reaping — disables the background thread.
222    /// Required for WASM (no threads available). Call
223    /// [`crate::Store::tick`] yourself from your event loop.
224    #[must_use]
225    pub fn with_ttl_reaper_manual(mut self) -> Self {
226        self.ttl_reaper = TtlReaperMode::Manual;
227        self
228    }
229
230    /// Configure this store as a replication replica of `upstream`
231    /// (`"host:port"` of a kevy server's replication listener). A
232    /// background thread streams writes from the primary and applies
233    /// them locally; this store rejects local writes with a
234    /// `READONLY` error. See [`crate::Store::open_replica`] for the
235    /// convenience constructor.
236    #[must_use]
237    pub fn with_replica_upstream(mut self, upstream: impl Into<String>) -> Self {
238        self.replica_upstream = Some(upstream.into());
239        self
240    }
241
242    /// Override the replica identity sent to the primary at handshake.
243    /// Useful when multiple embed replicas share one primary —
244    /// otherwise they'd share the slot and stomp each other's session
245    /// state.
246    #[must_use]
247    pub fn with_replica_id(mut self, id: impl Into<String>) -> Self {
248        self.replica_id = id.into();
249        self
250    }
251
252    /// Override the replica reconnect backoff bounds.
253    #[must_use]
254    pub fn with_replica_reconnect(mut self, min: Duration, max: Duration) -> Self {
255        self.replica_reconnect_min = min;
256        self.replica_reconnect_max = max.max(min);
257        self
258    }
259
260    /// Run this store as an embed-as-writer: bind a replication
261    /// source listener on `bind_addr` so replicas can subscribe to
262    /// the writes applied here.
263    #[must_use]
264    pub fn with_embed_writer(mut self, bind_addr: impl Into<String>) -> Self {
265        self.embed_writer_listen_addr = Some(bind_addr.into());
266        self
267    }
268
269    /// Override the embed-as-writer backlog byte budget.
270    #[must_use]
271    pub fn with_embed_writer_backlog(mut self, bytes: usize) -> Self {
272        self.embed_writer_backlog_bytes = bytes.max(64 * 1024);
273        self
274    }
275
276    /// Override the background reaper interval. Default 100 ms.
277    #[must_use]
278    pub fn with_reaper_interval(mut self, iv: Duration) -> Self {
279        self.reaper_interval = iv;
280        self
281    }
282
283    /// Override the snapshot file name inside `data_dir`.
284    #[must_use]
285    pub fn with_snapshot_filename(mut self, name: impl Into<String>) -> Self {
286        self.snapshot_filename = name.into();
287        self
288    }
289
290    /// Override the AOF file name inside `data_dir`.
291    #[must_use]
292    pub fn with_aof_filename(mut self, name: impl Into<String>) -> Self {
293        self.aof_filename = name.into();
294        self
295    }
296}
297
298#[cfg(test)]
299mod tests {
300    use super::*;
301
302    #[test]
303    fn default_is_pure_in_memory() {
304        let c = Config::default();
305        assert_eq!(c.maxmemory, 0);
306        assert!(c.data_dir.is_none());
307        assert_eq!(c.ttl_reaper, TtlReaperMode::Background);
308        assert!(c.aof);
309    }
310
311    #[test]
312    fn builder_chains() {
313        let c = Config::default()
314            .with_persist("/tmp/foo")
315            .with_max_memory(1024)
316            .with_eviction(EvictionPolicy::AllKeysLru)
317            .with_ttl_reaper_manual()
318            .with_appendfsync(AppendFsync::Always);
319        assert_eq!(c.data_dir.as_deref(), Some(std::path::Path::new("/tmp/foo")));
320        assert_eq!(c.maxmemory, 1024);
321        assert_eq!(c.eviction_policy, EvictionPolicy::AllKeysLru);
322        assert_eq!(c.ttl_reaper, TtlReaperMode::Manual);
323    }
324
325    #[test]
326    fn without_aof_disables_logging_path() {
327        let c = Config::default().with_persist("/tmp/foo").without_aof();
328        assert!(c.data_dir.is_some());
329        assert!(!c.aof);
330    }
331}