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
|
use super::{Node, NodeContext, NodeKind, NodeRequest, NodeResponse};
use crate::{config::DynNode, error::ServiceError};
use futures::Future;
use http::Uri;
use regex::{Regex, RegexSet};
use serde_yml::Value;
use std::{collections::BTreeMap, pin::Pin, sync::Arc};
pub struct PathsKind;
struct Paths {
matcher: RegexSet,
extractors: Vec<Regex>,
handlers: Vec<DynNode>,
}
impl NodeKind for PathsKind {
fn name(&self) -> &'static str {
"paths"
}
fn instanciate(&self, config: Value) -> anyhow::Result<Arc<dyn Node>> {
let routes = serde_yml::from_value::<BTreeMap<String, DynNode>>(config)?
.into_iter()
.collect::<Vec<(String, DynNode)>>();
let mut handlers = Vec::new();
let mut patterns = Vec::new();
let mut extractors = Vec::new();
for (k, v) in routes {
let pattern = format!("^{k}$");
handlers.push(v);
extractors.push(Regex::new(&pattern)?);
patterns.push(pattern);
}
let matcher = RegexSet::new(&patterns)?;
Ok(Arc::new(Paths {
handlers,
matcher,
extractors,
}))
}
}
impl Node for Paths {
fn handle<'a>(
&'a self,
context: &'a mut NodeContext,
mut request: NodeRequest,
) -> Pin<Box<dyn Future<Output = Result<NodeResponse, ServiceError>> + Send + Sync + 'a>> {
Box::pin(async move {
let path = request.uri().path();
let index = self
.matcher
.matches(path)
.iter()
.next()
.ok_or(ServiceError::UnknownPath)?;
let caps = self.extractors[index]
.captures(path)
.ok_or(ServiceError::Other)?;
if let Some(rest) = caps.get(1) {
let mut parts = http::uri::Parts::default();
parts.scheme = request.uri().scheme().cloned();
parts.authority = request.uri().authority().cloned();
if let Some(q) = request.uri().query() {
parts.path_and_query = Some(
format!("{}?{}", rest.as_str(), q)
.parse()
.map_err(|_| ServiceError::Other)?,
);
} else {
parts.path_and_query =
Some(rest.as_str().parse().map_err(|_| ServiceError::Other)?);
}
*request.uri_mut() = Uri::from_parts(parts).map_err(|_| ServiceError::InvalidUri)?
}
self.handlers[index].handle(context, request).await
})
}
}
|