shep-core 0.9.0

Types, Flockfile parsing, and the wire protocol shared by the shep process manager's daemon, client, and CLI
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
use std::collections::BTreeSet;
use std::path::Path;

use crate::config::{AppConfig, CronParseError, CronSchedule, KillSignal, LevelMatcher};
use crate::secrets;
use crate::values::UpDuration;

use super::{NormalizeError, tilde, validate};

/// A validated app config: only obtainable via [`normalize`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ResolvedApp {
    pub(super) config: AppConfig,
}

impl ResolvedApp {
    /// Borrow the validated configuration
    #[must_use]
    pub fn config(&self) -> &AppConfig {
        &self.config
    }

    /// Unwrap the validated configuration (consumes the proof token)
    #[must_use]
    pub fn into_config(self) -> AppConfig {
        self.config
    }
}

/// Validates one app config
///
/// # Errors
///
/// - [`NormalizeError::MissingName`]: `name` is empty.
/// - [`NormalizeError::InvalidName`]: `name` contains a path separator or a colon, or is `.`/`..`.
/// - [`NormalizeError::InvalidEnvironment`]: `environment` is `all`, the secrets store's every-environment slot, or falls outside the store's name grammar.
/// - [`NormalizeError::ReservedEnvVar`]: `env` sets `SHEP_INSTANCE`, `SHEP_NAME` or `SHEP_ENVIRONMENT`, which shep injects itself.
/// - [`NormalizeError::MissingScript`]: `script` is empty.
/// - [`NormalizeError::ZeroInstances`]: `instances == 0`.
/// - [`NormalizeError::InvalidCron`]: `cron_restart` is not valid in croner's dialect.
/// - [`NormalizeError::InvalidTimezone`]: `cron_timezone` is not a name in the IANA time-zone database.
/// - [`NormalizeError::InvalidProbe`]: a `readiness_probe`/`liveness_probe` target [`ProbeTarget::parse`](crate::config::ProbeTarget::parse) rejects.
/// - [`NormalizeError::ZeroFailureThreshold`]: a probe's `failure_threshold` is explicitly `0`.
/// - [`NormalizeError::IntervalBelowMinimum`]: a probe's `interval` is under the floor its own loop honours.
/// - [`NormalizeError::ZeroMaxMemory`]: `max_memory` is `0`.
/// - [`NormalizeError::ActionTimeoutTooLong`]: `action_timeout` is at or above the ceiling no RPC caller could wait past.
/// - [`NormalizeError::InvalidKillSignal`]: `kill_signal` names a signal the daemon's stop ladder cannot send.
/// - [`NormalizeError::WatchWithoutCwd`]: `watch` is `true` with no `cwd` set.
/// - [`NormalizeError::ZeroWatchDelay`]: `watch_delay` is `0`.
/// - [`NormalizeError::InvalidWatchGlob`]: a `watch_options` or `ignore_watch` pattern globset will not compile.
/// - [`NormalizeError::InvalidLevelRule`]: a `level_rules` entry has an empty pattern, one regex will not compile, or the list is longer than the ceiling on how many rules an app may declare.
/// - [`NormalizeError::BadTemplate`]: an `env`/`args`/log-path value carries an undefined or unclosed `{{...}}` token.
/// - [`NormalizeError::SecretInLogPath`]: `out_file` or `err_file` carries a `{{secret:...}}`.
/// - [`NormalizeError::SharedLogPath`]: `out_file` or `err_file` renders to the same path for two instances.
/// - [`NormalizeError::TildeUser`]: a path field names another user's `~user` home.
/// - [`NormalizeError::NoHomeForTilde`]: a path field expands `~/` but no home directory could be found.
/// - [`NormalizeError::NoShepHome`]: a templated value carries `{{SHEP_HOME}}` but no shep home could be found.
/// - [`NormalizeError::SelfDependency`]: an app names itself in `depends_on`.
/// - [`NormalizeError::InstanceDependency`]: a `depends_on` entry is written `name:slot`.
pub fn normalize(app: AppConfig) -> Result<ResolvedApp, NormalizeError> {
    let home = std::env::home_dir();
    let shep_home = crate::paths::shep_home(&|key| std::env::var(key).ok(), home.as_deref());
    normalize_with_home(app, home.as_deref(), shep_home.as_deref())
}

/// Validates a whole flock, rejecting duplicate sheep names
///
/// # Errors
///
/// Everything [`normalize`] returns, plus
/// [`NormalizeError::DuplicateName`]: two apps share a `name`.
/// [`NormalizeError::DependencyCycle`]: two apps in the document depend on each other.
pub fn normalize_all(apps: Vec<AppConfig>) -> Result<Vec<ResolvedApp>, NormalizeError> {
    let mut seen = BTreeSet::new();
    let resolved: Vec<ResolvedApp> = apps
        .into_iter()
        .map(|app| {
            if !seen.insert(app.name.clone()) {
                return Err(NormalizeError::DuplicateName(app.name));
            }
            normalize(app)
        })
        .collect::<Result<_, _>>()?;
    // Document-local only: a name this document does not hold is left to the
    // daemon, which is the only place that knows the whole flock.
    let nodes: Vec<crate::config::graph::BootNode> = resolved
        .iter()
        .map(|app| crate::config::graph::BootNode {
            name: app.config().name.clone(),
            depends_on: app.config().depends_on.clone(),
            kind: crate::config::graph::NodeKind::Sheep,
        })
        .collect();
    if let Some(cycle) = crate::config::graph::plan(&nodes).cycles.into_iter().next() {
        return Err(NormalizeError::DependencyCycle(cycle));
    }
    Ok(resolved)
}

/// Shortest `interval` a `liveness_probe` may name.
///
/// The daemon's liveness loop floors whatever it is handed at this same
/// value, so a smaller number would be silently honoured as this one with
/// no warning.
///
/// One second is a floor no legitimate configuration wants to be under: for
/// [`ProbeKind::Exec`](crate::config::ProbeKind::Exec) a shorter interval is
/// that many process spawns per second, per sheep, for as long as it runs.
pub(super) const MIN_LIVENESS_INTERVAL: UpDuration = UpDuration::from_millis(1_000);

/// Shortest `interval` a `readiness_probe` may name.
///
/// A whole second lower than [`MIN_LIVENESS_INTERVAL`]: the readiness wait
/// honours its `interval` exactly as written, bounded by `listen_timeout`,
/// so only zero needs rejecting. A fast app polling every 20ms to leave
/// `starting` sooner must not lose that.
pub(super) const MIN_READINESS_INTERVAL: UpDuration = UpDuration::from_millis(1);

/// Longest `action_timeout` an app may name.
///
/// The daemon clamps every RPC deadline to `MAX_DEADLINE_MS` (60s, in
/// shep-daemon's `rpc` module), so a value at or above that line could
/// never be honoured by any caller. Set 2s under the clamp so the daemon
/// still has room to build the `TimedOut` row and send it back after the
/// wait gives up.
const MAX_ACTION_TIMEOUT: UpDuration = UpDuration::from_millis(58_000);

/// Parameters so the `~/` expansion above is testable without mutating the
/// process environment, which is racy under a parallel `cargo test`. This is
/// also the seam that matters for correctness rather than only for tests:
/// the daemon may run as a different user than the CLI, so `~` has to be
/// resolved where the config is normalised, not where it is executed.
///
/// `shep_home` arrives the same way and for the same reason: it is the
/// directory `{{SHEP_HOME}}` expands to, and reading it inside the renderer
/// would resolve it wherever the value happened to be rendered.
///
/// [`normalize`], with both home directories supplied rather than read.
///
/// # Errors
/// The same set [`normalize`] documents.
pub fn normalize_with_home(
    mut app: AppConfig,
    home: Option<&Path>,
    shep_home: Option<&Path>,
) -> Result<ResolvedApp, NormalizeError> {
    if app.name.is_empty() {
        return Err(NormalizeError::MissingName);
    }
    if app.name.contains(['/', '\\', ':']) || app.name == "." || app.name == ".." {
        return Err(NormalizeError::InvalidName(app.name));
    }
    if let Some(environment) = &app.environment
        && (environment == secrets::ALL_ENVIRONMENTS || !secrets::is_name(environment))
    {
        return Err(NormalizeError::InvalidEnvironment {
            name: app.name.clone(),
            value: environment.clone(),
        });
    }
    for var in ["SHEP_INSTANCE", "SHEP_NAME", "SHEP_ENVIRONMENT"] {
        if app.env.contains_key(var) {
            return Err(NormalizeError::ReservedEnvVar {
                name: app.name.clone(),
                var,
            });
        }
    }
    for (key, value) in &app.env {
        validate::validate_template(&app.name, &format!("env.{key}"), value, shep_home)?;
    }
    for (index, value) in app.args.iter().enumerate() {
        validate::validate_template(&app.name, &format!("args[{index}]"), value, shep_home)?;
    }
    for (field, value) in [("out_file", &app.out_file), ("err_file", &app.err_file)] {
        if let Some(value) = value {
            validate::validate_template(&app.name, field, value, shep_home)?;
            if crate::config::template::holds_secret(value) {
                return Err(NormalizeError::SecretInLogPath {
                    name: app.name.clone(),
                    field,
                });
            }
        }
    }
    if app.script.is_empty() {
        return Err(NormalizeError::MissingScript);
    }
    // After the emptiness checks, so a missing script is reported as missing
    // rather than as a path problem, and before every check below that reads
    // a path.
    tilde::expand_paths(&mut app, home)?;
    if app.instances == 0 {
        return Err(NormalizeError::ZeroInstances);
    }
    // After the template validation above, so a malformed `out_file`/`err_file`
    // is reported as a bad template rather than as a shared path.
    if app.instances > 1 && !app.merge_logs {
        for (field, path) in [("out_file", &app.out_file), ("err_file", &app.err_file)] {
            // Rendered rather than searched for a substring: an escaped
            // `{{{{instance}}}}` contains the token's spelling but renders to
            // one literal path for every instance, which is exactly the
            // collision this refuses. Two slots that render alike collide.
            if let Some(path) = path
                && crate::config::template::render_positional(path, &app.name, 0, shep_home)
                    == crate::config::template::render_positional(path, &app.name, 1, shep_home)
            {
                return Err(NormalizeError::SharedLogPath {
                    name: app.name.clone(),
                    field,
                });
            }
        }
    }
    if let Some(pattern) = &app.cron_restart {
        CronSchedule::parse(pattern, app.cron_timezone.as_deref()).map_err(|e| match e {
            CronParseError::Pattern { pattern, reason } => {
                NormalizeError::InvalidCron { pattern, reason }
            }
            CronParseError::Timezone { name } => NormalizeError::InvalidTimezone { name },
        })?;
    } else if let Some(tz_name) = &app.cron_timezone {
        // A Flockfile can carry `cron_timezone` with no `cron_restart` to
        // pair it with, still a typo the user wants to hear about.
        crate::config::cron::parse_timezone_name(tz_name).ok_or_else(|| {
            NormalizeError::InvalidTimezone {
                name: tz_name.clone(),
            }
        })?;
    }
    validate::validate_probe(
        app.readiness_probe.as_ref(),
        "readiness_probe",
        MIN_READINESS_INTERVAL,
    )?;
    validate::validate_probe(
        app.liveness_probe.as_ref(),
        "liveness_probe",
        MIN_LIVENESS_INTERVAL,
    )?;
    if app.max_memory.is_some_and(|limit| limit.bytes() == 0) {
        // A ceiling every live process is already over: the enforcer would
        // report a breach on every reading, and the automatic restart that
        // follows resets the restart budget rather than spending it, so
        // `max_restarts` can never end the loop.
        return Err(NormalizeError::ZeroMaxMemory { name: app.name });
    }
    if let Some(name) = &app.kill_signal
        && KillSignal::parse(name).is_none()
    {
        // Rejected rather than clamped: a typo silently falling back to
        // SIGTERM would cost every stop and reload for the life of the
        // process, with no evidence but a detached daemon's log.
        return Err(NormalizeError::InvalidKillSignal {
            name: app.name,
            value: name.clone(),
        });
    }
    if app.action_timeout > MAX_ACTION_TIMEOUT {
        // Rejected rather than clamped: every value above the ceiling is
        // equally unreachable by any caller, so there is no honest lowered
        // value to silently fall back to.
        return Err(NormalizeError::ActionTimeoutTooLong {
            name: app.name,
            value: app.action_timeout,
            max: MAX_ACTION_TIMEOUT,
        });
    }
    if app.watch && app.cwd.is_none() {
        // `watch` asked for a feature the daemon has no directory to arm:
        // there is no cwd in the Flockfile, and defaulting to the daemon's
        // own cwd risks watching the whole filesystem under a systemd unit
        // with no `WorkingDirectory=`.
        return Err(NormalizeError::WatchWithoutCwd { name: app.name });
    }
    if app.watch_delay == Some(UpDuration::from_millis(0)) {
        // notify's debouncer derives its own poll tick as `watch_delay / 4`
        // on a dedicated OS thread, so a zero turns that thread into
        // `loop { sleep(0); lock(); }`, a CPU-spinning busy loop.
        return Err(NormalizeError::ZeroWatchDelay { name: app.name });
    }
    // Both lists are checked whether or not `watch` is on, so a typo'd
    // pattern is named now rather than the day `watch` flips on and nothing
    // happens.
    validate::validate_watch_globs(&app.name, "watch_options", &app.watch_options)?;
    validate::validate_watch_globs(&app.name, "ignore_watch", &app.ignore_watch)?;
    // Compiled to reject, and the result discarded: whichever client
    // classifies this sheep's lines compiles its own. A pattern refused
    // here can never reach one, which is the point of refusing it at config
    // time rather than at render time, where nobody would read the message.
    LevelMatcher::compile(&app.level_rules).map_err(|err| NormalizeError::InvalidLevelRule {
        name: app.name.clone(),
        reason: err.to_string(),
    })?;
    let mut seen = BTreeSet::new();
    let mut deduped = Vec::with_capacity(app.depends_on.len());
    for target in &app.depends_on {
        if target == &app.name {
            return Err(NormalizeError::SelfDependency(app.name.clone()));
        }
        if target.contains(':') {
            return Err(NormalizeError::InstanceDependency {
                sheep: app.name.clone(),
                target: target.clone(),
            });
        }
        if seen.insert(target.clone()) {
            deduped.push(target.clone());
        }
    }
    app.depends_on = deduped;
    Ok(ResolvedApp { config: app })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::{LevelRule, LevelRuleError, LineLevel};

    /// `reuse_port` loads because reload's overlap mode is chosen from it:
    /// refusing it would deny an operator the only way to ask for an
    /// overlapping reload.
    #[test]
    fn reuse_port_loads_now_that_reload_reads_it() {
        let mut app = AppConfig::minimal("web", "./server");
        app.reuse_port = true;

        let resolved = normalize(app).expect("reuse_port is implemented");
        assert!(resolved.config().reuse_port);
    }

    /// The default is off, so every Flockfile that does not mention it keeps
    /// loading.
    #[test]
    fn an_app_that_never_mentions_reuse_port_still_normalizes() {
        let resolved = normalize(AppConfig::minimal("web", "./server"))
            .expect("the common case must be untouched");
        assert!(!resolved.config().reuse_port);
    }
    use crate::config::AppConfig;

    #[test]
    fn a_colon_in_a_name_is_refused_because_it_is_the_instance_separator() {
        let err = normalize(AppConfig::minimal("web:2", "./srv")).unwrap_err();
        assert_eq!(err, NormalizeError::InvalidName("web:2".to_string()));

        let rendered = err.to_string();
        assert!(rendered.contains(':'), "says which character: {rendered}");
        // Spec D3 requires the error to name the character and suggest `-`.
        assert!(
            rendered.contains("`-`"),
            "suggests the stand-in: {rendered}"
        );
        assert!(
            !rendered.contains('\u{2014}') && !rendered.contains('\u{2013}'),
            "no em or en dash in copy a user reads: {rendered}"
        );

        assert!(normalize(AppConfig::minimal("web-2", "./srv")).is_ok());
    }

    /// Each reserved variable is refused with advice that fits it (#284):
    /// the `{{instance}}` and `{{name}}` templates for the two identity
    /// variables, and the `environment` field for the one that is not a
    /// template token at all. Nothing carries another variable's advice.
    #[test]
    fn the_reserved_env_vars_are_refused_rather_than_overwritten() {
        // Every advice string the Display arm can produce, so each case can
        // assert the absence of all the others. Naming one counterpart each
        // left the environment advice unexcluded on both identity variables.
        let advice = [
            ("SHEP_INSTANCE", "or `{{instance}}` in your own variable"),
            ("SHEP_NAME", "or `{{name}}` in your own variable"),
            ("SHEP_ENVIRONMENT", "or set `environment` on the app"),
        ];
        for (var, fitting) in advice {
            let mut app = AppConfig::minimal("web", "./srv");
            app.env.insert(var.to_string(), "mine".to_string());
            let err = normalize(app).unwrap_err();
            let rendered = err.to_string();
            assert!(rendered.contains(var), "names the variable: {rendered}");
            assert!(
                rendered.contains(fitting),
                "{var} gets advice that fits it: {rendered}"
            );
            for (owner, unrelated) in advice {
                assert!(
                    owner == var || !rendered.contains(unrelated),
                    "{var} carries {owner}'s advice: {rendered}"
                );
            }
            // The environment is not a template token, so its advice offers
            // no template and the message must not grow one from elsewhere.
            assert_eq!(
                rendered.contains("{{"),
                fitting.contains("{{"),
                "{var} offers a template only if its own advice does: {rendered}"
            );
            assert!(
                !rendered.contains('\u{2014}') && !rendered.contains('\u{2013}'),
                "no em or en dash in copy a user reads: {rendered}"
            );
        }
    }

    #[test]
    fn valid_minimal_config_normalizes() {
        let resolved = normalize(AppConfig::minimal("web", "./srv")).unwrap();
        assert_eq!(resolved.config().name, "web");
    }

    #[test]
    fn names_that_reach_the_filesystem_are_rejected() {
        // A name becomes a log/pid file stem via Path::join; a slash-prefixed
        // or dotdot name would escape $SHEP_HOME. Reject at the config boundary.
        for bad in ["/etc/passwd", "..", ".", "a/b", "a\\b"] {
            assert_eq!(
                normalize(AppConfig::minimal(bad, "./srv")).unwrap_err(),
                NormalizeError::InvalidName(bad.to_string())
            );
        }
        assert!(normalize(AppConfig::minimal("web-1", "./srv")).is_ok());
    }

    #[test]
    fn missing_name_and_script_are_distinct_errors() {
        assert_eq!(
            normalize(AppConfig::minimal("", "./srv")).unwrap_err(),
            NormalizeError::MissingName
        );
        assert_eq!(
            normalize(AppConfig::minimal("web", "")).unwrap_err(),
            NormalizeError::MissingScript
        );
    }

    #[test]
    fn zero_instances_rejected() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.instances = 0;
        assert_eq!(normalize(app).unwrap_err(), NormalizeError::ZeroInstances);
    }

    #[test]
    fn bad_cron_pattern_rejected_with_pattern_and_reason_carried_through() {
        // fails if the reason is not carried through from croner.
        let mut app = AppConfig::minimal("web", "./srv");
        app.cron_restart = Some("not a cron".to_string());
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidCron { pattern, reason } => {
                assert_eq!(pattern, "not a cron");
                assert!(!reason.is_empty());
            }
            other => panic!("expected InvalidCron, got {other:?}"),
        }
    }

    #[test]
    fn five_tokens_of_garbage_cron_pattern_rejected() {
        // fails if the validator only counts whitespace-separated tokens
        // instead of checking each field's range: five numeric-looking
        // tokens, all out of range.
        let mut app = AppConfig::minimal("web", "./srv");
        app.cron_restart = Some("99 99 99 99 99".to_string());
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidCron { pattern, .. } => {
                assert_eq!(pattern, "99 99 99 99 99");
            }
            other => panic!("expected InvalidCron, got {other:?}"),
        }
    }

    #[test]
    fn bad_cron_timezone_rejected_alongside_a_valid_cron_restart() {
        // fails if the `cron_restart` branch maps CronParseError::Timezone to
        // anything but NormalizeError::InvalidTimezone. CronSchedule::parse
        // resolves the zone before the pattern, so a valid pattern paired
        // with a bad zone is the only input that reaches that arm.
        let mut app = AppConfig::minimal("web", "./srv");
        app.cron_restart = Some("0 3 * * *".to_string());
        app.cron_timezone = Some("Mars/Olympus".to_string());
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidTimezone { name } => assert_eq!(name, "Mars/Olympus"),
            other => panic!("expected InvalidTimezone, got {other:?}"),
        }
    }

    #[test]
    fn cron_timezone_validated_even_without_cron_restart() {
        // fails if timezone validation is skipped when there's no pattern to
        // pair it with: a Flockfile with only a bad `cron_timezone` is a
        // typo the user wants to hear about.
        let mut app = AppConfig::minimal("web", "./srv");
        app.cron_timezone = Some("Mars/Olympus".to_string());
        match normalize(app).unwrap_err() {
            NormalizeError::InvalidTimezone { name } => assert_eq!(name, "Mars/Olympus"),
            other => panic!("expected InvalidTimezone, got {other:?}"),
        }
    }

    #[test]
    fn duplicate_names_rejected_across_a_flock() {
        let apps = vec![
            AppConfig::minimal("web", "./a"),
            AppConfig::minimal("web", "./b"),
        ];
        assert_eq!(
            normalize_all(apps).unwrap_err(),
            NormalizeError::DuplicateName("web".to_string())
        );
    }

    #[test]
    fn a_cycle_inside_one_document_is_refused_and_named() {
        // fails if normalize_all accepts a cycle, or reports it without a path
        let mut a = AppConfig::minimal("a", "./a");
        a.depends_on = vec!["b".to_string()];
        let mut b = AppConfig::minimal("b", "./b");
        b.depends_on = vec!["a".to_string()];
        match normalize_all(vec![a, b]) {
            Err(NormalizeError::DependencyCycle(cycle)) => {
                let rendered = NormalizeError::DependencyCycle(cycle).to_string();
                assert!(rendered.contains("a"), "{rendered}");
                assert!(rendered.contains("b"), "{rendered}");
                assert!(
                    rendered.contains(" -> "),
                    "the path must be shown: {rendered}"
                );
            }
            other => panic!("expected DependencyCycle, got {other:?}"),
        }
    }

    #[test]
    fn a_dependency_on_an_app_outside_the_document_is_accepted() {
        // fails if the document-local check refuses a cross-repository
        // dependency, which would make depends_on unusable across Flockfiles
        let mut api = AppConfig::minimal("api", "./api");
        api.depends_on = vec!["db-in-another-repo".to_string()];
        normalize_all(vec![api]).expect("an unresolved name is not a document error");
    }

    #[test]
    fn zero_max_memory_rejected() {
        // fails if `max_memory` is never inspected: zero is a ceiling every
        // live process is already over, so the enforcer breaches on every
        // reading and the automatic restart that follows resets the
        // restart budget instead of spending it.
        let mut app = AppConfig::minimal("web", "./srv");
        app.max_memory = Some(crate::values::MemSize::from_bytes(0));
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::ZeroMaxMemory {
                name: "web".to_string()
            }
        );
        // fails if the message regresses to a bare variant name with no
        // explanation.
        assert!(err.to_string().contains("max_memory"), "{err}");
    }

    #[test]
    fn a_nonzero_max_memory_is_accepted() {
        // fails if the check fires on `max_memory` being set at all rather
        // than on its being zero: that would refuse every app that
        // configures a limit, which is the whole feature
        let mut app = AppConfig::minimal("web", "./srv");
        app.max_memory = Some("512M".parse().unwrap());
        assert!(normalize(app).is_ok());
    }

    /// fails if a `kill_signal` shep cannot send is accepted here: that puts
    /// SIGTERM on the wire for the life of the process with nothing but one
    /// daemon log line to say so.
    #[test]
    fn a_kill_signal_shep_cannot_send_is_refused_by_name() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.kill_signal = Some("SIGUSR1".to_string());

        let err = normalize(app).unwrap_err();

        assert_eq!(
            err,
            NormalizeError::InvalidKillSignal {
                name: "web".to_string(),
                value: "SIGUSR1".to_string(),
            }
        );
        // The message has to name the accepted set, because the operator's next
        // move is picking a different word and there is nowhere else to look.
        let rendered = err.to_string();
        assert!(rendered.contains("SIGUSR1"), "{rendered}");
        assert!(rendered.contains("SIGTERM"), "{rendered}");
        assert!(rendered.contains("SIGUSR2"), "{rendered}");
    }

    /// fails if the four supported names, their bare forms, or a lowercase
    /// spelling stop being accepted. This is the compatibility half: every
    /// spelling `stop_signal` accepted before this task must still normalize.
    #[test]
    fn every_spelling_the_daemon_already_accepted_still_normalizes() {
        for name in [
            "SIGTERM", "TERM", "sigterm", "term", "SIGINT", "INT", "SIGQUIT", "QUIT", "SIGUSR2",
            "USR2", "sigusr2",
        ] {
            let mut app = AppConfig::minimal("web", "./srv");
            app.kill_signal = Some(name.to_string());
            assert!(
                normalize(app).is_ok(),
                "`{name}` was accepted before this task and must still be"
            );
        }
    }

    /// fails if an unset `kill_signal` is refused: the overwhelmingly common
    /// case, and the one a validation pass is most likely to break by
    /// treating `None` as an empty string.
    #[test]
    fn an_unset_kill_signal_is_not_a_config_error() {
        let app = AppConfig::minimal("web", "./srv");
        assert!(app.kill_signal.is_none());
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn a_sheep_cannot_claim_the_all_environment() {
        // `all` is the store's every-environment slot. A sheep resolving in
        // it would read that slot twice and never its own.
        let mut app = AppConfig::minimal("web", "./srv");
        app.environment = Some("all".to_string());
        let err = normalize(app).unwrap_err();
        assert!(err.to_string().contains("all"), "{err}");
    }

    #[test]
    fn an_environment_outside_the_grammar_is_refused() {
        for bad in ["", "has space", "has/slash"] {
            let mut app = AppConfig::minimal("web", "./srv");
            app.environment = Some(bad.to_string());
            assert!(normalize(app).is_err(), "{bad:?} must be refused");
        }
    }

    #[test]
    fn action_timeout_past_the_ceiling_is_rejected() {
        // fails if `action_timeout` is never inspected. One millisecond over
        // the ceiling is deliberate: a test at a round number like 60s could
        // pass by coincidence if the check used the wrong constant entirely
        // (`MAX_DEADLINE_MS` itself, say, instead of the margin under it).
        let mut app = AppConfig::minimal("web", "./srv");
        app.action_timeout = UpDuration::from_millis(MAX_ACTION_TIMEOUT.as_millis() + 1);
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::ActionTimeoutTooLong {
                name: "web".to_string(),
                value: UpDuration::from_millis(MAX_ACTION_TIMEOUT.as_millis() + 1),
                max: MAX_ACTION_TIMEOUT,
            }
        );
        // fails if the message regresses to a bare variant name with no
        // explanation.
        assert!(err.to_string().contains("action_timeout"), "{err}");
    }

    #[test]
    fn action_timeout_at_the_ceiling_is_accepted() {
        // fails if the comparison is `>=` rather than `>`: the ceiling
        // itself still leaves the daemon its full margin under the hard
        // clamp, so it is not one of the values nothing could ever satisfy.
        let mut app = AppConfig::minimal("web", "./srv");
        app.action_timeout = MAX_ACTION_TIMEOUT;
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn the_default_action_timeout_is_accepted() {
        // fails if `AppConfig::default()`'s own value ever drifts past the
        // ceiling normalize enforces: the one combination that must never
        // reject the config nobody customized.
        assert!(normalize(AppConfig::minimal("web", "./srv")).is_ok());
    }

    #[test]
    fn zero_watch_delay_rejected() {
        // fails if `watch_delay` is never inspected. notify's debouncer
        // derives its poll tick as `watch_delay / 4` and sleeps it on its own
        // OS thread, so zero is `loop { sleep(0); lock(); }`, a CPU-spinning
        // busy loop.
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        app.cwd = Some("/srv/web".to_string());
        app.watch_delay = Some(UpDuration::from_millis(0));
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::ZeroWatchDelay {
                name: "web".to_string()
            }
        );
        // fails if the message regresses to a bare variant name with no
        // explanation.
        assert!(err.to_string().contains("watch_delay"), "{err}");
    }

    #[test]
    fn a_zero_watch_delay_is_rejected_with_watch_off() {
        // fails if the check is nested inside the `watch` block: an app
        // carrying `watch_delay = "0"` with `watch = false` would normalize
        // clean, and the spin would arrive the day someone flips `watch =
        // true`
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch_delay = Some(UpDuration::from_millis(0));
        assert!(matches!(
            normalize(app).unwrap_err(),
            NormalizeError::ZeroWatchDelay { .. }
        ));
    }

    #[test]
    fn a_nonzero_watch_delay_is_accepted() {
        // fails if the check fires on `watch_delay` being set at all rather
        // than on its being zero: that would refuse every app that tunes
        // its own debounce
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        app.cwd = Some("/srv/web".to_string());
        app.watch_delay = Some(UpDuration::from_millis(1));
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn watch_true_without_cwd_rejected_naming_the_app() {
        // fails if a validator never looks at `watch`, or looks at it but
        // carries no app name, leaving the user unable to tell which
        // Flockfile entry to edit
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::WatchWithoutCwd {
                name: "web".to_string()
            }
        );
        // fails if the message regresses to a bare variant name with no
        // explanation.
        assert!(err.to_string().contains("no cwd to watch"), "{err}");
    }

    #[test]
    fn watch_true_with_cwd_accepted() {
        // fails if the check fires on `watch` alone, ignoring that a cwd was
        // actually provided
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch = true;
        app.cwd = Some("/srv/web".to_string());
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn level_rules_survive_normalization_in_the_order_they_were_written() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.level_rules = vec![
            LevelRule {
                pattern: r"\[ERROR\]".to_string(),
                level: LineLevel::Error,
            },
            LevelRule {
                pattern: r"\[WARN\]".to_string(),
                level: LineLevel::Warn,
            },
        ];
        let resolved = normalize(app.clone()).unwrap();
        assert_eq!(resolved.config().level_rules, app.level_rules);
    }

    /// The whole reason patterns are compiled here: a Flockfile that reaches
    /// the shepherd with a pattern nobody can compile would fail at draw
    /// time, in a client, where the message reaches nobody.
    #[test]
    fn a_level_rule_pattern_that_will_not_compile_is_rejected() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.level_rules = vec![LevelRule {
            pattern: "[unclosed".to_string(),
            level: LineLevel::Error,
        }];
        let err = normalize(app).unwrap_err();
        let rendered = err.to_string();
        for expected in ["web", "[unclosed"] {
            assert!(
                rendered.contains(expected),
                "{expected} missing: {rendered}"
            );
        }
    }

    /// An empty pattern matches every line, so the rule would claim the feed
    /// and leave every rule after it dead.
    #[test]
    fn an_empty_level_rule_pattern_is_rejected() {
        let mut app = AppConfig::minimal("web", "./srv");
        app.level_rules = vec![LevelRule {
            pattern: String::new(),
            level: LineLevel::Warn,
        }];
        let err = normalize(app).unwrap_err();
        assert_eq!(
            err,
            NormalizeError::InvalidLevelRule {
                name: "web".to_string(),
                reason: LevelRuleError::EmptyPattern {
                    level: LineLevel::Warn
                }
                .to_string(),
            }
        );
    }

    #[test]
    fn watch_options_without_watch_or_cwd_accepted() {
        // fails if the check is keyed on `watch_options` being non-empty
        // rather than on `watch` being true: that would reject a Flockfile
        // that never asked to be watched
        let mut app = AppConfig::minimal("web", "./srv");
        app.watch_options = vec!["src/**".to_string()];
        assert!(normalize(app).is_ok());
    }

    #[test]
    fn a_sheep_that_depends_on_itself_is_refused_by_name() {
        // fails if the self-edge check is missing, or if it reports a bare
        // cycle rather than naming the sheep
        let mut app = AppConfig::minimal("api", "./api");
        app.depends_on = vec!["api".to_string()];
        match normalize(app) {
            Err(NormalizeError::SelfDependency(name)) => assert_eq!(name, "api"),
            other => panic!("expected SelfDependency, got {other:?}"),
        }
    }

    #[test]
    fn a_dependency_on_one_instance_is_refused_naming_the_app_form() {
        // fails if `name:slot` is accepted as a dependency target
        let mut app = AppConfig::minimal("api", "./api");
        app.depends_on = vec!["db:2".to_string()];
        match normalize(app) {
            Err(NormalizeError::InstanceDependency { sheep, target }) => {
                assert_eq!(sheep, "api");
                assert_eq!(target, "db:2");
            }
            other => panic!("expected InstanceDependency, got {other:?}"),
        }
        let rendered = NormalizeError::InstanceDependency {
            sheep: "api".to_string(),
            target: "db:2".to_string(),
        }
        .to_string();
        assert!(
            rendered.contains("`db`"),
            "the refusal must name the app-level form: {rendered}"
        );
    }

    #[test]
    fn duplicate_dependencies_dedupe_rather_than_refusing() {
        // fails if a repeated name is an error, or if it survives into the
        // normalized config twice
        let mut app = AppConfig::minimal("api", "./api");
        app.depends_on = vec!["db".to_string(), "db".to_string()];
        let resolved = normalize(app).expect("a repeated name is not an error");
        assert_eq!(resolved.config().depends_on, vec!["db".to_string()]);
    }

    #[test]
    fn an_ordinary_dependency_list_survives_normalize() {
        // fails if the field is dropped or reordered
        let mut app = AppConfig::minimal("api", "./api");
        app.depends_on = vec!["db".to_string(), "cache".to_string()];
        let resolved = normalize(app).expect("an ordinary list normalizes");
        assert_eq!(
            resolved.config().depends_on,
            vec!["db".to_string(), "cache".to_string()]
        );
    }
}