kevy-config 7.0.0

Zero-dependency TOML subset parser and Config schema for kevy.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
//! `kevy-config` — TOML subset parser + Config schema for the kevy server.
//!
//! Zero crates.io dependencies; `#![forbid(unsafe_code)]`. Built specifically
//! for kevy's config file shape; not a general-purpose TOML library.
//!
//! Supported TOML subset:
//! - `[section]` table headers (one level deep)
//! - `key = value` with `value` ∈ {string, integer, boolean, size literal}
//! - String literals: `"double-quoted"` and `'single-quoted'`
//! - Integers: signed decimal (`123`, `-7`); prefixed forms (0x/0o/0b) NOT supported
//! - Booleans: `true` / `false`
//! - Size literals (kevy-specific extension): `"64mb"` / `"2gb"` / `"512kb"`
//!   parsed via [`parse_size`] when the schema field expects bytes
//! - `# comment` to end of line
//!
//! INTENTIONALLY UNSUPPORTED (TOML spec features kevy doesn't need):
//! - dotted keys (`a.b.c = ...`)
//! - multi-line strings (`"""…"""`)
//! - arrays / arrays of tables
//! - inline tables (`{ a = 1, b = 2 }`)
//! - datetime literals
//!
//! See [`Config`] for the schema, [`Config::load`] for the precedence chain.
//!
//! ```
//! use kevy_config::{AppendFsync, Config};
//!
//! let mut cfg = Config::from_toml_str(
//!     "[server]\nport = 7000\n\n[persistence]\nappendfsync = \"always\"\n",
//!     None,
//! )?;
//! cfg.merge_env([("KEVY_PORT", "7001")])?;
//! assert_eq!(cfg.server.port, 7001, "env over file");
//! assert_eq!(cfg.persistence.appendfsync, AppendFsync::Always);
//! assert!(cfg.to_toml_string().contains("appendfsync"));
//! # Ok::<(), kevy_config::ConfigError>(())
//! ```
#![forbid(unsafe_code)]
#![warn(missing_docs)]

mod apply;
mod cluster;
mod emit;
mod enums;
mod error;
mod lex;
mod notify;
mod parse;
mod peer;
mod preserve;
mod replication;
mod schema;
mod sections;
mod secure;
mod size;
mod tiering;
mod tuning;

pub use cluster::{ClusterSection, PeerEntry, ScopeEntry};
pub use error::ValueError;
pub use replication::{ReplicationRole, ReplicationSection};
pub use schema::{
    AdvancedSection, AppendFsync, AuditSection, Config, ConfigError, EvictionPolicy, ExpirySection,
    FeedSection, LogLevel, LogOutput, LogSection, LuaSection, MemorySection, MetricsSection,
    NotificationFlags, NotificationSection, PersistenceSection, ServerSection, SlowlogSection,
};
pub use secure::{SecureSection, key_from_hex, key_to_hex};
pub use size::parse_size;
pub use tiering::{TierBudgetSpec, TieringSection};

use std::path::{Path, PathBuf};

/// Auto-detect search order when `Config::load(None)` is called.
const AUTODETECT_PATHS: &[&str] = &["./kevy.toml", "/etc/kevy/kevy.toml"];

impl Config {
    /// Load config from the given explicit path, or auto-detect.
    ///
    /// Auto-detect order (first hit wins):
    /// 1. `$KEVY_DIR/kevy.toml` (if `KEVY_DIR` env is set)
    /// 2. `./kevy.toml`
    /// 3. `/etc/kevy/kevy.toml`
    ///
    /// If `path` is `Some`, that file is required to exist; otherwise
    /// returns `Ok(Config::default())` if no auto-detect path matched.
    ///
    /// ```
    /// use kevy_config::Config;
    ///
    /// let path = std::env::temp_dir().join(format!("kevy-config-load-{}.toml", std::process::id()));
    /// std::fs::write(&path, "[server]\nport = 7100\n").expect("write the temp config");
    /// let cfg = Config::load(Some(&path));
    /// std::fs::remove_file(&path).expect("remove the temp config");
    /// let cfg = cfg?;
    /// assert_eq!(cfg.server.port, 7100);
    /// assert_eq!(cfg.source_path.as_deref(), Some(path.as_path()));
    /// assert!(Config::load(Some(&path)).is_err(), "an explicit path must exist");
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub fn load(path: Option<&Path>) -> Result<Self, ConfigError> {
        if let Some(p) = path {
            let text = read_required(p)?;
            return Self::from_toml_str(&text, Some(p));
        }
        if let Some(p) = autodetect() {
            let text = read_required(&p)?;
            let mut cfg = Self::from_toml_str(&text, Some(&p))?;
            cfg.source_path = Some(p);
            return Ok(cfg);
        }
        Ok(Self::default())
    }

    /// Parse a TOML string (no file I/O). `source_path` is used for error
    /// reporting and `CONFIG REWRITE` write-back; pass `None` for in-memory.
    ///
    /// C6: marked `#[cold]` — only ever runs at server startup + on
    /// `CONFIG REWRITE`, never on the request hot path. Keeps the
    /// ~15.9 KB TOML-parse code off the iTLB pages around the steady-state
    /// dispatcher.
    ///
    /// ```
    /// use kevy_config::{Config, EvictionPolicy};
    ///
    /// let cfg = Config::from_toml_str(
    ///     "# a comment\n[memory]\nmaxmemory = \"64mb\"\nmaxmemory_policy = \"allkeys-lfu\"\n",
    ///     None,
    /// )?;
    /// assert_eq!(cfg.memory.maxmemory, 64 << 20);
    /// assert_eq!(cfg.memory.maxmemory_policy, EvictionPolicy::AllKeysLfu);
    /// assert!(Config::from_toml_str("[nosuch]\nkey = 1\n", None).is_err());
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    #[cold]
    pub fn from_toml_str(text: &str, source_path: Option<&Path>) -> Result<Self, ConfigError> {
        let mut cfg = Self::default();
        let items = parse::parse(text)?;
        for item in items {
            cfg.apply_item(&item)?;
        }
        if let Some(p) = source_path {
            cfg.source_path = Some(p.to_path_buf());
        }
        Ok(cfg)
    }

    /// Overlay environment variable values onto `self`. Iterates a
    /// caller-provided `(name, value)` list so tests can pump a fixture
    /// without touching the real env. The recognised variables match the
    /// pre-`kevy-config` set:
    /// - `KEVY_BIND` / `KEVY_PORT` / `KEVY_THREADS` / `KEVY_DIR` / `KEVY_AOF`
    ///
    /// Unknown variables are silently ignored (env may contain many
    /// unrelated keys).
    ///
    /// ```
    /// let mut cfg = kevy_config::Config::default();
    /// cfg.merge_env([("KEVY_PORT", "7002"), ("KEVY_AOF", "off"), ("HOME", "/root")])?;
    /// assert_eq!(cfg.server.port, 7002);
    /// assert!(!cfg.persistence.aof);
    /// assert!(cfg.merge_env([("KEVY_PORT", "not-a-port")]).is_err());
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub fn merge_env<I, K, V>(&mut self, env: I) -> Result<(), ConfigError>
    where
        I: IntoIterator<Item = (K, V)>,
        K: AsRef<str>,
        V: AsRef<str>,
    {
        for (k, v) in env {
            self.apply_env_var(k.as_ref(), v.as_ref())?;
        }
        Ok(())
    }

    /// Overlay parsed-from-CLI overrides onto `self`. Pass a struct of
    /// optional values (any `Some(_)` field overrides the corresponding
    /// schema field); the kevy binary builds one from `std::env::args`.
    ///
    /// ```
    /// let mut cli = kevy_config::CliOverrides::default();
    /// cli.port = Some(7000);
    /// let mut cfg = kevy_config::Config::default();
    /// cfg.merge_cli(cli)?;
    /// assert_eq!(cfg.server.port, 7000);
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub fn merge_cli(&mut self, cli: CliOverrides) -> Result<(), ConfigError> {
        if let Some(bind) = cli.bind {
            self.server.bind = bind;
        }
        if let Some(port) = cli.port {
            self.server.port = port;
        }
        if let Some(t) = cli.threads {
            self.server.threads = t;
        }
        if let Some(n) = cli.accept_shards {
            self.server.accept_shards = Some(n);
        }
        if let Some(d) = cli.data_dir {
            self.server.data_dir = d;
        }
        if let Some(aof) = cli.aof {
            self.persistence.aof = aof;
        }
        if let Some(cluster) = cli.cluster {
            self.cluster.enabled = cluster;
        }
        if let Some(budget) = cli.tiering_budget {
            self.tiering.budget = Some(budget);
        }
        Ok(())
    }

    // NOTE: `to_toml_string` (the CONFIG REWRITE template) lives in
    // [`crate::emit`] together with the canonical pair list the
    // preserving path shares — both serializers in one file so a new
    // schema section can't be added to one and missed by the other.
}

/// Optional CLI overrides applied via [`Config::merge_cli`].
///
/// Any `Some(_)` field overrides the corresponding schema field. CLI is the
/// highest-priority source (above env vars and the TOML file).
///
/// ```
/// use kevy_config::{CliOverrides, Config};
///
/// let mut cfg = Config::from_toml_str("[server]\nport = 7000\nthreads = 2\n", None)?;
/// let mut cli = CliOverrides::default();
/// cli.port = Some(7001);
/// cfg.merge_cli(cli)?;
/// assert_eq!(cfg.server.port, 7001, "CLI over file");
/// assert_eq!(cfg.server.threads, 2, "unset overrides leave the file value");
/// # Ok::<(), kevy_config::ConfigError>(())
/// ```
#[derive(Default, Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct CliOverrides {
    /// Override `server.bind` (`--bind A.B.C.D`).
    ///
    /// ```
    /// let mut cli = kevy_config::CliOverrides::default();
    /// cli.bind = Some([0, 0, 0, 0]);
    /// let mut cfg = kevy_config::Config::default();
    /// cfg.merge_cli(cli)?;
    /// assert_eq!(cfg.server.bind, [0, 0, 0, 0]);
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub bind: Option<[u8; 4]>,
    /// Override `server.port` (`--port N`).
    ///
    /// ```
    /// let mut cli = kevy_config::CliOverrides::default();
    /// cli.port = Some(6380);
    /// let mut cfg = kevy_config::Config::default();
    /// cfg.merge_cli(cli)?;
    /// assert_eq!(cfg.server.port, 6380);
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub port: Option<u16>,
    /// Override `server.threads` (`--threads N`).
    ///
    /// ```
    /// let mut cli = kevy_config::CliOverrides::default();
    /// cli.threads = Some(8);
    /// let mut cfg = kevy_config::Config::default();
    /// cfg.merge_cli(cli)?;
    /// assert_eq!(cfg.server.threads, 8);
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub threads: Option<usize>,
    /// Override `server.accept_shards` (`--accept-shards N`).
    /// `Some(N)` = only shards 0..N arm accept SQE; rest are compute-only.
    /// Use to fold conns onto fewer shards on sparse-conn workloads.
    ///
    /// ```
    /// let mut cli = kevy_config::CliOverrides::default();
    /// cli.accept_shards = Some(1);
    /// let mut cfg = kevy_config::Config::default();
    /// cfg.merge_cli(cli)?;
    /// assert_eq!(cfg.server.accept_shards, Some(1));
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub accept_shards: Option<usize>,
    /// Override `server.data_dir` (`--dir PATH`).
    ///
    /// ```
    /// let mut cli = kevy_config::CliOverrides::default();
    /// cli.data_dir = Some("/srv/kevy".into());
    /// let mut cfg = kevy_config::Config::default();
    /// cfg.merge_cli(cli)?;
    /// assert_eq!(cfg.server.data_dir.to_str(), Some("/srv/kevy"));
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub data_dir: Option<PathBuf>,
    /// Override `persistence.aof` (`--no-aof` → `Some(false)`).
    ///
    /// ```
    /// let mut cli = kevy_config::CliOverrides::default();
    /// cli.aof = Some(false);
    /// let mut cfg = kevy_config::Config::default();
    /// cfg.merge_cli(cli)?;
    /// assert!(!cfg.persistence.aof); // `--no-aof`
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub aof: Option<bool>,
    /// Override `cluster.enabled` (`--cluster` → `Some(true)`).
    ///
    /// ```
    /// let mut cli = kevy_config::CliOverrides::default();
    /// cli.cluster = Some(true);
    /// let mut cfg = kevy_config::Config::default();
    /// cfg.merge_cli(cli)?;
    /// assert!(cfg.cluster.enabled);
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub cluster: Option<bool>,
    /// Override `tiering.budget` (`--tiering-budget auto|70%|4gb`).
    /// `Some(_)` turns tiering on with that budget.
    ///
    /// ```
    /// let mut cli = kevy_config::CliOverrides::default();
    /// cli.tiering_budget = Some(kevy_config::TierBudgetSpec::Auto);
    /// let mut cfg = kevy_config::Config::default();
    /// cfg.merge_cli(cli)?;
    /// assert_eq!(cfg.tiering.budget, Some(kevy_config::TierBudgetSpec::Auto));
    /// # Ok::<(), kevy_config::ConfigError>(())
    /// ```
    pub tiering_budget: Option<TierBudgetSpec>,
}

fn read_required(p: &Path) -> Result<String, ConfigError> {
    std::fs::read_to_string(p)
        .map_err(|e| ConfigError::IoOpen { path: p.to_path_buf(), err: e.to_string() })
}

fn autodetect() -> Option<PathBuf> {
    if let Ok(dir) = std::env::var("KEVY_DIR") {
        let p = PathBuf::from(dir).join("kevy.toml");
        if p.exists() {
            return Some(p);
        }
    }
    for relative in AUTODETECT_PATHS {
        let p = PathBuf::from(relative);
        if p.exists() {
            return Some(p);
        }
    }
    None
}

// Send and Sync are part of the public contract: a change that loses
// either fails to compile here rather than in a caller.
const _: () = {
    const fn send_sync<T: Send + Sync>() {}
    send_sync::<Config>();
    send_sync::<CliOverrides>();
    send_sync::<ConfigError>();
    send_sync::<ValueError>();
    send_sync::<NotificationFlags>();
    send_sync::<PeerEntry>();
    send_sync::<ScopeEntry>();
    send_sync::<TierBudgetSpec>();
    send_sync::<AppendFsync>();
    send_sync::<EvictionPolicy>();
    send_sync::<LogLevel>();
    send_sync::<LogOutput>();
    send_sync::<ReplicationRole>();
};

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn defaults_match_documented_values() {
        let cfg = Config::default();
        assert_eq!(cfg.server.bind, [127, 0, 0, 1]);
        assert_eq!(cfg.server.port, 6004);
        assert_eq!(cfg.server.threads, 0);
        assert!(cfg.persistence.aof);
        assert_eq!(cfg.persistence.appendfsync, AppendFsync::EverySec);
        assert_eq!(cfg.memory.maxmemory, 0);
        assert_eq!(cfg.memory.maxmemory_policy, EvictionPolicy::NoEviction);
        assert_eq!(cfg.expiry.hz, 10);
        assert_eq!(cfg.expiry.sample, 20);
        assert_eq!(cfg.log.level, LogLevel::Info);
    }

    #[test]
    fn cli_overrides_apply_in_order() {
        let mut cfg = Config::default();
        let cli = CliOverrides {
            bind: Some([0, 0, 0, 0]),
            port: Some(7000),
            threads: Some(4),
            ..CliOverrides::default()
        };
        cfg.merge_cli(cli).unwrap();
        assert_eq!(cfg.server.bind, [0, 0, 0, 0]);
        assert_eq!(cfg.server.port, 7000);
        assert_eq!(cfg.server.threads, 4);
    }

    #[test]
    fn env_overrides_apply() {
        let mut cfg = Config::default();
        cfg.merge_env([
            ("KEVY_BIND", "0.0.0.0"),
            ("KEVY_PORT", "7001"),
            ("UNRELATED_VAR", "ignored"),
        ])
        .unwrap();
        assert_eq!(cfg.server.bind, [0, 0, 0, 0]);
        assert_eq!(cfg.server.port, 7001);
    }

    #[test]
    fn to_toml_string_round_trips_through_parser() {
        let mut original = Config::default();
        original.server.bind = [10, 0, 0, 1];
        original.server.port = 7779;
        original.server.threads = 4;
        original.server.data_dir = PathBuf::from("/var/lib/kevy");
        original.persistence.aof = false;
        original.persistence.appendfsync = AppendFsync::Always;
        original.persistence.auto_aof_rewrite_percentage = 200;
        original.persistence.auto_aof_rewrite_min_size = 128 * 1024 * 1024;
        original.memory.maxmemory = 4 * 1024 * 1024 * 1024;
        original.memory.maxmemory_policy = EvictionPolicy::AllKeysLfu;
        original.expiry.hz = 100;
        original.expiry.sample = 50;
        original.log.level = LogLevel::Warn;
        original.log.output = LogOutput::File(PathBuf::from("/var/log/kevy.log"));

        let toml_text = original.to_toml_string();
        let mut reparsed = Config::from_toml_str(&toml_text, None).unwrap_or_else(|e| {
            panic!("to_toml_string output did not reparse: {e}\n--- TOML ---\n{toml_text}")
        });
        // Re-parsing sets source_path only when one is passed; the live
        // config's source_path is not part of the wire format.
        reparsed.source_path = original.source_path.clone();
        assert_eq!(original, reparsed);
    }

    #[test]
    fn to_toml_string_escapes_quotes_and_backslashes_in_paths() {
        let mut cfg = Config::default();
        cfg.server.data_dir = PathBuf::from(r#"/path with "quote" and \back"#);
        let text = cfg.to_toml_string();
        assert!(
            text.contains(r#"data_dir = "/path with \"quote\" and \\back""#),
            "did not escape correctly: {text}"
        );
        // Round-trip the escape.
        let reparsed = Config::from_toml_str(&text, None).expect("reparse");
        assert_eq!(reparsed.server.data_dir, cfg.server.data_dir);
    }
}