kevy-config 1.15.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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! kevy `Config` schema, defaults, and error type. Apply-from-parser and
//! value-coercion logic lives in `apply.rs` so this file stays focused on
//! "what the settings ARE".

use std::path::PathBuf;

// ───────────── enums ─────────────

/// AOF fsync policy. Matches Redis `appendfsync`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppendFsync {
    /// `fsync` after every write command. Zero data-loss but ~50% throughput.
    Always,
    /// Background `fsync` every second. Lose at most 1s on crash. Default.
    EverySec,
    /// No explicit `fsync`; let OS pagecache flush. Lose ~30s on crash.
    No,
}

impl AppendFsync {
    /// Canonical Redis-compatible name (`always` / `everysec` / `no`).
    /// Used by `CONFIG GET appendfsync` and `CONFIG REWRITE`.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Always => "always",
            Self::EverySec => "everysec",
            Self::No => "no",
        }
    }
    /// Inverse of [`Self::as_str`] — case-insensitive. `None` for any
    /// other input; used by both the TOML parser and `CONFIG SET`.
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "always" => Some(Self::Always),
            "everysec" => Some(Self::EverySec),
            "no" => Some(Self::No),
            _ => None,
        }
    }
}

/// Maxmemory eviction policy. 8 variants matching Redis. `NoEviction`
/// (default) returns an error on writes once `maxmemory` is hit.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EvictionPolicy {
    /// Refuse writes once `maxmemory` is hit. Default.
    NoEviction,
    /// Approximated LRU across all keys.
    AllKeysLru,
    /// Approximated LFU across all keys.
    AllKeysLfu,
    /// Random key across all keys.
    AllKeysRandom,
    /// Approximated LRU across keys with a TTL.
    VolatileLru,
    /// Approximated LFU across keys with a TTL.
    VolatileLfu,
    /// Random key from those with a TTL.
    VolatileRandom,
    /// Key with the shortest remaining TTL.
    VolatileTtl,
}

impl EvictionPolicy {
    /// Canonical Redis-compatible name.
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::NoEviction => "noeviction",
            Self::AllKeysLru => "allkeys-lru",
            Self::AllKeysLfu => "allkeys-lfu",
            Self::AllKeysRandom => "allkeys-random",
            Self::VolatileLru => "volatile-lru",
            Self::VolatileLfu => "volatile-lfu",
            Self::VolatileRandom => "volatile-random",
            Self::VolatileTtl => "volatile-ttl",
        }
    }
    /// Inverse of [`Self::as_str`] — case-insensitive.
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "noeviction" => Some(Self::NoEviction),
            "allkeys-lru" => Some(Self::AllKeysLru),
            "allkeys-lfu" => Some(Self::AllKeysLfu),
            "allkeys-random" => Some(Self::AllKeysRandom),
            "volatile-lru" => Some(Self::VolatileLru),
            "volatile-lfu" => Some(Self::VolatileLfu),
            "volatile-random" => Some(Self::VolatileRandom),
            "volatile-ttl" => Some(Self::VolatileTtl),
            _ => None,
        }
    }
}

/// Log verbosity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogLevel {
    /// Very chatty, useful when debugging a kevy internal bug.
    Trace,
    /// Per-command / per-event detail; turn on locally to chase issues.
    Debug,
    /// Default; startup banner, WARNs, errors, key lifecycle events.
    Info,
    /// Only non-fatal warnings (e.g. unprotected bind) and errors.
    Warn,
    /// Only fatal errors.
    Error,
}

impl LogLevel {
    /// Canonical name. `Warn` renders as `warning` (Redis convention).
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::Trace => "trace",
            Self::Debug => "debug",
            Self::Info => "info",
            Self::Warn => "warning",
            Self::Error => "error",
        }
    }
    /// Inverse of [`Self::as_str`] — case-insensitive; accepts both
    /// `warn` and `warning` for the Warn level.
    pub fn parse(s: &str) -> Option<Self> {
        match s.to_ascii_lowercase().as_str() {
            "trace" => Some(Self::Trace),
            "debug" => Some(Self::Debug),
            "info" => Some(Self::Info),
            "warn" | "warning" => Some(Self::Warn),
            "error" => Some(Self::Error),
            _ => None,
        }
    }
}

/// Where to write log output.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LogOutput {
    /// Write to standard error (default).
    Stderr,
    /// Write to standard output.
    Stdout,
    /// Append to the named file (path resolved relative to cwd at startup).
    File(PathBuf),
}

impl LogOutput {
    /// Canonical name. `File(p)` renders as the path string.
    pub fn as_str(&self) -> std::borrow::Cow<'_, str> {
        match self {
            Self::Stderr => "stderr".into(),
            Self::Stdout => "stdout".into(),
            Self::File(p) => p.display().to_string().into(),
        }
    }
    /// Inverse of [`Self::as_str`]: `stderr` / `stdout` reserved; any
    /// other string is treated as a file path.
    pub fn parse(s: &str) -> Self {
        match s {
            "stderr" => Self::Stderr,
            "stdout" => Self::Stdout,
            path => Self::File(PathBuf::from(path)),
        }
    }
}

// ───────────── sections ─────────────

/// `[server]` section.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ServerSection {
    /// IPv4 bind address. Default `127.0.0.1`.
    pub bind: [u8; 4],
    /// TCP port. Default `6004`.
    pub port: u16,
    /// Shard / reactor thread count. `0` = auto (CPU count). Default `0`.
    pub threads: usize,
    /// Snapshot + AOF location. Default `.`.
    pub data_dir: PathBuf,
}

impl Default for ServerSection {
    fn default() -> Self {
        Self {
            bind: [127, 0, 0, 1],
            port: 6004,
            threads: 0,
            data_dir: PathBuf::from("."),
        }
    }
}

/// `[persistence]` section.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PersistenceSection {
    /// Append-only file enabled. Default `true`.
    pub aof: bool,
    /// AOF fsync policy. Default `EverySec`.
    pub appendfsync: AppendFsync,
    /// Trigger BGREWRITEAOF when current AOF is at least this fraction
    /// (as a percent — 100 = 2× the last-rewrite size) larger than the
    /// last rewrite. Default `100`.
    pub auto_aof_rewrite_percentage: u32,
    /// Never auto-rewrite an AOF smaller than this. Default `64mb` =
    /// `64 * 1024 * 1024`.
    pub auto_aof_rewrite_min_size: u64,
}

impl Default for PersistenceSection {
    fn default() -> Self {
        Self {
            aof: true,
            appendfsync: AppendFsync::EverySec,
            auto_aof_rewrite_percentage: 100,
            auto_aof_rewrite_min_size: 64 * 1024 * 1024,
        }
    }
}

/// `[memory]` section.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct MemorySection {
    /// Soft memory ceiling in bytes. `0` = unlimited. Default `0`.
    pub maxmemory: u64,
    /// Action when `maxmemory` is hit. Default `NoEviction`.
    pub maxmemory_policy: EvictionPolicy,
}

impl Default for MemorySection {
    fn default() -> Self {
        Self {
            maxmemory: 0,
            maxmemory_policy: EvictionPolicy::NoEviction,
        }
    }
}

/// `[expiry]` section. Controls the TTL background reaper.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExpirySection {
    /// Reaper frequency in Hz. Default `10` (every 100 ms).
    pub hz: u32,
    /// Keys sampled per reaper cycle. Default `20`.
    pub sample: u32,
}

impl Default for ExpirySection {
    fn default() -> Self {
        Self { hz: 10, sample: 20 }
    }
}

/// `[log]` section.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LogSection {
    /// Log verbosity. Default `Info`.
    pub level: LogLevel,
    /// Log sink. Default `Stderr`.
    pub output: LogOutput,
}

impl Default for LogSection {
    fn default() -> Self {
        Self {
            level: LogLevel::Info,
            output: LogOutput::Stderr,
        }
    }
}

/// `[advanced]` section — reactor-loop tuning knobs that used to be
/// hardcoded `const`s in `kevy-rt`. Defaults match the values shipped
/// in workspace v1.3 / earlier so the existing benchmark numbers
/// translate one-to-one. Tune only if you know what you're doing
/// (`bench/REPORT.md` documents the trade-offs).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct AdvancedSection {
    /// Iterations the per-core reactor spins on `poll(timeout=0)`
    /// before parking on a blocking wait. Higher = lower wake-up
    /// latency under contention, higher idle CPU; lower = the inverse.
    /// Default `256` (matches v1.0 const).
    pub spin_limit: u32,
    /// Bounded blocking wait in ms once the reactor parks. Acts as a
    /// safety backstop for any missed cross-core wake (the per-pair
    /// SeqCst fence is the primary mechanism since workspace v1.3.0).
    /// Default `50` ms.
    pub park_timeout_ms: u32,
    /// How many reactor loop iterations between wall-clock reads for
    /// the tick (TTL reaper / auto-AOF-rewrite / live-config refresh).
    /// In busy-poll mode (~1M iter/s) the default `256` is one check
    /// per ~256 µs — plenty for a 10 Hz tick. In park mode the
    /// reactor bypasses this throttle (each iter is already ≥ 1 ms),
    /// so the value only matters under sustained load. Default `256`.
    pub tick_check_every: u32,
    /// Per-direction SPSC ring slot count (one ring per ordered
    /// core-pair). Must be a power of two; the ring code rounds up.
    /// Overflow spills to a local backlog Vec rather than blocking,
    /// so a small ring just shifts work to the slower path. Default
    /// `1024`.
    pub ring_capacity: usize,
}

impl Default for AdvancedSection {
    fn default() -> Self {
        Self {
            spin_limit: 256,
            park_timeout_ms: 50,
            tick_check_every: 256,
            ring_capacity: 1024,
        }
    }
}

/// `[notification]` section. `notify_keyspace_events` is a string of
/// flag chars (Redis convention): `K` keyspace channel, `E` keyevent
/// channel, `g` generic cmds, `$` string cmds, `l` list, `s` set, `h`
/// hash, `z` zset, `A` alias for `g$lshz` (every event class except
/// the not-yet-implemented `x`/`e`/`t`/`n`). Default empty = OFF
/// (Redis default — zero hot-path cost).
///
/// Example: `notify_keyspace_events = "KEA"` enables every event
/// class on BOTH channels. `"K$"` enables only string events on the
/// keyspace channel.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct NotificationSection {
    /// Flag string controlling which keyspace notifications fire. Empty
    /// (default) = OFF: writes pay one atomic load + skip, no publish.
    pub notify_keyspace_events: String,
}

/// Parsed view of [`NotificationSection::notify_keyspace_events`]. The
/// runtime caches this struct per-shard (hot-reload via the existing
/// `LiveRuntimeConfig` tick path) so the per-write-command check
/// reduces to four bool reads on the hot path.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct NotificationFlags {
    /// `K` — publish on `__keyspace@<db>__:<key>` channel.
    pub keyspace: bool,
    /// `E` — publish on `__keyevent@<db>__:<event>` channel.
    pub keyevent: bool,
    /// `g` — DEL / EXPIRE / PERSIST / RENAME / TYPE / FLUSH etc.
    pub generic: bool,
    /// `$` — SET / GETSET / INCR* / APPEND / MSET / etc.
    pub string: bool,
    /// `l` — LPUSH / RPUSH / LPOP / RPOP / LREM / LSET / LTRIM / …
    pub list: bool,
    /// `s` — SADD / SREM / SPOP / SMOVE / …
    pub set: bool,
    /// `h` — HSET / HDEL / HINCRBY / HSETNX / …
    pub hash: bool,
    /// `z` — ZADD / ZINCRBY / ZREM / ZREMRANGEBY* / …
    pub zset: bool,
    /// `t` — XADD / XDEL / XTRIM / XGROUP / XACK / XCLAIM / XREADGROUP …
    pub stream: bool,
}

impl NotificationFlags {
    /// Notifications are entirely off (no channel enabled OR no class
    /// enabled). The hot-path emits skip via this check before any
    /// further classification or string formatting.
    pub fn is_empty(&self) -> bool {
        !(self.keyspace || self.keyevent)
            || !(self.generic
                || self.string
                || self.list
                || self.set
                || self.hash
                || self.zset
                || self.stream)
    }
}

/// `[slowlog]` section — controls the per-shard slow-command ring
/// buffer surfaced by `SLOWLOG GET/LEN/RESET`. Default is OFF
/// (`slower_than_micros = -1`) so the hot path never pays the
/// `Instant::now()` pair around dispatch (~30 ns/op, ≈9 % at 3 M
/// ops/s). To enable Redis-style 10 ms tracking, set
/// `slower_than_micros = 10000` in `[slowlog]` or run
/// `CONFIG SET slowlog-log-slower-than 10000`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SlowlogSection {
    /// Record any command whose execution took at least this many
    /// microseconds (Redis: `< slower_than_micros` is skipped). `-1`
    /// disables the log (zero hot-path cost — no `Instant::now()`
    /// taken); `0` records every command. Default `-1` (OFF).
    pub slower_than_micros: i64,
    /// Cap on the per-shard ring buffer. Once exceeded, the oldest
    /// entry is dropped to make room. Across `nshards` shards the
    /// effective server-wide cap is `max_len * nshards`. Default `128`.
    pub max_len: u32,
}

impl Default for SlowlogSection {
    fn default() -> Self {
        Self {
            slower_than_micros: -1,
            max_len: 128,
        }
    }
}

/// Parse a Redis-style `notify_keyspace_events` flag string into
/// [`NotificationFlags`]. Unknown chars are ignored (forward-compat
/// for `x`/`e`/`t`/`n` not yet implemented — see the section docs).
/// The `A` alias enables every event-class flag except channels.
pub fn parse_notification_flags(s: &str) -> NotificationFlags {
    let mut f = NotificationFlags::default();
    for c in s.chars() {
        match c {
            'K' => f.keyspace = true,
            'E' => f.keyevent = true,
            'g' => f.generic = true,
            '$' => f.string = true,
            'l' => f.list = true,
            's' => f.set = true,
            'h' => f.hash = true,
            'z' => f.zset = true,
            't' => f.stream = true,
            'A' => {
                // Alias for "g$lshzxetd" — every implemented event class.
                // Per Redis spec `A` includes the stream `t` class.
                f.generic = true;
                f.string = true;
                f.list = true;
                f.set = true;
                f.hash = true;
                f.zset = true;
                f.stream = true;
            }
            _ => {} // forward-compat: silently ignore unknown chars
        }
    }
    f
}

/// `[cluster]` section — single-node cluster mode: keys route by
/// Redis-cluster slot (CRC16 `{hashtag}` & 16383) and every shard `i`
/// gets a second, deterministic listener at `port_base + i` that answers
/// wrong-shard keys with `-MOVED`, so stock cluster-aware clients
/// (`redis-benchmark --cluster`, `redis-cli -c`) can address shards
/// directly. The main SO_REUSEPORT port keeps full forward-anywhere
/// behaviour for non-cluster clients. Not hot-settable: the routing
/// scheme is a startup property of the data dir (`shards.meta`).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct ClusterSection {
    /// Enable cluster mode. Default `false` (zero change).
    pub enabled: bool,
    /// First cluster port (shard `i` listens at `port_base + i`).
    /// `0` (default) = `server.port + 1`.
    pub port_base: u16,
}

// ───────────── top-level Config ─────────────

/// Complete kevy config: defaults + per-section overrides loaded from
/// the TOML file + env + CLI.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Config {
    /// `[server]` settings.
    pub server: ServerSection,
    /// `[persistence]` settings.
    pub persistence: PersistenceSection,
    /// `[memory]` settings.
    pub memory: MemorySection,
    /// `[expiry]` settings.
    pub expiry: ExpirySection,
    /// `[log]` settings.
    pub log: LogSection,
    /// `[notification]` settings (keyspace events).
    pub notification: NotificationSection,
    /// `[advanced]` settings (reactor tuning knobs).
    pub advanced: AdvancedSection,
    /// `[slowlog]` settings (slow-command ring buffer).
    pub slowlog: SlowlogSection,
    /// `[cluster]` settings (single-node cluster mode).
    pub cluster: ClusterSection,
    /// Path the config was loaded from (for `CONFIG REWRITE`). `None` =
    /// loaded from defaults only / from in-memory string.
    pub source_path: Option<PathBuf>,
}

// `ConfigError` lives in [`crate::error`] — split out so this file
// stays under the 500-LOC house rule. Re-exported below for any caller
// that still does `kevy_config::schema::ConfigError`.
pub use crate::error::ConfigError;