shep_core/config/daemon.rs
1//! Daemon-level configuration: `$SHEP_HOME/shep.toml`
2//!
3//! Layering (spec §5): file < `SHEP_*` env < CLI flags. This module applies
4//! the first two; the CLI applies its flags onto the returned struct.
5
6use core::fmt;
7
8use std::collections::BTreeMap;
9use std::path::PathBuf;
10
11use serde::Deserialize;
12
13use crate::values::UpDuration;
14
15/// The `[daemon]` section
16#[derive(Debug, Clone, Default, PartialEq, Deserialize)]
17#[serde(deny_unknown_fields, default)]
18pub struct DaemonSection {
19 /// Emit the daemon's own logs as JSON lines
20 pub log_json: bool,
21 /// Lowest severity of the daemon's own records that reaches its log
22 pub log_level: LogLevel,
23 /// Control-socket path override (default: `$SHEP_HOME/run/shep.sock`)
24 pub socket: Option<std::path::PathBuf>,
25 /// Dogs to autostart with the daemon (`shep enable` writes this)
26 pub enabled_dogs: Vec<String>,
27 /// Where an adopted dog's binary lives, keyed by dog name
28 /// (`shep adopt` writes this; `shep rehome` removes it).
29 ///
30 /// A name in [`Self::enabled_dogs`] with no entry here is a built-in
31 /// dog — an argv branch of the shep binary itself. That is the whole of
32 /// the distinction, and it is deliberately NOT recorded inside
33 /// `[dog.<name>]`: that table is the dog's own opaque configuration, and
34 /// a shep-owned key inside it would collide with a third-party dog's
35 /// schema.
36 pub adopted_dogs: BTreeMap<String, PathBuf>,
37 /// Longest a cron worker sleeps before re-deriving its next occurrence.
38 ///
39 /// Shorter recovers faster from a suspended laptop or an NTP step and
40 /// costs proportionally more wakeups per cron-configured sheep; longer
41 /// is cheaper and drifts further. Unset means the daemon's own default.
42 /// There is no upper bound: a very long value only degrades to sleeping
43 /// straight through to the occurrence, which still fires.
44 pub max_cron_sleep: Option<UpDuration>,
45}
46
47/// How much of the daemon's own diagnostics reaches its log.
48///
49/// Written as one of the names below in `[daemon] log_level` or in
50/// `SHEP_LOG_LEVEL`, lowercase and nothing else — the same closed grammar
51/// `log_json` accepts, so a typo is a startup error naming the value rather
52/// than a level silently reverting to the default.
53///
54/// The default is [`LogLevel::Warn`]. The daemon's records are dominated by
55/// warn-and-continue arms — an app that asked to be watched and could not be,
56/// a cron pattern that would not parse, a memory ceiling a process tree
57/// crossed — and each one is the *only* account of a decision the operator
58/// cannot otherwise see. [`LogLevel::Debug`] adds per-decision detail that
59/// fires per dropped restart and per child metric sample, which is a firehose
60/// on a busy flock rather than a slightly noisier log.
61#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
62#[serde(rename_all = "lowercase")]
63pub enum LogLevel {
64 /// Nothing at all — the daemon writes no records of its own.
65 Off,
66 /// Only faults the daemon could not work around.
67 Error,
68 /// Faults the daemon worked around, and what working around them cost.
69 #[default]
70 Warn,
71 /// Lifecycle milestones: the daemon came up, the daemon is going down.
72 Info,
73 /// Per-decision detail — every restart weighed, every metric sampled.
74 Debug,
75 /// Everything the daemon can say about itself.
76 Trace,
77}
78
79impl LogLevel {
80 /// The one spelling this level is written as, in the file and in the
81 /// environment alike
82 #[must_use]
83 pub const fn as_str(self) -> &'static str {
84 match self {
85 Self::Off => "off",
86 Self::Error => "error",
87 Self::Warn => "warn",
88 Self::Info => "info",
89 Self::Debug => "debug",
90 Self::Trace => "trace",
91 }
92 }
93
94 /// The level `name` spells, or `None` when it spells no level.
95 ///
96 /// The inverse of [`LogLevel::as_str`], and exact: an uppercase or
97 /// mixed-case name is not a level here, because `SHEP_LOG_JSON` accepts
98 /// no `TRUE` either.
99 #[must_use]
100 pub fn from_name(name: &str) -> Option<Self> {
101 match name {
102 "off" => Some(Self::Off),
103 "error" => Some(Self::Error),
104 "warn" => Some(Self::Warn),
105 "info" => Some(Self::Info),
106 "debug" => Some(Self::Debug),
107 "trace" => Some(Self::Trace),
108 _ => None,
109 }
110 }
111}
112
113/// Floor on `[daemon] max_cron_sleep`.
114///
115/// Zero makes every sleep return immediately and turns the loop into a hot
116/// spin that re-derives a schedule as fast as the runtime allows — while
117/// still firing correctly, which is what makes it hard to attribute. Low
118/// milliseconds are the same fault with a smaller constant. One second is a
119/// floor no legitimate configuration wants to be under: a five-field cron
120/// pattern cannot name anything finer than a minute, so even this is sixty
121/// times more often than the tightest schedule can fire.
122const MIN_CRON_SLEEP: UpDuration = UpDuration::from_millis(1_000);
123
124/// The `[whistle]` section
125///
126/// One key, and it is a gate rather than a tuning knob: `shep whistle`'s four
127/// control tools (`start_sheep`, `stop_sheep`, `restart_sheep`,
128/// `reload_sheep`) exist only when this is `true`, and its five read-only
129/// tools exist regardless.
130///
131/// **This lives in the shepherd's config file and nowhere else.** There is no
132/// `--allow-control` flag and no `SHEP_*` variable, deliberately: spec §14.7
133/// rules that whistle's gate is daemon config because config is auditable and
134/// flags are per-invocation. That is a legibility argument, not a
135/// containment one — `--home`/`SHEP_HOME` already choose which `shep.toml`
136/// gets read, so a flag would open nothing those don't already; a boolean in
137/// a file just leaves a diff and an mtime an operator can audit.
138///
139/// The shepherd itself never reads this key — `shep whistle` reads the file
140/// directly, at startup, in its own process. It is here because this struct is
141/// the grammar of `shep.toml`: `RawDaemonConfig` denies unknown fields, so a
142/// `[whistle]` section the grammar does not know about would refuse the whole
143/// file to boot rather than being silently ignored.
144///
145/// `Debug` is derived rather than redacted (IR-41): one boolean, no secret,
146/// nothing a `{:?}` could leak.
147#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Deserialize)]
148#[serde(deny_unknown_fields, default)]
149pub struct WhistleSection {
150 /// Whether `shep whistle` offers its control tools. Default `false`.
151 pub allow_control: bool,
152}
153
154/// The `[style]` section: how much the CLI dresses up its output.
155///
156/// Read by the CLI only. The daemon has no opinion about how anyone likes
157/// their tables, and parses this solely so an unknown key is not an error.
158///
159/// `Debug` is derived rather than redacted (IR-41): one optional string, no
160/// secret, nothing a `{:?}` could leak.
161#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
162#[serde(deny_unknown_fields, default)]
163pub struct StyleSection {
164 /// `full`, `plain` or `bare`. Absent means the CLI decides.
165 pub level: Option<String>,
166}
167
168/// Parsed daemon configuration with raw per-dog sections
169///
170/// Dog sections stay untyped here: each dog deserializes its own
171/// `[dog.<name>]` table so dog config schemas live with the dog code.
172///
173/// `#[non_exhaustive]`: this struct grows a section over time, and each one
174/// would otherwise be a breaking change for an out-of-tree struct literal.
175/// That is IR-20's ordinary reasoning applied to a struct. **It is not a
176/// validation gate**, and this type is deliberately
177/// not the proof token [`crate::config::ResolvedApp`] is: the attribute blocks
178/// struct literals and functional-update syntax from outside this crate, but
179/// not field mutation, and [`Self::default`] followed by an assignment to
180/// `daemon.max_cron_sleep` reaches an unvalidated value without a literal.
181///
182/// The contract is therefore stated, not enforced. [`Self::load`] and
183/// [`Self::load_layered`] are the validating constructors; a caller that
184/// mutates a loaded config afterwards is out of contract, and shep-core does
185/// not detect it and, with public fields, cannot.
186///
187/// That is the right trade here because nothing ever *receives* one of these.
188/// `ResolvedApp` protects a property of travel — the supervisor is handed one
189/// and must trust normalization it cannot see. Every production site loads a
190/// `DaemonConfig` and consumes it within a few lines (`run_daemon` renders it
191/// straight into `BootOptions`; shep-daemon's `dogs` reads one
192/// `[dog.<name>]` table; shep-cli's `whistle::gate` reads one boolean), and
193/// the daemon holds a `BootOptions`, not this. Guarding the one
194/// `max_cron_sleep` floor against a caller who is already out of contract
195/// would cost accessors for every field of every section, including a
196/// `BTreeMap<String, toml::Table>` two crates legitimately read. If an
197/// out-of-tree caller ever does need to mutate and re-check, the answer is to
198/// make `validate` public — one line, non-breaking — not to privatise the
199/// fields. `docs/specs/deferred.md` records this as resolved.
200///
201/// Nothing in the repository observes the attribute itself: it is invisible
202/// inside the defining crate, and seeing it needs a `trybuild` compile-fail
203/// tier this project declined once already for `ProcessInfo` (see
204/// `tests/process_info_builder_from_outside_the_crate.rs`, which admits the
205/// same gap and is required to stay shep-core's only `tests/` file).
206#[non_exhaustive]
207#[derive(Clone, Default, PartialEq)]
208pub struct DaemonConfig {
209 /// The `[daemon]` section
210 pub daemon: DaemonSection,
211 /// The `[whistle]` section
212 pub whistle: WhistleSection,
213 /// The `[style]` section
214 pub style: StyleSection,
215 /// The `[interpreters]` section: a script extension (no leading dot,
216 /// `"js"` not `".js"`) mapped to the interpreter that runs it.
217 ///
218 /// Read by the CLI only, and applied before a request ever reaches the
219 /// wire: `shep start`'s target resolution folds a match into an app's
220 /// own [`AppConfig::interpreter`](crate::config::AppConfig::interpreter)
221 /// exactly when that field is still unset, the same way `--cwd` and
222 /// `--fold` are folded in there. An app that already names an
223 /// interpreter -- explicitly in a Flockfile, including the literal
224 /// `"none"` -- is never touched by this map, and `--interpreter` on the
225 /// command line outranks both. The daemon itself never reads this
226 /// field; by the time an app reaches it, the CLI has already resolved
227 /// the question.
228 ///
229 /// Lives in this daemon-config grammar for the reason
230 /// [`StyleSection`]'s own doc gives for itself: `RawDaemonConfig`
231 /// denies unknown top-level keys, so a section this type does not know
232 /// about is a hard parse error for every `shep.toml` carrying one --
233 /// registering it here is what keeps `[interpreters]` from breaking
234 /// every daemon boot the moment an operator, or `shep`'s own first-run
235 /// scaffold, writes one.
236 pub interpreters: BTreeMap<String, String>,
237 /// Raw `[dog.<name>]` sections keyed by dog name
238 pub dog: BTreeMap<String, toml::Table>,
239}
240
241/// Debug implementation does not leak dog config values (IR-41)
242impl fmt::Debug for DaemonConfig {
243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244 f.debug_struct("DaemonConfig")
245 .field("daemon", &self.daemon)
246 .field("whistle", &self.whistle)
247 .field("style", &self.style)
248 .field("interpreters", &self.interpreters)
249 .field("dog", &format_args!("<{} tables>", self.dog.len()))
250 .finish()
251 }
252}
253
254#[derive(Deserialize, Default)]
255#[serde(deny_unknown_fields, default)]
256struct RawDaemonConfig {
257 daemon: DaemonSection,
258 whistle: WhistleSection,
259 style: StyleSection,
260 interpreters: BTreeMap<String, String>,
261 dog: BTreeMap<String, toml::Table>,
262}
263
264impl DaemonConfig {
265 /// Builds config from optional file source + environment overrides
266 ///
267 /// `file < env`, validated. Equivalent to
268 /// [`Self::load_layered`] with an empty [`DaemonOverrides`]; unchanged
269 /// for every existing caller.
270 ///
271 /// # Errors
272 ///
273 /// - [`DaemonConfigError::Toml`] — the file source is invalid TOML.
274 /// - [`DaemonConfigError::BadEnvValue`] — a `SHEP_*` value is not
275 /// parseable (`SHEP_LOG_JSON` accepts `1|0|true|false`;
276 /// `SHEP_LOG_LEVEL` accepts a [`LogLevel`] name;
277 /// `SHEP_MAX_CRON_SLEEP` parses as an [`UpDuration`]).
278 /// - [`DaemonConfigError::BelowMinimum`] — the effective
279 /// `max_cron_sleep` (file, `SHEP_MAX_CRON_SLEEP`, whichever won) is
280 /// below the floor.
281 pub fn load(
282 file_source: Option<&str>,
283 env: &dyn Fn(&str) -> Option<String>,
284 ) -> Result<Self, DaemonConfigError> {
285 Self::load_layered(file_source, env, &DaemonOverrides::new())
286 }
287
288 /// Builds config from optional file source + environment + CLI-flag
289 /// overrides
290 ///
291 /// `file < env < flags` (spec §5), validated exactly once, at the end —
292 /// see the private `validate` method below for why validating per layer
293 /// instead would be wrong.
294 ///
295 /// # Errors
296 ///
297 /// - [`DaemonConfigError::Toml`] — the file source is invalid TOML.
298 /// - [`DaemonConfigError::BadEnvValue`] — a `SHEP_*` value is not
299 /// parseable (`SHEP_LOG_JSON` accepts `1|0|true|false`;
300 /// `SHEP_LOG_LEVEL` accepts a [`LogLevel`] name;
301 /// `SHEP_MAX_CRON_SLEEP` parses as an [`UpDuration`]).
302 /// - [`DaemonConfigError::BelowMinimum`] — the effective
303 /// `max_cron_sleep` (file, `SHEP_MAX_CRON_SLEEP`, or
304 /// `--max-cron-sleep`, whichever won) is below the floor.
305 pub fn load_layered(
306 file_source: Option<&str>,
307 env: &dyn Fn(&str) -> Option<String>,
308 overrides: &DaemonOverrides,
309 ) -> Result<Self, DaemonConfigError> {
310 let raw: RawDaemonConfig = match file_source {
311 Some(src) => toml::from_str(src).map_err(|e| DaemonConfigError::Toml(e.to_string()))?,
312 None => RawDaemonConfig::default(),
313 };
314 let mut cfg = Self {
315 daemon: raw.daemon,
316 whistle: raw.whistle,
317 style: raw.style,
318 interpreters: raw.interpreters,
319 dog: raw.dog,
320 };
321 if let Some(v) = env("SHEP_LOG_JSON") {
322 cfg.daemon.log_json = match parse_daemon_bool(&v) {
323 Some(value) => value,
324 None => return Err(DaemonConfigError::BadEnvValue("SHEP_LOG_JSON", v)),
325 };
326 }
327 if let Some(v) = env("SHEP_LOG_LEVEL") {
328 let Some(level) = LogLevel::from_name(&v) else {
329 return Err(DaemonConfigError::BadEnvValue("SHEP_LOG_LEVEL", v));
330 };
331 cfg.daemon.log_level = level;
332 }
333 if let Some(v) = env("SHEP_SOCKET") {
334 cfg.daemon.socket = Some(std::path::PathBuf::from(v));
335 }
336 // Provenance needs no tracking beyond this one flag: whichever layer
337 // last wrote max_cron_sleep is the key the refusal names, so the
338 // operator is pointed at the thing they can actually edit.
339 // Validating each layer as it is read instead would make a good
340 // SHEP_MAX_CRON_SLEEP unable to rescue a broken shep.toml, or a good
341 // --max-cron-sleep unable to rescue either, which is not what
342 // "file < env < flags" means.
343 let mut max_cron_sleep_key = "max_cron_sleep";
344 if let Some(v) = env("SHEP_MAX_CRON_SLEEP") {
345 let parsed = v
346 .parse::<UpDuration>()
347 .map_err(|_| DaemonConfigError::BadEnvValue("SHEP_MAX_CRON_SLEEP", v))?;
348 cfg.daemon.max_cron_sleep = Some(parsed);
349 max_cron_sleep_key = "SHEP_MAX_CRON_SLEEP";
350 }
351 if let Some(value) = overrides.log_json {
352 cfg.daemon.log_json = value;
353 }
354 if let Some(value) = overrides.log_level {
355 cfg.daemon.log_level = value;
356 }
357 if let Some(value) = &overrides.socket {
358 cfg.daemon.socket = Some(value.clone());
359 }
360 if let Some(value) = overrides.max_cron_sleep {
361 cfg.daemon.max_cron_sleep = Some(value);
362 max_cron_sleep_key = "--max-cron-sleep";
363 }
364 cfg.validate(max_cron_sleep_key)?;
365 Ok(cfg)
366 }
367
368 /// Checks every invariant a `DaemonConfig` carries, whatever layers
369 /// produced it.
370 ///
371 /// One call site, at the bottom of [`Self::load_layered`], and that is
372 /// the point: validating per layer would stop a good `--max-cron-sleep`
373 /// from rescuing a broken `shep.toml`, which is not what
374 /// `file < env < flags` means. The same reasoning the env layer already
375 /// carries, extended one layer up.
376 ///
377 /// `key` is provenance — the spelling the operator actually set, so the
378 /// refusal names the thing they can edit.
379 ///
380 /// Private. It guards construction, not mutation: a caller outside this
381 /// crate can assign to a `pub` field afterwards and this never runs
382 /// again. See the type's own doc for why that is accepted rather than
383 /// closed.
384 ///
385 /// # Errors
386 ///
387 /// - [`DaemonConfigError::BelowMinimum`] — `max_cron_sleep` is under the
388 /// floor that keeps the cron loop from spinning.
389 fn validate(&self, key: &'static str) -> Result<(), DaemonConfigError> {
390 if let Some(value) = self.daemon.max_cron_sleep
391 && value < MIN_CRON_SLEEP
392 {
393 return Err(DaemonConfigError::BelowMinimum {
394 key,
395 value,
396 min: MIN_CRON_SLEEP,
397 });
398 }
399 Ok(())
400 }
401}
402
403/// The CLI-flag layer of `file < env < flags` (spec §5).
404///
405/// Every field is `Option`: `None` means the flag was absent and the layer
406/// below wins. Nothing here validates — [`DaemonConfig::load_layered`] runs
407/// [`DaemonConfig`]'s single validation pass once, after all three layers,
408/// so a flag can rescue a file the layer below would have rejected.
409///
410/// `#[non_exhaustive]` because this type grows a field every time the hidden
411/// `daemon` subcommand grows a flag; that is anticipated by construction, not
412/// hypothetical — the same field-growth reasoning [`DaemonConfig`] carries,
413/// and like it, not a claim that the value was validated. Build one with
414/// [`Self::new`] and the chained setters — the consuming-self shape
415/// `ProcessInfo::builder` already uses in this workspace, and the shape
416/// `#[non_exhaustive]` requires, since it rules out struct literals and
417/// functional update from outside.
418///
419/// `Debug` is derived rather than redacted (IR-41): four values, none of
420/// them a secret — a socket path and a log level are already visible in
421/// `ps`.
422#[non_exhaustive]
423#[derive(Debug, Clone, Default, PartialEq, Eq)]
424pub struct DaemonOverrides {
425 /// `--log-json`
426 pub log_json: Option<bool>,
427 /// `--log-level`
428 pub log_level: Option<LogLevel>,
429 /// `--socket`
430 pub socket: Option<PathBuf>,
431 /// `--max-cron-sleep`
432 pub max_cron_sleep: Option<UpDuration>,
433}
434
435impl DaemonOverrides {
436 /// An empty layer — every flag absent.
437 #[must_use]
438 pub fn new() -> Self {
439 Self::default()
440 }
441
442 /// Sets the `--log-json` override.
443 #[must_use]
444 pub fn log_json(mut self, value: Option<bool>) -> Self {
445 self.log_json = value;
446 self
447 }
448
449 /// Sets the `--log-level` override.
450 #[must_use]
451 pub fn log_level(mut self, value: Option<LogLevel>) -> Self {
452 self.log_level = value;
453 self
454 }
455
456 /// Sets the `--socket` override.
457 #[must_use]
458 pub fn socket(mut self, value: Option<PathBuf>) -> Self {
459 self.socket = value;
460 self
461 }
462
463 /// Sets the `--max-cron-sleep` override.
464 #[must_use]
465 pub fn max_cron_sleep(mut self, value: Option<UpDuration>) -> Self {
466 self.max_cron_sleep = value;
467 self
468 }
469}
470
471/// The boolean grammar of `shep.toml` and the `SHEP_*` environment: `1`, `0`,
472/// `true`, `false`, and nothing else.
473///
474/// One function so the file/env layer and the `--log-json` flag cannot drift.
475/// clap's own `BoolishValueParser` additionally accepts
476/// `yes`/`no`/`y`/`n`/`on`/`off`; using it would widen the grammar on the flag
477/// side only, and widening an input grammar beyond spec is a named drift risk
478/// on this project.
479///
480/// The name says whose grammar this is on purpose. It is not a general
481/// boolean parser and must not be widened into one: the whole value of
482/// exporting it is that there is exactly one answer to "what counts as true
483/// in shep's daemon config".
484#[must_use]
485pub fn parse_daemon_bool(value: &str) -> Option<bool> {
486 match value {
487 "1" | "true" => Some(true),
488 "0" | "false" => Some(false),
489 _ => None,
490 }
491}
492
493/// Error type returned from [`DaemonConfig::load`]
494///
495/// `#[non_exhaustive]`: every `[daemon]` key this crate learns to validate
496/// brings its own rejection reason, and `deferred.md`'s daemon-config flags
497/// layer is a whole set of them at once (IR-20 — the same reasoning
498/// [`NormalizeError`](crate::config::NormalizeError) states for the per-app
499/// side).
500#[non_exhaustive]
501#[derive(Debug, Clone, PartialEq, Eq)]
502pub enum DaemonConfigError {
503 /// `shep.toml` is invalid TOML (carries the parser message)
504 Toml(String),
505 /// A `SHEP_*` env var held an unparseable value (var name, value)
506 BadEnvValue(&'static str, String),
507 /// A `[daemon]` duration is below the floor that keeps the daemon from
508 /// spinning. Carries the key the user actually set — the TOML key or
509 /// the environment variable, whichever supplied the winning value.
510 BelowMinimum {
511 /// `max_cron_sleep` or `SHEP_MAX_CRON_SLEEP`.
512 key: &'static str,
513 /// The value as the user wrote it.
514 value: UpDuration,
515 /// The floor it failed.
516 min: UpDuration,
517 },
518}
519
520impl fmt::Display for DaemonConfigError {
521 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
522 match self {
523 Self::Toml(m) => write!(f, "invalid shep.toml: {m}"),
524 Self::BadEnvValue(var, v) => write!(f, "invalid value `{v}` for {var}"),
525 Self::BelowMinimum { key, value, min } => {
526 write!(
527 f,
528 "invalid value `{value}` for {key}: must be at least {min}"
529 )
530 }
531 }
532 }
533}
534
535impl core::error::Error for DaemonConfigError {}
536
537#[cfg(test)]
538mod tests {
539 use super::*;
540 use crate::values::UpDuration;
541
542 fn no_env(_: &str) -> Option<String> {
543 None
544 }
545
546 // fails if a serde default invents 60s in shep-core and takes the
547 // "unset" state away from the layer below
548 #[test]
549 fn missing_max_cron_sleep_leaves_the_field_none() {
550 let cfg = DaemonConfig::load(None, &no_env).unwrap();
551 assert_eq!(cfg.daemon.max_cron_sleep, None);
552 }
553
554 // fails if the field is a bare integer, where "5m" is a TOML error and
555 // "5" is five milliseconds
556 #[test]
557 fn max_cron_sleep_file_value_parses_via_upduration() {
558 let cfg = DaemonConfig::load(Some("[daemon]\nmax_cron_sleep = \"5m\""), &no_env).unwrap();
559 assert_eq!(
560 cfg.daemon.max_cron_sleep,
561 Some(UpDuration::from_millis(5 * 60_000))
562 );
563 }
564
565 // fails if the env read is placed before the file is folded in, or
566 // omitted entirely
567 #[test]
568 fn env_max_cron_sleep_beats_file_value() {
569 let env = |k: &str| (k == "SHEP_MAX_CRON_SLEEP").then(|| "90s".to_string());
570 let cfg = DaemonConfig::load(Some("[daemon]\nmax_cron_sleep = \"5m\""), &env).unwrap();
571 assert_eq!(
572 cfg.daemon.max_cron_sleep,
573 Some(UpDuration::from_millis(90_000))
574 );
575 }
576
577 // fails if the env read swallows its parse failure (`.ok()` and drop
578 // it, or an `Err` arm that only logs), leaving the file's value
579 // silently in force and the typo invisible
580 #[test]
581 fn bad_env_max_cron_sleep_is_a_typed_error() {
582 let env = |k: &str| (k == "SHEP_MAX_CRON_SLEEP").then(|| "banana".to_string());
583 assert_eq!(
584 DaemonConfig::load(None, &env),
585 Err(DaemonConfigError::BadEnvValue(
586 "SHEP_MAX_CRON_SLEEP",
587 "banana".to_string()
588 ))
589 );
590 }
591
592 // fails if the floor is compared with `>` instead of `>=`, or the check
593 // silently clamps instead of rejecting
594 #[test]
595 fn max_cron_sleep_floor_rejects_below_one_second() {
596 let cfg = DaemonConfig::load(Some("[daemon]\nmax_cron_sleep = \"1s\""), &no_env).unwrap();
597 assert_eq!(
598 cfg.daemon.max_cron_sleep,
599 Some(UpDuration::from_millis(1_000))
600 );
601
602 assert_eq!(
603 DaemonConfig::load(Some("[daemon]\nmax_cron_sleep = \"999\""), &no_env),
604 Err(DaemonConfigError::BelowMinimum {
605 key: "max_cron_sleep",
606 value: UpDuration::from_millis(999),
607 min: UpDuration::from_millis(1_000),
608 })
609 );
610 }
611
612 // fails if only the file value is validated and never the override, or
613 // if the reported key is the file's even though the environment
614 // introduced the fault
615 #[test]
616 fn env_max_cron_sleep_floor_check_runs_on_the_winner() {
617 let env = |k: &str| (k == "SHEP_MAX_CRON_SLEEP").then(|| "0".to_string());
618 assert_eq!(
619 DaemonConfig::load(Some("[daemon]\nmax_cron_sleep = \"5m\""), &env),
620 Err(DaemonConfigError::BelowMinimum {
621 key: "SHEP_MAX_CRON_SLEEP",
622 value: UpDuration::from_millis(0),
623 min: UpDuration::from_millis(1_000),
624 })
625 );
626 }
627
628 // fails if the message wording drifts (e.g. "invalid" alone, or the
629 // `key`/`min` operands swapped) without anyone noticing — this is the
630 // entire user-facing payload of the reject-don't-clamp decision: it is
631 // what actually reaches `shepd.err.log` on exit code 4.
632 #[test]
633 fn below_minimum_display_is_exact() {
634 let err = DaemonConfigError::BelowMinimum {
635 key: "max_cron_sleep",
636 value: UpDuration::from_millis(999),
637 min: UpDuration::from_millis(1_000),
638 };
639 assert_eq!(
640 err.to_string(),
641 "invalid value `999` for max_cron_sleep: must be at least 1s"
642 );
643 }
644
645 #[test]
646 fn missing_file_yields_defaults() {
647 let cfg = DaemonConfig::load(None, &no_env).unwrap();
648 assert!(!cfg.daemon.log_json);
649 assert!(cfg.daemon.enabled_dogs.is_empty());
650 assert!(cfg.dog.is_empty());
651 }
652
653 #[test]
654 fn file_sets_values_and_keeps_dog_sections_raw() {
655 let src = r#"
656[daemon]
657log_json = true
658enabled_dogs = ["metrics"]
659
660[dog.metrics]
661port = 9615
662"#;
663 let cfg = DaemonConfig::load(Some(src), &no_env).unwrap();
664 assert!(cfg.daemon.log_json);
665 assert_eq!(cfg.daemon.enabled_dogs, vec!["metrics"]);
666 assert_eq!(cfg.dog["metrics"]["port"].as_integer(), Some(9615));
667 }
668
669 /// fails if `adopted_dogs` is not `default`ed, or is declared outside
670 /// `deny_unknown_fields`'s reach: a `shep.toml` written before it
671 /// existed must still load, and a typo'd key must still be refused.
672 /// Both halves matter — dropping `default` breaks every existing file,
673 /// and the table is the one place an operator names a binary shep is
674 /// about to run at the daemon's own trust level.
675 #[test]
676 fn adopted_dogs_default_empty_and_round_trip_by_name() {
677 let bare = DaemonConfig::load(Some("[daemon]\nlog_json = true\n"), &no_env).unwrap();
678 assert!(bare.daemon.adopted_dogs.is_empty());
679
680 let src = r#"
681[daemon]
682enabled_dogs = ["metrics", "otel"]
683
684[daemon.adopted_dogs]
685otel = "/usr/local/bin/shep-otel"
686"#;
687 let cfg = DaemonConfig::load(Some(src), &no_env).unwrap();
688 assert_eq!(cfg.daemon.enabled_dogs, vec!["metrics", "otel"]);
689 assert_eq!(
690 cfg.daemon.adopted_dogs.get("otel"),
691 Some(&std::path::PathBuf::from("/usr/local/bin/shep-otel"))
692 );
693 assert!(
694 !cfg.daemon.adopted_dogs.contains_key("metrics"),
695 "a name with no entry here is a built-in, and that is the whole distinction"
696 );
697 }
698
699 #[test]
700 fn env_overrides_file() {
701 let env = |k: &str| (k == "SHEP_LOG_JSON").then(|| "true".to_string());
702 let cfg = DaemonConfig::load(Some("[daemon]\nlog_json = false"), &env).unwrap();
703 assert!(cfg.daemon.log_json);
704 }
705
706 // The default decides what an operator who configured nothing actually
707 // sees, and every warn-and-continue arm in the daemon rides on it. `Off`
708 // would hide all of them; `Info` and below would bury them.
709 //
710 // fails if the `#[default]` attribute moves to another variant, or if a
711 // serde default invents a level the enum's own `Default` does not agree
712 // with.
713 #[test]
714 fn an_unset_log_level_is_warn() {
715 assert_eq!(
716 DaemonConfig::load(None, &no_env).unwrap().daemon.log_level,
717 LogLevel::Warn
718 );
719 }
720
721 // One owner for the six names (Rule 9). `as_str`, `from_name` and serde's
722 // `rename_all` are three separate spellings of the same mapping, and
723 // nothing but this makes them agree.
724 //
725 // fails if any one of the three drifts from the other two — a `rename_all`
726 // dropped or changed to `snake_case`, an `as_str` arm returning the
727 // variant name verbatim, a `from_name` arm mapped to the wrong level.
728 #[test]
729 fn every_log_level_name_means_the_same_thing_in_the_file_and_the_environment() {
730 let levels = [
731 LogLevel::Off,
732 LogLevel::Error,
733 LogLevel::Warn,
734 LogLevel::Info,
735 LogLevel::Debug,
736 LogLevel::Trace,
737 ];
738 for level in levels {
739 let name = level.as_str();
740 assert_eq!(LogLevel::from_name(name), Some(level), "from_name({name})");
741
742 let file = format!("[daemon]\nlog_level = \"{name}\"");
743 let cfg = DaemonConfig::load(Some(&file), &no_env).unwrap();
744 assert_eq!(cfg.daemon.log_level, level, "[daemon] log_level = {name:?}");
745
746 let env = |k: &str| (k == "SHEP_LOG_LEVEL").then(|| name.to_string());
747 let cfg = DaemonConfig::load(None, &env).unwrap();
748 assert_eq!(cfg.daemon.log_level, level, "SHEP_LOG_LEVEL={name}");
749 }
750 }
751
752 // fails if the env read is placed before the file is folded in, or omitted
753 // entirely — the shape that leaves a knob parsed and never applied.
754 #[test]
755 fn env_log_level_beats_file_value() {
756 let env = |k: &str| (k == "SHEP_LOG_LEVEL").then(|| "debug".to_string());
757 let cfg = DaemonConfig::load(Some("[daemon]\nlog_level = \"error\""), &env).unwrap();
758 assert_eq!(cfg.daemon.log_level, LogLevel::Debug);
759 }
760
761 // fails if the env read swallows an unknown name and leaves the default
762 // standing — a daemon that silently logs at `warn` after being asked for
763 // `trace` is indistinguishable from one with nothing to say. Also fails if
764 // the grammar is widened to accept case-insensitive names, which
765 // `SHEP_LOG_JSON` does not accept either.
766 #[test]
767 fn bad_env_log_level_is_a_typed_error() {
768 for value in ["verbose", "WARN", ""] {
769 let env = |k: &str| (k == "SHEP_LOG_LEVEL").then(|| value.to_string());
770 assert_eq!(
771 DaemonConfig::load(None, &env),
772 Err(DaemonConfigError::BadEnvValue(
773 "SHEP_LOG_LEVEL",
774 value.to_string()
775 )),
776 "SHEP_LOG_LEVEL={value:?}"
777 );
778 }
779 }
780
781 // fails if the enum grows a `#[serde(other)]` catch-all, which would turn
782 // a misspelled level in `shep.toml` into a silent fallback instead of the
783 // startup error `ExitCode::InvalidConfig` reports.
784 //
785 // Also fails if `log_level` is dropped from `DaemonSection` altogether,
786 // which the variant alone cannot tell apart: `deny_unknown_fields` answers
787 // an undefined key with the same `Toml` variant. Asserting the message
788 // merely mentions `verbose` would not separate them either — a
789 // `deny_unknown_fields` error echoes the offending source line, the value
790 // included, which was checked against a key this section really does not
791 // define. Only "unknown *variant*" is exclusive to the level's own name
792 // being rejected, so that is what is pinned; the wording is serde's, and
793 // it is also what an operator reads out of `ExitCode::InvalidConfig`.
794 #[test]
795 fn bad_file_log_level_is_a_toml_error() {
796 let err = DaemonConfig::load(Some("[daemon]\nlog_level = \"verbose\""), &no_env)
797 .expect_err("a misspelled level must not parse");
798 let DaemonConfigError::Toml(message) = err else {
799 panic!("a misspelled level is a TOML error, not {err:?}");
800 };
801 assert!(
802 message.contains("unknown variant `verbose`"),
803 "the error must reject the level's own name, not some other key: {message:?}"
804 );
805 }
806
807 #[test]
808 fn socket_override_via_file_and_env() {
809 let cfg = DaemonConfig::load(Some("[daemon]\nsocket = \"/tmp/a.sock\""), &no_env).unwrap();
810 assert_eq!(
811 cfg.daemon.socket.as_deref(),
812 Some(std::path::Path::new("/tmp/a.sock"))
813 );
814 let env = |k: &str| (k == "SHEP_SOCKET").then(|| "/tmp/b.sock".to_string());
815 let cfg = DaemonConfig::load(Some("[daemon]\nsocket = \"/tmp/a.sock\""), &env).unwrap();
816 assert_eq!(
817 cfg.daemon.socket.as_deref(),
818 Some(std::path::Path::new("/tmp/b.sock"))
819 );
820 }
821
822 #[test]
823 fn bad_toml_is_a_typed_error() {
824 assert!(matches!(
825 DaemonConfig::load(Some("[daemon"), &no_env),
826 Err(DaemonConfigError::Toml(_))
827 ));
828 }
829
830 // fails if `[whistle]` stops being a section the shepherd will start
831 // with: `RawDaemonConfig` denies unknown fields, so a `[whistle]`
832 // section this type did not know about would return
833 // `DaemonConfigError::Toml` and `shep daemon` would exit 4 — an
834 // operator who turned whistle's control tools on would lose their
835 // shepherd on the next boot.
836 #[test]
837 fn a_whistle_section_parses_and_defaults_to_refusing_control() {
838 let cfg = DaemonConfig::load(Some("[whistle]\nallow_control = true\n"), &no_env).unwrap();
839 assert!(cfg.whistle.allow_control);
840
841 let absent = DaemonConfig::load(Some("[daemon]\nlog_level = \"info\"\n"), &no_env).unwrap();
842 assert!(
843 !absent.whistle.allow_control,
844 "a file with no [whistle] section leaves control off"
845 );
846
847 // The third case, and it is a DIFFERENT code path from the second:
848 // an absent `[whistle]` table is filled by `RawDaemonConfig`'s own
849 // container-level `#[serde(default)]`, which never consults the
850 // field's serde default at all. A present-but-empty table is the
851 // only input that does. Without this line, a field-level
852 // `#[serde(default = "...")]` on `allow_control` could flip the gate
853 // open and no test in this file would notice — which is exactly
854 // what the first draft's mutation assumed it was proving.
855 let empty_table = DaemonConfig::load(Some("[whistle]\n"), &no_env).unwrap();
856 assert!(
857 !empty_table.whistle.allow_control,
858 "a [whistle] section with no keys leaves control off"
859 );
860 }
861
862 // fails if the section silently accepts a key it does not implement. A
863 // `[whistle] allow_contro = true` typo that parsed would leave an
864 // operator certain the gate was open and whistle certain it was shut,
865 // with nothing anywhere saying otherwise.
866 #[test]
867 fn a_misspelled_whistle_key_is_a_named_error() {
868 let err =
869 DaemonConfig::load(Some("[whistle]\nallow_contro = true\n"), &no_env).unwrap_err();
870 let DaemonConfigError::Toml(message) = err else {
871 panic!("a misspelled key is a TOML error, got {err:?}")
872 };
873 // The full quoted form, not the bare stem: `"allow_control"` also
874 // contains `"allow_contro"`, so an assertion on the stem would pass
875 // on a message that named only what serde EXPECTED and never quoted
876 // what the operator actually wrote. serde's `deny_unknown_fields`
877 // message is "unknown field `allow_contro`, expected
878 // `allow_control`", and the closing backtick is what distinguishes
879 // the two.
880 assert!(
881 message.contains("unknown field `allow_contro`"),
882 "the message quotes the key that was not understood: {message}"
883 );
884 }
885
886 // fails if validation moves back into a per-layer position — the flags
887 // layer must be able to rescue a file the layer below would reject,
888 // which is what `file < env < flags` means. Same rule the env layer's
889 // own comment already states.
890 #[test]
891 fn a_flag_rescues_a_below_floor_file_value() {
892 let cfg = DaemonConfig::load_layered(
893 Some("[daemon]\nmax_cron_sleep = \"500\"\n"),
894 &no_env,
895 &DaemonOverrides::new().max_cron_sleep(Some(UpDuration::from_millis(300_000))),
896 )
897 .unwrap();
898 assert_eq!(
899 cfg.daemon.max_cron_sleep,
900 Some(UpDuration::from_millis(300_000))
901 );
902 }
903
904 // fails if a below-floor FLAG is accepted, or if the refusal names the
905 // TOML key the operator did not set.
906 #[test]
907 fn a_below_floor_flag_is_refused_naming_the_flag() {
908 let err = DaemonConfig::load_layered(
909 None,
910 &no_env,
911 &DaemonOverrides::new().max_cron_sleep(Some(UpDuration::from_millis(500))),
912 )
913 .unwrap_err();
914 assert_eq!(
915 err,
916 DaemonConfigError::BelowMinimum {
917 key: "--max-cron-sleep",
918 value: UpDuration::from_millis(500),
919 min: MIN_CRON_SLEEP,
920 }
921 );
922 assert!(err.to_string().contains("--max-cron-sleep"), "got: {err}");
923 }
924
925 // fails if a flag stops beating the env layer.
926 #[test]
927 fn a_flag_beats_the_environment() {
928 let env = |k: &str| (k == "SHEP_LOG_LEVEL").then(|| "trace".to_string());
929 let cfg = DaemonConfig::load_layered(
930 Some("[daemon]\nlog_level = \"error\"\n"),
931 &env,
932 &DaemonOverrides::new().log_level(Some(LogLevel::Info)),
933 )
934 .unwrap();
935 assert_eq!(cfg.daemon.log_level, LogLevel::Info);
936 }
937
938 // Pins that `load` (the two-layer file+env path) and `load_layered`
939 // (the three-layer file+env+flags path `load` itself delegates to)
940 // agree when no flag is set. It does NOT catch a `bool` field standing
941 // in for `Option<bool>`: `load` routes through `load_layered` on both
942 // sides of the `assert_eq!`, so a mutation on that line lands on both
943 // sides alike and this test stays green. That guard is
944 // `file_sets_values_and_keeps_dog_sections_raw` and `env_overrides_file`
945 // in this file, and cli_e2e's
946 // `shep_log_json_makes_the_daemons_own_records_json` — each pins an
947 // actual value coming through a specific layer, which a flattened
948 // `Option<bool>` would get wrong.
949 #[test]
950 fn an_absent_flag_leaves_every_lower_layer_alone() {
951 let src = "[daemon]\nlog_json = true\nlog_level = \"debug\"\nsocket = \"/tmp/s.sock\"\n";
952 let layered =
953 DaemonConfig::load_layered(Some(src), &no_env, &DaemonOverrides::new()).unwrap();
954 let plain = DaemonConfig::load(Some(src), &no_env).unwrap();
955 assert_eq!(layered, plain);
956 }
957
958 #[test]
959 fn the_bool_grammar_is_exactly_four_spellings() {
960 assert_eq!(parse_daemon_bool("1"), Some(true));
961 assert_eq!(parse_daemon_bool("0"), Some(false));
962 assert_eq!(parse_daemon_bool("true"), Some(true));
963 assert_eq!(parse_daemon_bool("false"), Some(false));
964 for wider in ["yes", "no", "on", "off", "TRUE", "y"] {
965 assert_eq!(
966 parse_daemon_bool(wider),
967 None,
968 "{wider} must not be a boolean here"
969 );
970 }
971 }
972
973 // fails if `[interpreters]` stops parsing as a plain extension ->
974 // interpreter map, or if a value written as a bare word (no quotes
975 // needed, since these are ordinary TOML strings) fails to round-trip.
976 #[test]
977 fn interpreters_parses_as_an_extension_map() {
978 let cfg = DaemonConfig::load(
979 Some("[interpreters]\njs = \"node\"\npy = \"python3\"\n"),
980 &no_env,
981 )
982 .unwrap();
983 assert_eq!(cfg.interpreters.get("js").map(String::as_str), Some("node"));
984 assert_eq!(
985 cfg.interpreters.get("py").map(String::as_str),
986 Some("python3")
987 );
988 assert_eq!(cfg.interpreters.len(), 2);
989 }
990
991 // An empty/absent `[interpreters]` must not fail a `shep.toml` that
992 // never mentions the section at all -- most of them, until an operator
993 // (or the first-run scaffold) writes one.
994 #[test]
995 fn interpreters_defaults_to_empty() {
996 assert!(
997 DaemonConfig::load(None, &no_env)
998 .unwrap()
999 .interpreters
1000 .is_empty()
1001 );
1002 assert!(
1003 DaemonConfig::load(Some("[daemon]\nlog_json = true\n"), &no_env)
1004 .unwrap()
1005 .interpreters
1006 .is_empty()
1007 );
1008 }
1009
1010 // `[interpreters]` values are arbitrary extension keys, not a fixed
1011 // field set, so `deny_unknown_fields` (which governs *struct* fields)
1012 // must not reject an extension this build has never heard of -- that
1013 // would defeat the whole point of an operator-editable map.
1014 #[test]
1015 fn an_unrecognised_extension_is_not_an_unknown_field() {
1016 let cfg = DaemonConfig::load(Some("[interpreters]\nlua = \"lua5.4\"\n"), &no_env).unwrap();
1017 assert_eq!(
1018 cfg.interpreters.get("lua").map(String::as_str),
1019 Some("lua5.4")
1020 );
1021 }
1022
1023 // A value that is not a string (an operator's `js = 5`, say) is still a
1024 // parse error -- shep-core's usual "fail loudly at parse time" rule for
1025 // a bad shape, same as every other typed field in this file.
1026 #[test]
1027 fn a_non_string_interpreter_value_is_a_parse_error() {
1028 assert!(DaemonConfig::load(Some("[interpreters]\njs = 5\n"), &no_env).is_err());
1029 }
1030
1031 #[test]
1032 fn debug_redacts_dog_values() {
1033 // Dog tables carry things like webhook URLs; a lazy derive(Debug)
1034 // would land them in daemon logs. Exact string pinned so that
1035 // regression fails here instead of leaking a secret.
1036 let cfg = DaemonConfig::load(Some("[dog.metrics]\nport = 9615"), &no_env).unwrap();
1037 assert_eq!(
1038 format!("{cfg:?}"),
1039 "DaemonConfig { daemon: DaemonSection { log_json: false, log_level: Warn, socket: None, enabled_dogs: [], adopted_dogs: {}, max_cron_sleep: None }, whistle: WhistleSection { allow_control: false }, style: StyleSection { level: None }, interpreters: {}, dog: <1 tables> }"
1040 );
1041 }
1042}