pub use crate::breaker::{Admission, CircuitState};
use crate::breaker::{Breaker, BreakerConfig};
use crate::proxies::TrustedProxies;
use crate::Error;
use arc_swap::ArcSwap;
use std::borrow::Cow;
use std::sync::Arc;
use std::time::Duration;
#[derive(Clone)]
pub struct Upstream {
pub uri: http::Uri,
pub name: String,
breaker: Arc<Breaker>,
health_path: Option<String>,
health_disabled: bool,
}
impl Upstream {
pub fn new(uri: http::Uri, breaker: BreakerConfig) -> Result<Self, Error> {
let name = upstream_name(&uri);
let breaker = Arc::new(Breaker::for_upstream(name.clone(), &breaker)?);
Ok(Self {
uri,
name,
breaker,
health_path: None,
health_disabled: false,
})
}
pub fn with_health(mut self, path: Option<String>, disabled: bool) -> Self {
self.health_path = path;
self.health_disabled = disabled;
self
}
pub fn health_path(&self) -> &str {
self.health_path.as_deref().unwrap_or("/health")
}
pub fn health_disabled(&self) -> bool {
self.health_disabled
}
pub fn try_acquire(&self) -> Option<Admission> {
self.breaker.try_acquire()
}
pub fn release(&self, admission: Admission) {
self.breaker.release(admission)
}
pub fn record_success(&self, admission: Admission) {
self.breaker.record_success(admission)
}
pub fn record_failure(&self, admission: Admission) {
self.breaker.record_failure(admission)
}
pub fn state(&self) -> CircuitState {
self.breaker.state()
}
pub(crate) fn reuse(
&self,
cooldown: Duration,
failure_threshold: u32,
health_path: Option<String>,
health_disabled: bool,
) -> Self {
self.breaker.reconfigure(cooldown, failure_threshold);
self.clone().with_health(health_path, health_disabled)
}
}
pub(crate) fn upstream_name(uri: &http::Uri) -> String {
let host = uri.host().unwrap_or("").to_ascii_lowercase();
let port = uri.port_u16().unwrap_or(match uri.scheme_str() {
Some("https") => 443,
_ => 80,
});
format!("{host}:{port}")
}
#[non_exhaustive]
pub struct Route {
pub prefix: String,
pub upstream: Upstream,
pub rewrite_host: bool,
pub strip_prefix: bool,
}
impl Route {
pub fn new(prefix: impl Into<String>, upstream: Upstream) -> Self {
Self {
prefix: prefix.into(),
upstream,
rewrite_host: false,
strip_prefix: false,
}
}
pub fn with_strip_prefix(mut self, strip: bool) -> Self {
self.strip_prefix = strip;
self
}
pub fn stripped_prefix(&self) -> &str {
self.prefix.trim_end_matches('/')
}
pub fn stripped_path(&self, raw_path: &str) -> Option<String> {
let prefix = self.stripped_prefix();
if prefix.is_empty() {
return Some(raw_path.to_string());
}
let norm = normalize(raw_path);
let rest = norm.strip_prefix(prefix)?;
let out = if rest.is_empty() { "/" } else { rest };
(out.starts_with('/') && !crate::path::bad_path(out)).then(|| out.to_string())
}
pub fn with_rewrite_host(mut self, rewrite: bool) -> Self {
self.rewrite_host = rewrite;
self
}
}
pub struct RouteTable {
routes: Vec<Route>,
pub upstream_timeout: Duration,
keepalive_timeout: Duration,
request_body_idle_timeout: Duration,
request_body_timeout: Duration,
drain_timeout: Duration,
shutdown_delay: Duration,
trusted_proxies: TrustedProxies,
forwarded_header: bool,
xff_mode: crate::config::XffMode,
local_health_path: Option<String>,
access_log: bool,
request_id: bool,
}
impl RouteTable {
pub fn new(mut routes: Vec<Route>, upstream_timeout: Duration) -> Self {
routes.sort_by_key(|r| std::cmp::Reverse(r.prefix.len()));
Self {
routes,
upstream_timeout,
keepalive_timeout: Duration::from_secs(crate::config::DEFAULT_KEEPALIVE_SECS),
request_body_idle_timeout: Duration::from_secs(crate::config::DEFAULT_BODY_IDLE_SECS),
request_body_timeout: Duration::from_secs(crate::config::DEFAULT_BODY_TOTAL_SECS),
drain_timeout: Duration::from_secs(crate::config::DEFAULT_DRAIN_SECS),
shutdown_delay: Duration::ZERO,
trusted_proxies: TrustedProxies::default(),
forwarded_header: false,
xff_mode: crate::config::XffMode::default(),
local_health_path: None,
access_log: false,
request_id: false,
}
}
pub fn with_local_health_path(mut self, p: Option<String>) -> Self {
self.local_health_path = p;
self
}
pub fn local_health_path(&self) -> Option<&str> {
self.local_health_path.as_deref()
}
pub fn with_keepalive_timeout(mut self, d: Duration) -> Self {
self.keepalive_timeout = d;
self
}
pub fn with_request_body_idle_timeout(mut self, d: Duration) -> Self {
self.request_body_idle_timeout = d;
self
}
pub fn with_request_body_timeout(mut self, d: Duration) -> Self {
self.request_body_timeout = d;
self
}
pub fn with_drain_timeout(mut self, d: Duration) -> Self {
self.drain_timeout = d;
self
}
pub fn with_shutdown_delay(mut self, d: Duration) -> Self {
self.shutdown_delay = d;
self
}
pub fn drain_timeout(&self) -> Duration {
self.drain_timeout
}
pub fn shutdown_delay(&self) -> Duration {
self.shutdown_delay
}
pub fn with_trusted_proxies(mut self, t: TrustedProxies) -> Self {
self.trusted_proxies = t;
self
}
pub fn with_forwarded_header(mut self, on: bool) -> Self {
self.forwarded_header = on;
self
}
pub fn with_access_log(mut self, on: bool) -> Self {
self.access_log = on;
self
}
pub fn with_request_id(mut self, on: bool) -> Self {
self.request_id = on;
self
}
pub fn access_log(&self) -> bool {
self.access_log
}
pub fn request_id(&self) -> bool {
self.request_id
}
pub fn with_xff_mode(mut self, m: crate::config::XffMode) -> Self {
self.xff_mode = m;
self
}
pub fn forwarded_header(&self) -> bool {
self.forwarded_header
}
pub fn xff_mode(&self) -> crate::config::XffMode {
self.xff_mode
}
pub fn keepalive_timeout(&self) -> Duration {
self.keepalive_timeout
}
pub fn request_body_idle_timeout(&self) -> Duration {
self.request_body_idle_timeout
}
pub fn request_body_timeout(&self) -> Duration {
self.request_body_timeout
}
pub fn trusted_proxies(&self) -> &TrustedProxies {
&self.trusted_proxies
}
pub fn lookup(&self, path: &str) -> Option<&Route> {
let path = normalize(path);
self.routes
.iter()
.find(|r| prefix_matches(&r.prefix, &path))
}
pub fn upstreams(&self) -> impl Iterator<Item = &Upstream> {
let mut seen = std::collections::HashSet::new();
self.routes
.iter()
.filter_map(move |r| seen.insert(r.upstream.name.clone()).then_some(&r.upstream))
}
pub fn publish_gauges(&self) {
for u in self.upstreams() {
u.breaker.set_gauges();
}
}
}
fn hex_val(c: u8) -> Option<u8> {
(c as char).to_digit(16).map(|d| d as u8)
}
fn is_unreserved(c: u8) -> bool {
c.is_ascii_alphanumeric() || matches!(c, b'-' | b'.' | b'_' | b'~')
}
fn rewrite_at(b: &[u8], i: usize) -> Option<(usize, [u8; 3], usize)> {
match b[i] {
b'/' if b.get(i + 1) == Some(&b'/') => Some((1, [0; 3], 0)),
b'%' => {
let (h, l) = (hex_val(*b.get(i + 1)?)?, hex_val(*b.get(i + 2)?)?);
let c = h << 4 | l;
if is_unreserved(c) {
Some((3, [c, 0, 0], 1))
} else if b[i + 1].is_ascii_lowercase() || b[i + 2].is_ascii_lowercase() {
Some((
3,
[
b'%',
b[i + 1].to_ascii_uppercase(),
b[i + 2].to_ascii_uppercase(),
],
3,
))
} else {
None
}
}
_ => None,
}
}
pub(crate) fn normalize(path: &str) -> Cow<'_, str> {
if !path.contains('%') && !path.contains("//") {
return Cow::Borrowed(path);
}
let b = path.as_bytes();
let Some(first) = (0..b.len()).find(|&i| rewrite_at(b, i).is_some()) else {
return Cow::Borrowed(path);
};
let mut out = Vec::with_capacity(b.len());
out.extend_from_slice(&b[..first]);
let mut i = first;
while i < b.len() {
match rewrite_at(b, i) {
Some((n, bytes, len)) => {
out.extend_from_slice(&bytes[..len]);
i += n;
}
None => {
out.push(b[i]);
i += 1;
}
}
}
Cow::Owned(String::from_utf8(out).expect("only ASCII substituted"))
}
fn prefix_matches(prefix: &str, path: &str) -> bool {
if prefix.ends_with('/') {
return path.starts_with(prefix);
}
if !path.starts_with(prefix) {
return false;
}
matches!(path.as_bytes().get(prefix.len()), None | Some(b'/'))
}
pub type SharedTable = Arc<ArcSwap<RouteTable>>;
#[cfg(test)]
mod tests {
use super::*;
fn upstream() -> Upstream {
Upstream::new("http://localhost:8001".parse().unwrap(), Default::default()).unwrap()
}
fn table(prefixes: &[&str]) -> RouteTable {
let routes = prefixes
.iter()
.map(|p| Route::new(*p, upstream()))
.collect();
RouteTable::new(routes, Duration::from_secs(30))
}
fn route_of<'a>(t: &'a RouteTable, p: &str) -> Option<&'a str> {
t.lookup(p).map(|r| r.prefix.as_str())
}
#[test]
fn matches_on_normalised_path() {
let t = table(&["/", "/api", "/~x"]);
assert_eq!(route_of(&t, "/%61pi/x"), Some("/api"));
assert_eq!(route_of(&t, "//api/x"), Some("/api"));
assert_eq!(route_of(&t, "/api//x"), Some("/api"));
assert_eq!(route_of(&t, "///api"), Some("/api"));
assert_eq!(route_of(&t, "/%7ex"), Some("/~x"));
assert_eq!(route_of(&t, "/%7Ex/y"), Some("/~x"));
assert_eq!(route_of(&t, "/API/x"), Some("/"));
assert_eq!(route_of(&t, "/%41pi/x"), Some("/"));
assert_eq!(route_of(&t, "/api%2fx"), Some("/"));
assert_eq!(route_of(&t, "/api%2Fx"), Some("/"));
assert_eq!(route_of(&t, "/apix"), Some("/"));
}
#[test]
fn normalize_cases() {
for (raw, want) in [
("/a%2fb", "/a%2Fb"),
("/a%2Fb", "/a%2Fb"),
("/%61%2f//b", "/a%2F/b"),
("/a%zz", "/a%zz"),
("/a%6", "/a%6"),
("/a%e4%b8%ad", "/a%E4%B8%AD"),
] {
assert_eq!(normalize(raw), want, "{raw}");
}
for p in ["/", "/api/x", "/a%2Fb", "/a%zz"] {
assert!(matches!(normalize(p), Cow::Borrowed(_)), "{p}");
}
}
#[test]
fn decoding_dots_only_happens_inside_longer_segments() {
assert_eq!(normalize("/api/a%2eb"), "/api/a.b");
assert_eq!(normalize("/api/%2e%2e/x"), "/api/../x");
}
#[test]
fn escaped_prefix_and_trailing_slash_prefix() {
let t = table(&["/", "/a%2Fb", "/v/"]);
assert_eq!(route_of(&t, "/a%2fb"), Some("/a%2Fb"));
assert_eq!(route_of(&t, "/a%2Fb/x"), Some("/a%2Fb"));
assert_eq!(route_of(&t, "/v//x"), Some("/v/"));
assert_eq!(route_of(&t, "/v/a//x"), Some("/v/"));
let t = table(&["/api/", "/api/v1/"]);
assert_eq!(route_of(&t, "/api//"), Some("/api/"));
assert_eq!(route_of(&t, "/api/v1//x"), Some("/api/v1/"));
}
#[test]
fn segment_boundary_matches() {
let t = table(&["/svc-a"]);
assert!(t.lookup("/svc-a").is_some());
assert!(t.lookup("/svc-a/").is_some());
assert!(t.lookup("/svc-a/x").is_some());
assert!(t.lookup("/svc-ab").is_none());
assert!(t.lookup("/other").is_none());
}
#[test]
fn longest_prefix_wins() {
let t = table(&["/svc-a", "/svc-a/v2"]);
let r = t.lookup("/svc-a/v2/users").unwrap();
assert_eq!(r.prefix, "/svc-a/v2");
let r = t.lookup("/svc-a/v1/users").unwrap();
assert_eq!(r.prefix, "/svc-a");
}
#[test]
fn root_catch_all() {
let t = table(&["/svc-a", "/"]);
assert_eq!(t.lookup("/svc-a").unwrap().prefix, "/svc-a");
assert_eq!(t.lookup("/anything/else").unwrap().prefix, "/");
}
#[test]
fn trailing_slash_prefix_is_plain_starts_with() {
let t = table(&["/svc-a/"]);
assert!(t.lookup("/svc-a/x").is_some());
assert!(t.lookup("/svc-a").is_none());
}
#[test]
fn stripped_path_remainders() {
let r = |p: &str| Route::new(p, upstream()).with_strip_prefix(true);
assert_eq!(
r("/api").stripped_path("/api/users").as_deref(),
Some("/users")
);
assert_eq!(r("/api").stripped_path("/api").as_deref(), Some("/"));
assert_eq!(r("/api").stripped_path("/api/").as_deref(), Some("/"));
assert_eq!(
r("/api/").stripped_path("/api/users").as_deref(),
Some("/users")
);
assert_eq!(r("/api/").stripped_path("/api/").as_deref(), Some("/"));
assert_eq!(r("/api/").stripped_prefix(), "/api");
assert_eq!(
r("/api").stripped_path("/%61pi/users").as_deref(),
Some("/users")
);
assert_eq!(
r("/api").stripped_path("//api//users").as_deref(),
Some("/users")
);
assert_eq!(
r("/api").stripped_path("/api/a%2fb").as_deref(),
Some("/a%2Fb")
);
assert_eq!(r("/").stripped_path("/x").as_deref(), Some("/x"));
assert_eq!(r("/api").stripped_path("/api/%2%65%2%65/x"), None);
assert_eq!(r("/api").stripped_path("/apix"), None);
assert_eq!(r("/api").stripped_path("/other"), None);
assert_eq!(r("/api").stripped_path("/api/%2e%2e/x"), None);
for p in ["/api/a/b", "/api/%41", "/api/a%2Fb", "/api"] {
let out = r("/api").stripped_path(p).unwrap();
assert!(!crate::path::bad_path(&out), "{p} -> {out}");
}
}
#[test]
fn upstreams_deduped_by_name() {
let shared = upstream();
let routes = vec![
Route::new("/a", shared.clone()),
Route::new("/b", shared.clone()),
];
let t = RouteTable::new(routes, Duration::from_secs(30));
assert_eq!(t.upstreams().count(), 1);
}
}