Skip to main content

arks_server/web/core/
router.rs

1//! Declarative segment-based HTTP router supporting static segments, named parameters
2//! (`:id`, `:branch`), tail wildcards (`*path`), and accurate `405 Method Not Allowed`.
3
4use super::ctx::RouteParams;
5use super::route::AccessPolicy;
6
7/// Supported HTTP methods for Web UI and API routes.
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub enum Method {
10    Get,
11    Post,
12    Patch,
13    Delete,
14}
15
16impl Method {
17    pub fn parse(raw: &str) -> Option<Self> {
18        match raw {
19            "GET" => Some(Self::Get),
20            "POST" => Some(Self::Post),
21            "PATCH" => Some(Self::Patch),
22            "DELETE" => Some(Self::Delete),
23            _ => None,
24        }
25    }
26
27    pub const fn as_str(self) -> &'static str {
28        match self {
29            Self::Get => "GET",
30            Self::Post => "POST",
31            Self::Patch => "PATCH",
32            Self::Delete => "DELETE",
33        }
34    }
35}
36
37/// Declarative route entry stored inside [`Router`].
38#[derive(Debug, Clone)]
39pub struct RouteDef<H> {
40    pub method: Method,
41    pub pattern: &'static str,
42    pub policy: AccessPolicy,
43    pub handler: H,
44}
45
46#[derive(Debug, Clone)]
47enum Segment {
48    Static(&'static str),
49    Param(&'static str),
50    Wildcard(&'static str),
51}
52
53struct CompiledRoute<H> {
54    def: RouteDef<H>,
55    segments: Vec<Segment>,
56}
57
58/// Result of matching `(method, path)` against a [`Router`].
59#[derive(Debug)]
60pub enum RouteMatch<'a, H> {
61    Matched {
62        route: &'a RouteDef<H>,
63        params: RouteParams,
64    },
65    MethodNotAllowed {
66        allow: Vec<Method>,
67    },
68    NotFound,
69}
70
71/// Deterministic ordered segment router (zero external dependencies).
72pub struct Router<H> {
73    routes: Vec<CompiledRoute<H>>,
74}
75
76impl<H> Default for Router<H> {
77    fn default() -> Self {
78        Self::new()
79    }
80}
81
82impl<H> Router<H> {
83    pub fn new() -> Self {
84        Self { routes: Vec::new() }
85    }
86
87    /// Register a route with explicit HTTP method, pattern, and access policy.
88    pub fn add(
89        &mut self,
90        method: Method,
91        pattern: &'static str,
92        policy: AccessPolicy,
93        handler: H,
94    ) -> &mut Self {
95        let segments = compile_pattern(pattern);
96        self.routes.push(CompiledRoute {
97            def: RouteDef {
98                method,
99                pattern,
100                policy,
101                handler,
102            },
103            segments,
104        });
105        self
106    }
107
108    pub fn get(&mut self, pattern: &'static str, policy: AccessPolicy, handler: H) -> &mut Self {
109        self.add(Method::Get, pattern, policy, handler)
110    }
111
112    pub fn post(&mut self, pattern: &'static str, policy: AccessPolicy, handler: H) -> &mut Self {
113        self.add(Method::Post, pattern, policy, handler)
114    }
115
116    /// Match an incoming HTTP method and path. Static/exact matches declared earlier win.
117    ///
118    /// Per RFC 9110 §9.3.2, `HEAD` matches `GET` routes.
119    pub fn match_request(&self, method_str: &str, path: &str) -> RouteMatch<'_, H> {
120        let req_method = if method_str == "HEAD" {
121            Some(Method::Get)
122        } else {
123            Method::parse(method_str)
124        };
125        let path_segs: Vec<&str> = split_segments(path);
126        let mut allowed: Vec<Method> = Vec::new();
127
128        for compiled in &self.routes {
129            if let Some(params) = match_segments(&compiled.segments, &path_segs) {
130                if req_method == Some(compiled.def.method) {
131                    return RouteMatch::Matched {
132                        route: &compiled.def,
133                        params,
134                    };
135                }
136                if !allowed.contains(&compiled.def.method) {
137                    allowed.push(compiled.def.method);
138                }
139            }
140        }
141
142        if !allowed.is_empty() {
143            RouteMatch::MethodNotAllowed { allow: allowed }
144        } else {
145            RouteMatch::NotFound
146        }
147    }
148
149    /// Return all registered HTTP methods matching `path` (for `OPTIONS` / `Allow`).
150    pub fn allowed_methods(&self, path: &str) -> Vec<Method> {
151        let path_segs: Vec<&str> = split_segments(path);
152        let mut allowed: Vec<Method> = Vec::new();
153        for compiled in &self.routes {
154            if match_segments(&compiled.segments, &path_segs).is_some()
155                && !allowed.contains(&compiled.def.method)
156            {
157                allowed.push(compiled.def.method);
158            }
159        }
160        allowed
161    }
162}
163
164/// Format an RFC 9110 §10.2.1 `Allow` header value from router methods,
165/// automatically advertising `HEAD` when `GET` is allowed, plus `OPTIONS`.
166pub fn format_allow_header(methods: &[Method]) -> String {
167    let mut parts: Vec<&'static str> = Vec::with_capacity(methods.len() + 2);
168    for &m in methods {
169        parts.push(m.as_str());
170        if m == Method::Get && !parts.contains(&"HEAD") {
171            parts.push("HEAD");
172        }
173    }
174    if !parts.is_empty() && !parts.contains(&"OPTIONS") {
175        parts.push("OPTIONS");
176    }
177    parts.join(", ")
178}
179
180fn split_segments(path: &str) -> Vec<&str> {
181    let trimmed = path.trim_matches('/');
182    if trimmed.is_empty() {
183        Vec::new()
184    } else {
185        trimmed.split('/').collect()
186    }
187}
188
189fn compile_pattern(pattern: &'static str) -> Vec<Segment> {
190    split_segments(pattern)
191        .into_iter()
192        .map(|seg| {
193            if let Some(name) = seg.strip_prefix(':') {
194                Segment::Param(name)
195            } else if let Some(name) = seg.strip_prefix('*') {
196                Segment::Wildcard(name)
197            } else {
198                Segment::Static(seg)
199            }
200        })
201        .collect()
202}
203
204fn match_segments(pattern: &[Segment], input: &[&str]) -> Option<RouteParams> {
205    let mut params = RouteParams::new();
206    let mut pi = 0usize;
207    let mut ii = 0usize;
208
209    while pi < pattern.len() {
210        match pattern[pi] {
211            Segment::Static(lit) => {
212                if input.get(ii).copied() != Some(lit) {
213                    return None;
214                }
215                pi += 1;
216                ii += 1;
217            }
218            Segment::Param(name) => {
219                let val = *input.get(ii)?;
220                if val.is_empty() {
221                    return None;
222                }
223                params.insert(name, val);
224                pi += 1;
225                ii += 1;
226            }
227            Segment::Wildcard(name) => {
228                let tail = if ii < input.len() {
229                    input[ii..].join("/")
230                } else {
231                    String::new()
232                };
233                params.insert(name, tail);
234                return Some(params);
235            }
236        }
237    }
238
239    if ii == input.len() {
240        Some(params)
241    } else {
242        None
243    }
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    #[test]
251    fn router_matches_static_param_wildcard_and_405() {
252        let mut r: Router<&'static str> = Router::new();
253        r.get("/", AccessPolicy::ReadRepo, "home")
254            .get("/pulls/new", AccessPolicy::ReadRepo, "pr_new")
255            .get("/pulls/:branch", AccessPolicy::ReadRepo, "pr_detail")
256            .post(
257                "/issues/:id/comment",
258                AccessPolicy::WriteRepo,
259                "issue_comment",
260            )
261            .get("/blob/:rev/*path", AccessPolicy::ReadRepo, "blob");
262
263        match r.match_request("GET", "/pulls/new") {
264            RouteMatch::Matched { route, .. } => assert_eq!(route.handler, "pr_new"),
265            other => panic!("expected pr_new, got {other:?}"),
266        }
267        match r.match_request("GET", "/pulls/feature-1") {
268            RouteMatch::Matched { route, params } => {
269                assert_eq!(route.handler, "pr_detail");
270                assert_eq!(params.get("branch"), Some("feature-1"));
271            }
272            other => panic!("expected pr_detail, got {other:?}"),
273        }
274        match r.match_request("GET", "/blob/main/crates/arks/src/main.rs") {
275            RouteMatch::Matched { route, params } => {
276                assert_eq!(route.handler, "blob");
277                assert_eq!(params.get("rev"), Some("main"));
278                assert_eq!(params.get("path"), Some("crates/arks/src/main.rs"));
279            }
280            other => panic!("expected blob, got {other:?}"),
281        }
282        match r.match_request("GET", "/issues/7/comment") {
283            RouteMatch::MethodNotAllowed { allow } => assert_eq!(allow, vec![Method::Post]),
284            other => panic!("expected 405, got {other:?}"),
285        }
286        assert!(matches!(
287            r.match_request("GET", "/unknown"),
288            RouteMatch::NotFound
289        ));
290    }
291}