ferryman-core 0.3.0

Lock-free circuit breaker, prefix routing table, hot-reloadable TOML config and active health checks for the ferryman reverse proxy.
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
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
//! TOML config schema + reload-time builder.
//!
//! `config.toml` is the authoritative source for routing rules. The reload
//! task in `crates/server/src/reload.rs` re-reads this file on filesystem
//! events, calls [`build_table`], and atomically swaps the result into the
//! `SharedTable`.

use crate::error::Error;
use crate::proxies::TrustedProxies;
use crate::route::{Route, RouteTable, Upstream};
use crate::BreakerConfig;
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::time::Duration;

/// Top-level config file.
///
/// Reserved: the top-level names `mtls`, `jwt`, `limits`, `tls` and
/// `tenant_rps` are never claimed by core; an embedding (ferryman-edge)
/// strips them before [`ConfigToml::from_table`]. Any other unknown key is
/// rejected.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct ConfigToml {
    /// Active health-check interval in seconds.
    #[serde(default = "default_health_interval")]
    pub health_interval_secs: u64,
    /// Default circuit-breaker cooldown if a route doesn't override.
    #[serde(default = "default_cooldown")]
    pub default_cooldown_secs: u64,
    /// Consecutive failures before a closed circuit opens. Must be >= 1.
    #[serde(default = "default_failure_threshold")]
    pub failure_threshold: u32,
    /// Timeout for a forwarded request to an upstream, in seconds.
    #[serde(default = "default_upstream_timeout")]
    pub upstream_timeout_secs: u64,
    /// HTTP/1 keep-alive idle timeout in seconds (1..=86400).
    #[serde(default = "default_keepalive_timeout")]
    pub keepalive_timeout_secs: u64,
    /// CIDR ranges (or bare IPs) of proxies whose forwarding headers are trusted.
    #[serde(default)]
    pub trusted_proxies: Vec<String>,
    /// Longest gap between request-body frames, in seconds (1..=86400).
    #[serde(default = "default_body_idle_timeout")]
    pub request_body_idle_timeout_secs: u64,
    /// Total time allowed to receive a request body, in seconds (1..=86400).
    /// Not required to be >= the idle timeout; whichever fires first wins.
    #[serde(default = "default_body_timeout")]
    pub request_body_timeout_secs: u64,
    /// Path the proxy itself answers with `200 ok` on `GET`/`HEAD`, for
    /// platforms that only probe the serving port. Absolute, no query or
    /// fragment; must not equal a route prefix. Shadows any route prefix it
    /// falls under. Default: none.
    #[serde(default)]
    pub local_health_path: Option<String>,
    /// On shutdown, how long to wait for in-flight connections after the
    /// listener closes, in seconds (1..=86400). Default 25.
    #[serde(default = "default_drain_timeout")]
    pub drain_timeout_secs: u64,
    /// On shutdown, how long to keep serving with `/readyz` at 503 before
    /// the listener closes, in seconds (0..=86400). Default 0.
    #[serde(default)]
    pub shutdown_delay_secs: u64,
    /// Also emit an RFC 7239 `Forwarded` element (`for`, `proto`, `host`).
    /// Default false.
    #[serde(default)]
    pub forwarded_header: bool,
    /// How `X-Forwarded-For` is built: `"append"` (default) adds the peer to
    /// the incoming list; `"replace"` sets it to the single client address
    /// that goes into `X-Real-IP`.
    #[serde(default)]
    pub xff: XffMode,
    /// Emit one `ferryman::access` log line per request. Default false.
    #[serde(default)]
    pub access_log: bool,
    /// Generate `x-request-id` when absent (and replace invalid ones), set it
    /// on the upstream request and the response. Default false.
    #[serde(default)]
    pub request_id: bool,
    pub routes: Vec<RouteToml>,
}

/// `xff` config key: how the upstream-bound `X-Forwarded-For` is built.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum XffMode {
    /// Append the peer address to the incoming list.
    #[default]
    Append,
    /// Replace the list with the client address (as in `X-Real-IP`).
    Replace,
}

fn default_health_interval() -> u64 {
    5
}
fn default_cooldown() -> u64 {
    30
}
fn default_failure_threshold() -> u32 {
    3
}
fn default_upstream_timeout() -> u64 {
    30
}
pub(crate) const DEFAULT_KEEPALIVE_SECS: u64 = 10;
pub(crate) const DEFAULT_DRAIN_SECS: u64 = 25;
fn default_drain_timeout() -> u64 {
    DEFAULT_DRAIN_SECS
}
pub(crate) const DEFAULT_BODY_IDLE_SECS: u64 = 30;
pub(crate) const DEFAULT_BODY_TOTAL_SECS: u64 = 300;
fn default_body_timeout() -> u64 {
    DEFAULT_BODY_TOTAL_SECS
}
fn default_keepalive_timeout() -> u64 {
    DEFAULT_KEEPALIVE_SECS
}
fn default_body_idle_timeout() -> u64 {
    DEFAULT_BODY_IDLE_SECS
}

/// Upper bound for every duration key, so `Duration` arithmetic can't overflow.
const MAX_SECS: u64 = 86_400;

/// One routing rule.
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
#[non_exhaustive]
pub struct RouteToml {
    /// Path prefix to match (e.g. `/svc-a`).
    pub prefix: String,
    /// Upstream URI, e.g. `http://localhost:8001`.
    pub upstream: String,
    /// Per-route circuit-breaker cooldown override.
    #[serde(default)]
    pub cooldown_secs: Option<u64>,
    /// Active health-probe path; absolute, no query or fragment. Default
    /// `/health`. Routes sharing an upstream must agree.
    #[serde(default)]
    pub health_path: Option<String>,
    /// Skip active health probing for this route's upstream (default
    /// `false`); only request traffic then drives its breaker. Routes
    /// sharing an upstream must agree.
    #[serde(default)]
    pub health_disabled: bool,
    /// Send the upstream's `host[:port]` as `Host` instead of the client's
    /// (default `false`). Routes sharing an upstream may differ.
    #[serde(default)]
    pub rewrite_host: bool,
    /// Remove the matched prefix from the path sent upstream (default
    /// `false`) and set `X-Forwarded-Prefix` to it. The forwarded path is
    /// then the normalised one.
    #[serde(default)]
    pub strip_prefix: bool,
}

/// Read and parse the TOML config at `path`. Shared by the server's initial
/// boot and its hot-reload watcher so both get the same error context.
///
/// # Errors
///
/// [`Error::ReadConfig`] if the file can't be read, [`Error::Toml`] if it
/// doesn't parse (both carry the cause as `source()`).
pub fn load_config(path: &Path) -> Result<ConfigToml, Error> {
    let raw = std::fs::read_to_string(path).map_err(|source| Error::ReadConfig {
        path: path.to_path_buf(),
        source,
    })?;
    raw.parse().map_err(|e| match e {
        Error::Toml { source, .. } => Error::Toml {
            path: Some(path.to_path_buf()),
            source,
        },
        e => e,
    })
}

impl std::str::FromStr for ConfigToml {
    type Err = Error;

    /// Parse config text (no file context: [`Error::Toml`] has `path: None`).
    fn from_str(s: &str) -> Result<Self, Error> {
        toml::from_str(s).map_err(|source| Error::Toml { path: None, source })
    }
}

impl ConfigToml {
    /// Build a config from an already-parsed TOML table (two-pass parse: the
    /// caller removes the keys it owns first). `deny_unknown_fields` applies
    /// to whatever remains.
    ///
    /// Core never claims the top-level names `mtls`, `jwt`, `limits`, `tls`
    /// and `tenant_rps`; they are reserved for ferryman-edge, which strips
    /// them before calling this.
    ///
    /// # Errors
    ///
    /// [`Error::Toml`] (with `path: None`) on unknown keys or wrong types.
    pub fn from_table(table: toml::Table) -> Result<Self, Error> {
        table
            .try_into()
            .map_err(|source| Error::Toml { path: None, source })
    }
}

/// Build a [`RouteTable`] from a parsed [`ConfigToml`], validating routes
/// and upstream URIs. If `prev` is given, upstreams that also existed in it
/// (matched by `host:port` name) share its circuit breaker, so a hot reload
/// neither resets an open circuit nor strands results from in-flight
/// requests on an orphaned breaker. Fails without side effects.
///
/// # Errors
///
/// [`Error::InvalidConfig`] (out-of-range top-level key),
/// [`Error::InvalidCidr`] (`trusted_proxies`), [`Error::InvalidPrefix`],
/// [`Error::NonCanonicalPrefix`],
/// [`Error::DuplicatePrefix`], [`Error::InvalidUpstream`],
/// [`Error::InvalidCooldown`], [`Error::ConflictingCooldown`],
/// [`Error::InvalidHealthPath`], [`Error::ConflictingHealth`] and
/// [`Error::InvalidBreakerConfig`].
pub fn build_table(cfg: ConfigToml, prev: Option<&RouteTable>) -> Result<RouteTable, Error> {
    if cfg.failure_threshold < 1 {
        return Err(Error::InvalidConfig {
            key: "failure_threshold",
            reason: format!("must be >= 1, got {}", cfg.failure_threshold),
        });
    }
    for (key, v) in [
        ("health_interval_secs", cfg.health_interval_secs),
        ("upstream_timeout_secs", cfg.upstream_timeout_secs),
        ("default_cooldown_secs", cfg.default_cooldown_secs),
        ("keepalive_timeout_secs", cfg.keepalive_timeout_secs),
        (
            "request_body_idle_timeout_secs",
            cfg.request_body_idle_timeout_secs,
        ),
        ("request_body_timeout_secs", cfg.request_body_timeout_secs),
        ("drain_timeout_secs", cfg.drain_timeout_secs),
    ] {
        if v == 0 {
            return Err(Error::InvalidConfig {
                key,
                reason: "must be >= 1".into(),
            });
        }
        if v > MAX_SECS {
            return Err(Error::InvalidConfig {
                key,
                reason: format!("must be <= {MAX_SECS}, got {v}"),
            });
        }
    }
    if cfg.shutdown_delay_secs > MAX_SECS {
        return Err(Error::InvalidConfig {
            key: "shutdown_delay_secs",
            reason: format!("must be <= {MAX_SECS}, got {}", cfg.shutdown_delay_secs),
        });
    }
    if let Some(p) = &cfg.local_health_path {
        if !(p.starts_with('/')
            && !p.contains(['?', '#'])
            && p.parse::<http::uri::PathAndQuery>().is_ok())
        {
            return Err(Error::InvalidConfig {
                key: "local_health_path",
                reason: format!("{p:?} must start with '/' and contain no '?' or '#'"),
            });
        }
        if crate::path::bad_path(p) {
            return Err(Error::InvalidConfig {
                key: "local_health_path",
                reason: format!("{p:?} is not an acceptable request path"),
            });
        }
        if let Some(r) = cfg.routes.iter().find(|r| &r.prefix == p) {
            return Err(Error::InvalidConfig {
                key: "local_health_path",
                reason: format!(
                    "{p:?} equals the prefix of route {:?} and would shadow it",
                    r.prefix
                ),
            });
        }
    }
    let trusted_proxies = TrustedProxies::parse(&cfg.trusted_proxies)?;

    let default_cooldown = Duration::from_secs(cfg.default_cooldown_secs);
    let upstream_timeout = Duration::from_secs(cfg.upstream_timeout_secs);

    let prev_by_name: HashMap<&str, &Upstream> = prev
        .map(|t| t.upstreams().map(|u| (u.name.as_str(), u)).collect())
        .unwrap_or_default();

    // Validate everything first so a rejected reload never touches the
    // breakers the live table is still using.
    let mut seen_prefixes = HashSet::new();
    let mut cooldown_by_name: HashMap<String, Duration> = HashMap::new();
    let mut health_by_name: HashMap<String, (String, bool)> = HashMap::new();
    let mut validated = Vec::with_capacity(cfg.routes.len());

    for r in cfg.routes {
        if !r.prefix.starts_with('/') {
            return Err(Error::InvalidPrefix { prefix: r.prefix });
        }
        let normal = crate::route::normalize(&r.prefix);
        if !r.prefix.is_ascii() || normal != r.prefix {
            let normal = if r.prefix.is_ascii() {
                normal.into_owned()
            } else {
                "ASCII only (percent-encode non-ASCII bytes)".to_string()
            };
            return Err(Error::NonCanonicalPrefix {
                prefix: r.prefix,
                normal,
            });
        }
        if r.prefix.contains([';', '\\']) || {
            let u = r.prefix.to_ascii_uppercase();
            u.contains("%2F") || u.contains("%5C")
        } {
            return Err(Error::NonCanonicalPrefix {
                prefix: r.prefix,
                normal: "prefixes may not contain ';', '\\', %2F or %5C (such requests are rejected as ambiguous)".to_string(),
            });
        }
        if !seen_prefixes.insert(r.prefix.clone()) {
            return Err(Error::DuplicatePrefix { prefix: r.prefix });
        }

        let bad = |reason: String, source| Error::InvalidUpstream {
            route: r.prefix.clone(),
            upstream: r.upstream.clone(),
            reason,
            source,
        };
        let uri: http::Uri = r
            .upstream
            .parse()
            .map_err(|e| bad(format!("invalid upstream URI {:?}", r.upstream), Some(e)))?;

        match uri.scheme_str() {
            Some("http") => {}
            Some(other) => {
                return Err(bad(
                    format!(
                        "upstream {:?} has scheme {:?} — https upstreams are not supported",
                        r.upstream, other
                    ),
                    None,
                ))
            }
            None => {
                return Err(bad(
                    format!(
                        "upstream {:?} has no scheme (expected e.g. http://host:port)",
                        r.upstream
                    ),
                    None,
                ))
            }
        }
        // Also catches an empty IPv6 literal (`http://[]:80`).
        if uri
            .host()
            .is_none_or(|h| h.trim_matches(['[', ']']).is_empty())
        {
            return Err(bad(format!("upstream {:?} has no host", r.upstream), None));
        }
        if let Some(pq) = uri.path_and_query() {
            if pq.query().is_some() {
                return Err(bad(
                    format!("upstream {:?} must not include a query string", r.upstream),
                    None,
                ));
            }
            if !pq.path().is_empty() && pq.path() != "/" {
                return Err(bad(
                    format!(
                        "upstream {:?} must not include a path (got {:?})",
                        r.upstream,
                        pq.path()
                    ),
                    None,
                ));
            }
        }

        let name = crate::route::upstream_name(&uri);
        let cooldown = r
            .cooldown_secs
            .map(Duration::from_secs)
            .unwrap_or(default_cooldown);
        if cooldown.is_zero() {
            return Err(Error::InvalidCooldown {
                route: r.prefix,
                reason: "must be >= 1".into(),
            });
        }
        if cooldown.as_secs() > MAX_SECS {
            return Err(Error::InvalidCooldown {
                route: r.prefix,
                reason: format!("must be <= {MAX_SECS}, got {}", cooldown.as_secs()),
            });
        }
        // Validate the breaker config here, before `prev` is touched, so the
        // `Upstream::new` below cannot fail.
        let breaker = BreakerConfig::default()
            .with_cooldown(cooldown)
            .with_failure_threshold(cfg.failure_threshold);
        breaker.validate().map_err(|e| match e {
            Error::InvalidBreakerConfig { reason, .. } => Error::InvalidBreakerConfig {
                reason,
                upstream: Some(name.clone()),
            },
            e => e,
        })?;
        let first = *cooldown_by_name.entry(name.clone()).or_insert(cooldown);
        if first != cooldown {
            return Err(Error::ConflictingCooldown {
                route: r.prefix,
                upstream: name,
                cooldown_secs: cooldown.as_secs(),
                other_secs: first.as_secs(),
            });
        }
        if let Some(p) = &r.health_path {
            if !(p.starts_with('/')
                && !p.contains(['?', '#'])
                && p.parse::<http::uri::PathAndQuery>().is_ok())
            {
                return Err(Error::InvalidHealthPath {
                    route: r.prefix,
                    path: p.clone(),
                });
            }
        }
        let health = (
            r.health_path.unwrap_or_else(|| "/health".to_string()),
            r.health_disabled,
        );
        let first = health_by_name
            .entry(name.clone())
            .or_insert_with(|| health.clone());
        let conflict = if first.0 != health.0 {
            Some(("health_path", health.0.clone(), first.0.clone()))
        } else if first.1 != health.1 {
            Some(("health_disabled", health.1.to_string(), first.1.to_string()))
        } else {
            None
        };
        if let Some((setting, value, other)) = conflict {
            return Err(Error::ConflictingHealth {
                route: r.prefix,
                upstream: name,
                setting,
                value,
                other,
            });
        }
        validated.push((
            r.prefix,
            uri,
            name,
            cooldown,
            breaker,
            health,
            (r.rewrite_host, r.strip_prefix),
        ));
    }

    let mut upstreams_by_name: HashMap<String, Upstream> = HashMap::new();
    let mut routes = Vec::with_capacity(validated.len());
    for (
        prefix,
        uri,
        name,
        cooldown,
        breaker,
        (health_path, health_disabled),
        (rewrite_host, strip_prefix),
    ) in validated
    {
        let upstream = match upstreams_by_name.get(&name) {
            Some(u) => u.clone(),
            None => {
                let health_path = Some(health_path);
                let u = match prev_by_name.get(name.as_str()) {
                    // Breaker (and its state) is kept; health settings are
                    // simply replaced on the new table's Upstream.
                    Some(prev_u) => prev_u.reuse(
                        cooldown,
                        cfg.failure_threshold,
                        health_path,
                        health_disabled,
                    ),
                    None => Upstream::new(uri, breaker)?.with_health(health_path, health_disabled),
                };
                upstreams_by_name.insert(name, u.clone());
                u
            }
        };
        routes.push(
            Route::new(prefix, upstream)
                .with_rewrite_host(rewrite_host)
                .with_strip_prefix(strip_prefix),
        );
    }

    Ok(RouteTable::new(routes, upstream_timeout)
        .with_keepalive_timeout(Duration::from_secs(cfg.keepalive_timeout_secs))
        .with_request_body_idle_timeout(Duration::from_secs(cfg.request_body_idle_timeout_secs))
        .with_request_body_timeout(Duration::from_secs(cfg.request_body_timeout_secs))
        .with_drain_timeout(Duration::from_secs(cfg.drain_timeout_secs))
        .with_shutdown_delay(Duration::from_secs(cfg.shutdown_delay_secs))
        .with_trusted_proxies(trusted_proxies)
        .with_forwarded_header(cfg.forwarded_header)
        .with_xff_mode(cfg.xff)
        .with_access_log(cfg.access_log)
        .with_request_id(cfg.request_id)
        .with_local_health_path(cfg.local_health_path))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::route::{Admission, CircuitState};

    fn cfg(routes: Vec<RouteToml>) -> ConfigToml {
        ConfigToml {
            health_interval_secs: 5,
            default_cooldown_secs: 30,
            failure_threshold: 3,
            upstream_timeout_secs: 30,
            keepalive_timeout_secs: 10,
            trusted_proxies: Vec::new(),
            request_body_idle_timeout_secs: 30,
            request_body_timeout_secs: 300,
            local_health_path: None,
            drain_timeout_secs: 25,
            shutdown_delay_secs: 0,
            forwarded_header: false,
            xff: XffMode::Append,
            access_log: false,
            request_id: false,
            routes,
        }
    }

    #[test]
    fn log_keys_default_and_parse() {
        let t = build_table(cfg(vec![route("/a", "http://h:1")]), None).unwrap();
        assert!(!t.access_log() && !t.request_id());
        let c: ConfigToml = "access_log = true\nrequest_id = true\n[[routes]]\nprefix = \"/\"\nupstream = \"http://h:1\"\n"
            .parse()
            .unwrap();
        let t = build_table(c, None).unwrap();
        assert!(t.access_log() && t.request_id());
    }

    #[test]
    fn non_normal_prefixes_are_rejected() {
        for p in ["/%61dmin", "/a%2fb", "/x//y", "/中"] {
            let r = build_table(cfg(vec![route(p, "http://h:1")]), None);
            assert!(matches!(r, Err(Error::NonCanonicalPrefix { .. })), "{p}");
        }
        for p in ["/a%2Fb", "/a%5Cb", "/a;b", "/a\\b"] {
            let r = build_table(cfg(vec![route(p, "http://h:1")]), None);
            assert!(matches!(r, Err(Error::NonCanonicalPrefix { .. })), "{p}");
        }
    }

    fn route(prefix: &str, upstream: &str) -> RouteToml {
        RouteToml {
            prefix: prefix.to_string(),
            upstream: upstream.to_string(),
            cooldown_secs: None,
            health_path: None,
            health_disabled: false,
            rewrite_host: false,
            strip_prefix: false,
        }
    }

    #[test]
    fn local_health_path_validation() {
        for bad in ["healthz", "/h?x=1", "/h#f", "/svc-a", "/a/../b", "/a%00"] {
            let mut c = cfg(vec![route("/svc-a", "http://h:1")]);
            c.local_health_path = Some(bad.into());
            assert!(
                matches!(
                    build_table(c, None),
                    Err(Error::InvalidConfig {
                        key: "local_health_path",
                        ..
                    })
                ),
                "{bad}"
            );
        }
        let mut c = cfg(vec![route("/svc-a", "http://h:1")]);
        c.local_health_path = Some("/up".into());
        assert_eq!(
            build_table(c, None).unwrap().local_health_path(),
            Some("/up")
        );
        let c = cfg(vec![route("/svc-a", "http://h:1")]);
        assert_eq!(build_table(c, None).unwrap().local_health_path(), None);
    }

    #[test]
    fn rejects_prefix_without_leading_slash() {
        let c = cfg(vec![route("svc-a", "http://localhost:8001")]);
        assert!(build_table(c, None).is_err());
    }

    #[test]
    fn rejects_https_upstream() {
        let c = cfg(vec![route("/svc-a", "https://localhost:8001")]);
        let err = build_table(c, None).err().expect("should reject https");
        assert!(err.to_string().contains("https"), "{err}");
    }

    #[test]
    fn rejects_duplicate_prefix() {
        let c = cfg(vec![
            route("/svc-a", "http://localhost:8001"),
            route("/svc-a", "http://localhost:8002"),
        ]);
        assert!(build_table(c, None).is_err());
    }

    #[test]
    fn rejects_upstream_with_path() {
        let c = cfg(vec![route("/svc-a", "http://localhost:8001/api")]);
        assert!(build_table(c, None).is_err());
    }

    #[test]
    fn rejects_upstream_with_query() {
        let c = cfg(vec![route("/svc-a", "http://localhost:8001/?x=1")]);
        assert!(build_table(c, None).is_err());
    }

    #[test]
    fn rejects_zero_failure_threshold() {
        let mut c = cfg(vec![route("/svc-a", "http://localhost:8001")]);
        c.failure_threshold = 0;
        assert!(build_table(c, None).is_err());
    }

    #[test]
    fn accepts_valid_config() {
        let c = cfg(vec![
            route("/svc-a", "http://localhost:8001"),
            route("/svc-b", "http://localhost:8002"),
        ]);
        let t = build_table(c, None).unwrap();
        assert!(t.lookup("/svc-a").is_some());
        assert_eq!(t.upstreams().count(), 2);
    }

    #[test]
    fn reload_preserves_open_circuit() {
        let c = cfg(vec![route("/svc-a", "http://localhost:8001")]);
        let old = build_table(c.clone(), None).unwrap();
        let up = old.upstreams().next().unwrap();
        for _ in 0..3 {
            up.record_failure(Admission::Normal);
        }
        assert_eq!(up.state(), crate::route::CircuitState::Open);

        let new = build_table(c, Some(&old)).unwrap();
        let new_up = new.upstreams().next().unwrap();
        assert_eq!(new_up.state(), CircuitState::Open);

        // Same breaker, not a copy: a probe result landing on the old
        // table's upstream is visible through the new table.
        up.record_success(Admission::Probe);
        assert_eq!(new_up.state(), CircuitState::Closed);
    }

    #[test]
    fn failed_reload_leaves_prev_breakers_untouched() {
        let mut c = cfg(vec![route("/svc-a", "http://localhost:8001")]);
        c.default_cooldown_secs = 1000;
        let old = build_table(c.clone(), None).unwrap();
        let up = old.upstreams().next().unwrap();
        for _ in 0..3 {
            up.record_failure(Admission::Normal);
        }

        // Would shrink the cooldown, but the second route is invalid.
        c.default_cooldown_secs = 1;
        c.routes.push(route("nope", "http://localhost:8002"));
        assert!(build_table(c, Some(&old)).is_err());
        assert_eq!(up.try_acquire(), None, "cooldown must still be 1000s");
    }

    #[test]
    fn rejects_zero_durations() {
        for field in [
            "health_interval_secs",
            "upstream_timeout_secs",
            "default_cooldown_secs",
        ] {
            let raw =
                format!("{field} = 0\n[[routes]]\nprefix = \"/a\"\nupstream = \"http://h:1\"\n");
            let c: ConfigToml = toml::from_str(&raw).unwrap();
            let err = build_table(c, None).err().expect(field);
            assert!(format!("{err}").contains(field), "{err}");
        }
        let mut r = route("/a", "http://h:1");
        r.cooldown_secs = Some(0);
        assert!(build_table(cfg(vec![r]), None).is_err());
    }

    #[test]
    fn rejects_unknown_fields() {
        let raw = "failure_treshold = 1\nroutes = []\n";
        assert!(toml::from_str::<ConfigToml>(raw).is_err());
        let raw = "[[routes]]\nprefix = \"/a\"\nupstream = \"http://h:1\"\ncooldown_sec = 5\n";
        assert!(toml::from_str::<ConfigToml>(raw).is_err());
    }

    const MIN: &str = "[[routes]]\nprefix = \"/a\"\nupstream = \"http://h:1\"\n";

    #[test]
    fn from_table_rejects_unknown_and_accepts_stripped_edge_keys() {
        let mut t: toml::Table = format!("failure_treshold = 1\n{MIN}").parse().unwrap();
        let e = ConfigToml::from_table(t.clone()).unwrap_err();
        assert!(matches!(e, Error::Toml { path: None, .. }), "{e}");
        t.remove("failure_treshold");
        t.insert("tenant_rps".into(), 5.into());
        t.insert("jwt".into(), toml::Table::new().into());
        t.insert("limits".into(), toml::Table::new().into());
        assert!(ConfigToml::from_table(t.clone()).is_err());
        for k in ["tenant_rps", "jwt", "limits"] {
            t.remove(k);
        }
        assert_eq!(ConfigToml::from_table(t).unwrap().routes.len(), 1);
    }

    #[test]
    fn from_str_matches_load_config_and_has_no_path() {
        let p = std::env::temp_dir().join(format!("ferryman-a4-{}.toml", std::process::id()));
        let raw = format!("failure_threshold = 7\n{MIN}");
        std::fs::write(&p, &raw).unwrap();
        let a = load_config(&p).unwrap();
        let b: ConfigToml = raw.parse().unwrap();
        assert_eq!(format!("{a:?}"), format!("{b:?}"));
        std::fs::write(&p, "routes = 3").unwrap();
        let Error::Toml { path, .. } = load_config(&p).unwrap_err() else {
            panic!()
        };
        assert_eq!(path.as_deref(), Some(p.as_path()));
        std::fs::remove_file(&p).ok();
        let e = "routes = 3".parse::<ConfigToml>().unwrap_err();
        assert!(matches!(&e, Error::Toml { path: None, .. }));
        assert_eq!(e.to_string(), "parsing config");
    }

    #[test]
    fn rejects_conflicting_cooldowns_for_shared_upstream() {
        let mut b = route("/b", "http://localhost:8001");
        b.cooldown_secs = Some(5);
        let c = cfg(vec![route("/a", "http://localhost:8001"), b]);
        let err = build_table(c, None).err().expect("conflict");
        assert!(format!("{err}").contains("different cooldown"), "{err}");
    }

    #[test]
    fn reload_shares_state_across_routes_with_same_upstream() {
        let c = cfg(vec![
            route("/svc-a", "http://localhost:8001"),
            route("/svc-a-v2", "http://localhost:8001"),
        ]);
        let t = build_table(c, None).unwrap();
        assert_eq!(t.upstreams().count(), 1);
    }

    fn parse(extra: &str) -> Result<RouteTable, Error> {
        let raw = format!("{extra}\n[[routes]]\nprefix = \"/a\"\nupstream = \"http://h:1\"\n");
        build_table(toml::from_str(&raw).unwrap(), None)
    }

    #[test]
    fn rejects_empty_upstream_host() {
        for up in ["http://:80", "http://", "http://[]:80", "http://@:80"] {
            let err = build_table(cfg(vec![route("/a", up)]), None)
                .err()
                .expect(up);
            assert!(
                err.to_string().contains("no host") || err.to_string().contains("invalid"),
                "{err}"
            );
        }
        let err = build_table(cfg(vec![route("/a", "http://:80")]), None)
            .err()
            .unwrap();
        assert!(err.to_string().contains("has no host"), "{err}");
    }

    #[test]
    fn rejects_durations_above_one_day() {
        for key in [
            "health_interval_secs",
            "upstream_timeout_secs",
            "default_cooldown_secs",
            "keepalive_timeout_secs",
            "request_body_idle_timeout_secs",
            "request_body_timeout_secs",
            "drain_timeout_secs",
            "shutdown_delay_secs",
        ] {
            assert!(parse(&format!("{key} = 86400")).is_ok(), "{key} at bound");
            let err = parse(&format!("{key} = 86401")).err().expect(key);
            assert!(err.to_string().contains(key), "{err}");
            assert!(parse(&format!("{key} = 9223372036854775807")).is_err());
        }
        let mut r = route("/a", "http://h:1");
        r.cooldown_secs = Some(86_401);
        let err = build_table(cfg(vec![r]), None).err().unwrap();
        assert!(err.to_string().contains("cooldown_secs"), "{err}");
    }

    #[test]
    fn forwarding_keys_parse() {
        let t = parse("").unwrap();
        assert!(!t.forwarded_header());
        assert_eq!(t.xff_mode(), XffMode::Append);
        let t = parse("forwarded_header = true\nxff = \"replace\"").unwrap();
        assert!(t.forwarded_header());
        assert_eq!(t.xff_mode(), XffMode::Replace);
        assert!(toml::from_str::<ConfigToml>("xff = \"nope\"\nroutes = []").is_err());
    }

    #[test]
    fn new_keys_default_and_parse() {
        let t = parse("").unwrap();
        assert_eq!(t.keepalive_timeout(), Duration::from_secs(10));
        assert_eq!(t.request_body_idle_timeout(), Duration::from_secs(30));
        assert_eq!(t.request_body_timeout(), Duration::from_secs(300));
        assert!(t.trusted_proxies().is_empty());

        let t = parse(
            "keepalive_timeout_secs = 75\nrequest_body_idle_timeout_secs = 5\n\
             trusted_proxies = [\"10.0.0.0/8\", \"fd00::/8\"]",
        )
        .unwrap();
        assert_eq!(t.keepalive_timeout(), Duration::from_secs(75));
        assert_eq!(t.request_body_idle_timeout(), Duration::from_secs(5));
        assert!(t
            .trusted_proxies()
            .contains("::ffff:10.1.1.1".parse().unwrap()));
    }

    #[test]
    fn rejects_zero_new_keys_and_bad_cidr() {
        for key in [
            "keepalive_timeout_secs",
            "request_body_idle_timeout_secs",
            "request_body_timeout_secs",
            "drain_timeout_secs",
        ] {
            assert!(parse(&format!("{key} = 0")).is_err());
        }
        assert!(parse("shutdown_delay_secs = 0").is_ok());
        let t = parse("").unwrap();
        assert_eq!(t.drain_timeout(), Duration::from_secs(25));
        assert_eq!(t.shutdown_delay(), Duration::ZERO);
        let t = parse("drain_timeout_secs = 8\nshutdown_delay_secs = 3").unwrap();
        assert_eq!(t.drain_timeout(), Duration::from_secs(8));
        assert_eq!(t.shutdown_delay(), Duration::from_secs(3));
        let err = parse("trusted_proxies = [\"10.0.0.0/33\"]").err().unwrap();
        assert!(err.to_string().contains("10.0.0.0/33"), "{err}");
    }

    #[test]
    fn health_keys_default_and_parse() {
        let t = parse("").unwrap();
        let u = t.lookup("/a").unwrap().upstream.clone();
        assert_eq!((u.health_path(), u.health_disabled()), ("/health", false));

        let raw = "[[routes]]\nprefix = \"/a\"\nupstream = \"http://h:1\"\n\
                   health_path = \"/ready\"\nhealth_disabled = true\n";
        let t = build_table(toml::from_str(raw).unwrap(), None).unwrap();
        let u = &t.lookup("/a").unwrap().upstream;
        assert_eq!((u.health_path(), u.health_disabled()), ("/ready", true));
    }

    #[test]
    fn rejects_bad_health_path() {
        for bad in ["healthz", "", "/h?x=1", "/h#f", "/a b", "/a\u{1}b"] {
            let mut r = route("/a", "http://h:1");
            r.health_path = Some(bad.to_string());
            let r = build_table(cfg(vec![r]), None);
            assert!(
                matches!(r, Err(Error::InvalidHealthPath { .. })),
                "{bad:?}: {:?}",
                r.err()
            );
        }
    }

    #[test]
    fn rejects_conflicting_health_for_shared_upstream() {
        let mut b = route("/b", "http://localhost:8001");
        b.health_path = Some("/ready".into());
        let c = cfg(vec![route("/a", "http://localhost:8001"), b]);
        let err = build_table(c, None).err().expect("conflict");
        assert!(
            matches!(&err, Error::ConflictingHealth { route, setting: "health_path", .. } if route == "/b"),
            "{err}"
        );

        let mut b = route("/b", "http://localhost:8001");
        b.health_disabled = true;
        let c = cfg(vec![route("/a", "http://localhost:8001"), b]);
        assert!(matches!(
            build_table(c, None).err(),
            Some(Error::ConflictingHealth {
                setting: "health_disabled",
                ..
            })
        ));

        // Explicit default equals implicit default: no conflict.
        let mut b = route("/b", "http://localhost:8001");
        b.health_path = Some("/health".into());
        let c = cfg(vec![route("/a", "http://localhost:8001"), b]);
        assert!(build_table(c, None).is_ok());
    }

    #[test]
    fn reload_changing_health_keeps_breaker_state() {
        let c = cfg(vec![route("/a", "http://localhost:8001")]);
        let old = build_table(c.clone(), None).unwrap();
        let up = old.upstreams().next().unwrap();
        for _ in 0..3 {
            up.record_failure(Admission::Normal);
        }
        assert_eq!(up.state(), CircuitState::Open);

        let mut r = route("/a", "http://localhost:8001");
        r.health_path = Some("/ready".into());
        r.health_disabled = true;
        let new = build_table(cfg(vec![r]), Some(&old)).unwrap();
        let new_up = new.upstreams().next().unwrap();
        assert_eq!(new_up.state(), CircuitState::Open, "state must survive");
        assert_eq!(
            (new_up.health_path(), new_up.health_disabled()),
            ("/ready", true)
        );
        // Old table keeps its own settings; breaker is still shared.
        assert_eq!((up.health_path(), up.health_disabled()), ("/health", false));
        up.record_success(Admission::Probe);
        assert_eq!(new_up.state(), CircuitState::Closed);
    }
}