aboutsummaryrefslogtreecommitdiff
path: root/src/modules/paths.rs
blob: 713166432849c0ae8c9e13b25bf7a3f8aec217c3 (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
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
/*
    This file is part of gnix (https://codeberg.org/metamuffin/gnix)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2025 metamuffin <metamuffin.org>
*/
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::{
    de::{
        value::{MapAccessDeserializer, SeqAccessDeserializer},
        Visitor,
    },
    Deserialize,
};
use serde_yml::Value;
use std::{collections::BTreeMap, marker::PhantomData, 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::<SeqOrMap<DynNode>>(config)?.0;
        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
        })
    }
}

struct SeqOrMap<T>(Vec<(String, T)>);
impl<'de, T: Deserialize<'de>> Deserialize<'de> for SeqOrMap<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct Vis<V>(PhantomData<V>);
        impl<'de, V: Deserialize<'de>> Visitor<'de> for Vis<V> {
            type Value = SeqOrMap<V>;
            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("map or sequence of maps")
            }
            fn visit_seq<A>(self, seq: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::SeqAccess<'de>,
            {
                Vec::<BTreeMap<String, V>>::deserialize(SeqAccessDeserializer::new(seq))
                    .map(|e| SeqOrMap(e.into_iter().flat_map(|el| el.into_iter()).collect()))
            }
            fn visit_map<A>(self, map: A) -> Result<Self::Value, A::Error>
            where
                A: serde::de::MapAccess<'de>,
            {
                BTreeMap::<String, V>::deserialize(MapAccessDeserializer::new(map))
                    .map(|map| SeqOrMap(map.into_iter().collect()))
            }
        }
        deserializer.deserialize_any(Vis(PhantomData))
    }
}