ferryman-core 0.2.3

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
//! 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::proxies::TrustedProxies;
use crate::route::{Route, RouteTable, Upstream};
use anyhow::{bail, Context};
use serde::Deserialize;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use std::time::Duration;

/// Top-level config file.
#[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,
    pub routes: Vec<RouteToml>,
}

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_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>,
}

/// 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.
pub fn load_config(path: &Path) -> anyhow::Result<ConfigToml> {
    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("reading config file {}", path.display()))?;
    toml::from_str(&raw).with_context(|| format!("parsing config file {}", path.display()))
}

/// 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.
pub fn build_table(cfg: ConfigToml, prev: Option<&RouteTable>) -> anyhow::Result<RouteTable> {
    if cfg.failure_threshold < 1 {
        bail!(
            "failure_threshold 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),
    ] {
        if v == 0 {
            bail!("{key} must be >= 1");
        }
        if v > MAX_SECS {
            bail!("{key} must be <= {MAX_SECS}, got {v}");
        }
    }
    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 validated = Vec::with_capacity(cfg.routes.len());

    for r in cfg.routes {
        if !r.prefix.starts_with('/') {
            bail!("route prefix {:?} must start with '/'", r.prefix);
        }
        if !seen_prefixes.insert(r.prefix.clone()) {
            bail!("duplicate route prefix {:?}", r.prefix);
        }

        let uri: http::Uri = r.upstream.parse().with_context(|| {
            format!(
                "route {:?}: invalid upstream URI {:?}",
                r.prefix, r.upstream
            )
        })?;

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

        let name = crate::route::upstream_name(&uri);
        let cooldown = r
            .cooldown_secs
            .map(Duration::from_secs)
            .unwrap_or(default_cooldown);
        if cooldown.is_zero() {
            bail!("route {:?}: cooldown_secs must be >= 1", r.prefix);
        }
        if cooldown.as_secs() > MAX_SECS {
            bail!(
                "route {:?}: cooldown_secs must be <= {MAX_SECS}, got {}",
                r.prefix,
                cooldown.as_secs()
            );
        }
        let first = *cooldown_by_name.entry(name.clone()).or_insert(cooldown);
        if first != cooldown {
            bail!(
                "route {:?}: upstream {name} is shared with another route but has a \
                 different cooldown ({}s vs {}s); routes to one upstream share one breaker",
                r.prefix,
                cooldown.as_secs(),
                first.as_secs()
            );
        }
        validated.push((r.prefix, uri, name, cooldown));
    }

    let mut upstreams_by_name: HashMap<String, Upstream> = HashMap::new();
    let routes = validated
        .into_iter()
        .map(|(prefix, uri, name, cooldown)| {
            let upstream = upstreams_by_name
                .entry(name)
                .or_insert_with_key(|name| match prev_by_name.get(name.as_str()) {
                    Some(prev_u) => prev_u.reuse(cooldown, cfg.failure_threshold),
                    None => Upstream::new(uri, cooldown, cfg.failure_threshold),
                })
                .clone();
            Route { prefix, upstream }
        })
        .collect();

    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_trusted_proxies(trusted_proxies))
}

#[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,
            routes,
        }
    }

    fn route(prefix: &str, upstream: &str) -> RouteToml {
        RouteToml {
            prefix: prefix.to_string(),
            upstream: upstream.to_string(),
            cooldown_secs: 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());
    }

    #[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) -> anyhow::Result<RouteTable> {
        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",
        ] {
            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 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",
        ] {
            assert!(parse(&format!("{key} = 0")).is_err());
        }
        let err = parse("trusted_proxies = [\"10.0.0.0/33\"]").err().unwrap();
        assert!(err.to_string().contains("10.0.0.0/33"), "{err}");
    }
}