kochab/src/routing.rs

154 lines
5.3 KiB
Rust
Raw Normal View History

//! Utilities for routing requests
//!
//! See [`RoutingNode`] for details on how routes are matched.
2020-11-20 18:22:34 +00:00
use uriparse::path::{Path, Segment};
2020-11-20 02:37:02 +00:00
use std::collections::HashMap;
use std::convert::TryInto;
use crate::Handler;
use crate::types::Request;
#[derive(Default)]
/// A node for routing requests
///
/// Routing is processed by a tree, with each child being a single path segment. For
/// example, if a handler existed at "/trans/rights", then the root-level node would have
/// a child "trans", which would have a child "rights". "rights" would have no children,
/// but would have an attached handler.
///
/// If one route is shorter than another, say "/trans/rights" and
/// "/trans/rights/r/human", then the longer route always matches first, so a request for
/// "/trans/rights/r/human/rights" would be routed to "/trans/rights/r/human", and
/// "/trans/rights/now" would route to "/trans/rights"
///
/// Routing is only performed on normalized paths, so "/endpoint" and "/endpoint/" are
/// considered to be the same route.
2020-11-20 02:37:02 +00:00
pub struct RoutingNode(Option<Handler>, HashMap<String, Self>);
impl RoutingNode {
/// Attempt to identify a handler based on path segments
///
/// This searches the network of routing nodes attempting to match a specific request,
/// represented as a sequence of path segments. For example, "/dir/image.png?text"
/// should be represented as `&["dir", "image.png"]`.
///
2020-11-20 18:22:34 +00:00
/// If a match is found, it is returned, along with the segments of the path trailing
/// the handler. For example, a route `/foo` recieving a request to `/foo/bar` would
/// receive `vec!["bar"]`
///
/// See [`RoutingNode`] for details on how routes are matched.
2020-11-20 18:22:34 +00:00
pub fn match_path<I,S>(&self, path: I) -> Option<(Vec<S>, &Handler)>
2020-11-20 02:37:02 +00:00
where
I: IntoIterator<Item=S>,
S: AsRef<str>,
{
let mut node = self;
2020-11-20 18:22:34 +00:00
let mut path = path.into_iter().filter(|seg| !seg.as_ref().is_empty());
2020-11-20 02:37:02 +00:00
let mut last_seen_handler = None;
2020-11-20 18:22:34 +00:00
let mut since_last_handler = Vec::new();
2020-11-20 02:37:02 +00:00
loop {
let Self(maybe_handler, map) = node;
2020-11-20 18:22:34 +00:00
if maybe_handler.is_some() {
last_seen_handler = maybe_handler.as_ref();
since_last_handler.clear();
}
2020-11-20 02:37:02 +00:00
if let Some(segment) = path.next() {
2020-11-20 18:22:34 +00:00
let maybe_route = map.get(segment.as_ref());
since_last_handler.push(segment);
if let Some(route) = maybe_route {
2020-11-20 02:37:02 +00:00
node = route;
} else {
2020-11-20 18:22:34 +00:00
break;
2020-11-20 02:37:02 +00:00
}
} else {
2020-11-20 18:22:34 +00:00
break;
2020-11-20 02:37:02 +00:00
}
2020-11-20 18:22:34 +00:00
};
if let Some(handler) = last_seen_handler {
since_last_handler.extend(path);
Some((since_last_handler, handler))
} else {
None
2020-11-20 02:37:02 +00:00
}
}
/// Attempt to identify a route for a given [`Request`]
///
2020-11-20 18:22:34 +00:00
/// See [`RoutingNode::match_path()`] for more information
pub fn match_request(&self, req: &Request) -> Option<(Vec<String>, &Handler)> {
let mut path = req.path().to_borrowed();
2020-11-20 02:37:02 +00:00
path.normalize(false);
self.match_path(path.segments())
2020-11-20 18:22:34 +00:00
.map(|(segs, h)| (
segs.into_iter()
.map(Segment::as_str)
.map(str::to_owned)
.collect(),
h,
))
2020-11-20 02:37:02 +00:00
}
/// Add a route to the network
///
/// This method wraps [`add_route_by_path()`](Self::add_route_by_path()) while
/// unwrapping any errors that might occur. For this reason, this method only takes
/// static strings. If you would like to add a string dynamically, please use
/// [`RoutingNode::add_route_by_path()`] in order to appropriately deal with any
/// errors that might arise.
pub fn add_route(&mut self, path: &'static str, handler: Handler) {
2020-11-20 02:37:02 +00:00
let path: Path = path.try_into().expect("Malformed path route received");
self.add_route_by_path(path, handler).unwrap();
}
/// Add a route to the network
///
/// The path provided MUST be absolute. Callers should verify this before calling
/// this method.
///
/// For information about how routes work, see [`RoutingNode::match_path()`]
pub fn add_route_by_path(&mut self, mut path: Path, handler: Handler) -> Result<(), ConflictingRouteError>{
2020-11-20 02:37:02 +00:00
debug_assert!(path.is_absolute());
path.normalize(false);
let mut node = self;
for segment in path.segments() {
if segment != "" {
node = node.1.entry(segment.to_string()).or_default();
}
2020-11-20 02:37:02 +00:00
}
if node.0.is_some() {
Err(ConflictingRouteError())
} else {
node.0 = Some(handler);
2020-11-20 02:37:02 +00:00
Ok(())
}
}
/// Recursively shrink maps to fit
pub fn shrink(&mut self) {
let mut to_shrink = vec![&mut self.1];
while let Some(shrink) = to_shrink.pop() {
shrink.shrink_to_fit();
to_shrink.extend(shrink.values_mut().map(|n| &mut n.1));
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct ConflictingRouteError();
impl std::error::Error for ConflictingRouteError { }
impl std::fmt::Display for ConflictingRouteError {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(f, "Attempted to create a route with the same matcher as an existing route")
}
}