summaryrefslogtreecommitdiff
path: root/src/modules/paths.rs
blob: b994d488d01e888e14bdd9c0dc1a1486fbf90d04 (plain)
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
use super::{Node, NodeContext, NodeKind, NodeRequest, NodeResponse};
use crate::{config::DynNode, error::ServiceError};
use futures::Future;
use regex::RegexSet;
use serde_yaml::Value;
use std::{collections::BTreeMap, pin::Pin, sync::Arc};

pub struct PathsKind;

struct Paths {
    matcher: RegexSet,
    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_yaml::from_value::<BTreeMap<String, DynNode>>(config)?
            .into_iter()
            .collect::<Vec<(String, DynNode)>>();

        let mut handlers = Vec::new();
        let mut patterns = Vec::new();
        for (k, v) in routes {
            handlers.push(v);
            patterns.push(format!("^{}$", k));
        }
        let matcher = RegexSet::new(&patterns)?;

        Ok(Arc::new(Paths { handlers, matcher }))
    }
}
impl Node for Paths {
    fn handle<'a>(
        &'a self,
        context: &'a mut NodeContext,
        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)?;

            self.handlers[index].handle(context, request).await
        })
    }
}