churust-core 0.1.0

Core engine, routing, pipeline, and extractors for the Churust web framework.
Documentation
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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
//! The trie-based [`Router`], its [`Match`] result, and the [`RouteBuilder`]
//! DSL used inside [`AppBuilder::routing`](crate::AppBuilder::routing).
//!
//! Routes are matched segment by segment against static text, `{param}`
//! captures, and a trailing `{name...}` wildcard. Static segments win over
//! parameters, which win over wildcards.

use crate::handler::{boxed, BoxHandler, IntoHandler};
use http::Method;
use std::collections::HashMap;

/// The outcome of routing a `(method, path)` pair against the [`Router`].
///
/// Returned by [`Router::route`]. The framework translates each variant into a
/// response: [`Found`](Match::Found) runs the handler,
/// [`MethodNotAllowed`](Match::MethodNotAllowed) yields `405` with an `Allow`
/// header, and [`NotFound`](Match::NotFound) yields `404`.
///
/// ```
/// use churust_core::{boxed, Call, IntoHandler, Router, Match};
/// use http::Method;
///
/// let mut router = Router::new();
/// router.add(Method::GET, "/users/{id}", boxed((|_c: Call| async { "ok" }).into_handler()));
///
/// match router.route(&Method::GET, "/users/7") {
///     Match::Found { params, .. } => assert_eq!(params.get("id").unwrap(), "7"),
///     _ => panic!("expected a match"),
/// }
/// assert!(matches!(router.route(&Method::GET, "/nope"), Match::NotFound));
/// assert!(matches!(router.route(&Method::POST, "/users/7"), Match::MethodNotAllowed { .. }));
/// ```
pub enum Match {
    /// A handler matched the path and method. Carries the matched handler and
    /// the captured path parameters (`{name}` -> value).
    Found {
        /// The handler registered for this `(path, method)`.
        handler: BoxHandler,
        /// The captured path parameters, keyed by name.
        params: HashMap<String, String>,
    },
    /// The path matched a route, but not for this method. `allow` lists the
    /// methods that *are* registered (used to build the `Allow` header).
    MethodNotAllowed {
        /// The methods registered for the matched path.
        allow: Vec<Method>,
    },
    /// No route matched the path at all.
    NotFound,
}

#[derive(Default)]
struct Node {
    statics: HashMap<String, Node>,
    param: Option<(String, Box<Node>)>,      // {name}
    wildcard: Option<(String, BoxHandlers)>, // {name...} terminal
    handlers: BoxHandlers,
}

#[derive(Default)]
struct BoxHandlers(HashMap<Method, BoxHandler>);

impl std::fmt::Debug for Node {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Node").finish_non_exhaustive()
    }
}

/// A compiled, trie-based router mapping `(method, path)` to a handler.
///
/// Build one with [`Router::new`], register routes with [`Router::add`], and
/// look them up with [`Router::route`]. Inside an application you usually do not
/// touch the `Router` directly — the
/// [`RouteBuilder`] DSL in
/// [`AppBuilder::routing`](crate::AppBuilder::routing) populates it for you.
///
/// Supported pattern syntax (full paths, leading `/`):
/// - static segments: `/users/list`
/// - named parameters: `/users/{id}` (captured as `id`)
/// - trailing wildcard: `/files/{path...}` (captures the remaining path,
///   slashes included; must be the last segment)
///
/// ```
/// use churust_core::{boxed, Call, IntoHandler, Router, Match};
/// use http::Method;
///
/// let mut router = Router::new();
/// router.add(Method::GET, "/files/{path...}", boxed((|_c: Call| async { "" }).into_handler()));
/// match router.route(&Method::GET, "/files/a/b/c.txt") {
///     Match::Found { params, .. } => assert_eq!(params.get("path").unwrap(), "a/b/c.txt"),
///     _ => panic!("expected wildcard match"),
/// }
/// ```
#[derive(Debug, Default)]
pub struct Router {
    root: Node,
}

impl Router {
    /// Create an empty router. Equivalent to [`Router::default`].
    pub fn new() -> Self {
        Self::default()
    }

    /// Insert `handler` for `method` at `pattern` (the full path, e.g.
    /// `/users/{id}`).
    ///
    /// Registering different methods at the same path is fine; registering the
    /// same `(method, path)` twice replaces the earlier handler.
    ///
    /// # Panics
    ///
    /// Panics if a `{name...}` wildcard segment is not the final segment of the
    /// pattern.
    ///
    /// ```
    /// use churust_core::{boxed, Call, IntoHandler, Router, Match};
    /// use http::Method;
    ///
    /// let mut router = Router::new();
    /// router.add(Method::GET, "/ping", boxed((|_c: Call| async { "pong" }).into_handler()));
    /// assert!(matches!(router.route(&Method::GET, "/ping"), Match::Found { .. }));
    /// ```
    pub fn add(&mut self, method: Method, pattern: &str, handler: BoxHandler) {
        let mut node = &mut self.root;
        let segments: Vec<&str> = split_segments(pattern);
        for (i, seg) in segments.iter().enumerate() {
            if let Some(name) = seg.strip_prefix('{').and_then(|s| s.strip_suffix("...}")) {
                // wildcard must be terminal
                assert!(
                    i == segments.len() - 1,
                    "wildcard `{{{name}...}}` must be last segment"
                );
                let entry = node
                    .wildcard
                    .get_or_insert_with(|| (name.to_string(), BoxHandlers::default()));
                entry.1 .0.insert(method, handler);
                return;
            } else if let Some(name) = seg.strip_prefix('{').and_then(|s| s.strip_suffix('}')) {
                let entry = node
                    .param
                    .get_or_insert_with(|| (name.to_string(), Box::new(Node::default())));
                node = entry.1.as_mut();
            } else {
                node = node.statics.entry(seg.to_string()).or_default();
            }
        }
        node.handlers.0.insert(method, handler);
    }

    /// Route `path` for `method`, returning a [`Match`].
    ///
    /// Matching prefers static segments over `{param}` captures, and falls back
    /// to a `{name...}` wildcard at the deepest matchable ancestor. A path that
    /// matches a node with no handler for `method` yields
    /// [`Match::MethodNotAllowed`]; a path that matches no node yields
    /// [`Match::NotFound`].
    ///
    /// ```
    /// use churust_core::{boxed, Call, IntoHandler, Router, Match};
    /// use http::Method;
    ///
    /// let mut router = Router::new();
    /// router.add(Method::GET, "/", boxed((|_c: Call| async { "home" }).into_handler()));
    /// assert!(matches!(router.route(&Method::GET, "/"), Match::Found { .. }));
    /// assert!(matches!(router.route(&Method::GET, "/missing"), Match::NotFound));
    /// ```
    pub fn route(&self, method: &Method, path: &str) -> Match {
        let segments = split_segments(path);
        let mut params = HashMap::new();
        match Self::walk(&self.root, &segments, 0, &mut params) {
            Some(node) => match node.handlers.0.get(method) {
                Some(h) => Match::Found {
                    handler: h.clone(),
                    params,
                },
                None if node.handlers.0.is_empty() => Match::NotFound,
                None => Match::MethodNotAllowed {
                    allow: node.handlers.0.keys().cloned().collect(),
                },
            },
            None => {
                // try wildcard at the deepest matchable ancestor
                if let Some(m) = Self::walk_wildcard(&self.root, &segments, 0, method, &mut params)
                {
                    m
                } else {
                    Match::NotFound
                }
            }
        }
    }

    fn walk<'a>(
        node: &'a Node,
        segs: &[&str],
        i: usize,
        params: &mut HashMap<String, String>,
    ) -> Option<&'a Node> {
        if i == segs.len() {
            return Some(node);
        }
        let seg = segs[i];
        if let Some(child) = node.statics.get(seg) {
            if let Some(n) = Self::walk(child, segs, i + 1, params) {
                return Some(n);
            }
        }
        if let Some((name, child)) = &node.param {
            params.insert(name.clone(), seg.to_string());
            if let Some(n) = Self::walk(child, segs, i + 1, params) {
                return Some(n);
            }
            params.remove(name);
        }
        None
    }

    fn walk_wildcard(
        node: &Node,
        segs: &[&str],
        i: usize,
        method: &Method,
        params: &mut HashMap<String, String>,
    ) -> Option<Match> {
        if let Some((name, handlers)) = &node.wildcard {
            let rest = segs[i..].join("/");
            params.insert(name.clone(), rest);
            return Some(match handlers.0.get(method) {
                Some(h) => Match::Found {
                    handler: h.clone(),
                    params: std::mem::take(params),
                },
                None => Match::MethodNotAllowed {
                    allow: handlers.0.keys().cloned().collect(),
                },
            });
        }
        if i < segs.len() {
            if let Some(child) = node.statics.get(segs[i]) {
                if let Some(m) = Self::walk_wildcard(child, segs, i + 1, method, params) {
                    return Some(m);
                }
            }
            if let Some((pname, child)) = &node.param {
                params.insert(pname.clone(), segs[i].to_string());
                if let Some(m) = Self::walk_wildcard(child, segs, i + 1, method, params) {
                    return Some(m);
                }
                params.remove(pname);
            }
        }
        None
    }
}

fn split_segments(path: &str) -> Vec<&str> {
    path.split('/').filter(|s| !s.is_empty()).collect()
}

/// The route-definition DSL handed to the closure in
/// [`AppBuilder::routing`](crate::AppBuilder::routing).
///
/// Register handlers with the per-method helpers ([`get`](RouteBuilder::get),
/// [`post`](RouteBuilder::post), [`put`](RouteBuilder::put),
/// [`delete`](RouteBuilder::delete)) or the generic [`method`](RouteBuilder::method).
/// Group related routes under a common prefix with [`route`](RouteBuilder::route),
/// which nests cleanly. Each handler may be an extractor closure or anything
/// implementing [`Handler`](crate::Handler).
///
/// ```
/// use churust_core::{Churust, Call, TestClient};
/// # tokio::runtime::Runtime::new().unwrap().block_on(async {
/// let app = Churust::server()
///     .routing(|r| {
///         r.get("/", |_c: Call| async { "home" });
///         r.route("/api", |r| {
///             r.get("/health", |_c: Call| async { "ok" });
///         });
///     })
///     .build();
/// let res = TestClient::new(app).get("/api/health").send().await;
/// assert_eq!(res.text(), "ok");
/// # });
/// ```
pub struct RouteBuilder<'r> {
    router: &'r mut Router,
    prefix: String,
}

impl<'r> RouteBuilder<'r> {
    pub(crate) fn new(router: &'r mut Router) -> Self {
        Self {
            router,
            prefix: String::new(),
        }
    }

    fn full(&self, path: &str) -> String {
        let mut p = self.prefix.clone();
        if !path.starts_with('/') {
            p.push('/');
        }
        p.push_str(path);
        p
    }

    /// Register a handler for `method` at `path`. Accepts both extractor
    /// closures (via the `HandlerFn` family) and anything already implementing
    /// `Handler` — including a pre-boxed `BoxHandler` — through `IntoHandler`.
    pub fn method<Marker, H>(&mut self, method: Method, path: &str, handler: H) -> &mut Self
    where
        H: IntoHandler<Marker>,
    {
        let full = self.full(path);
        self.router
            .add(method, &full, boxed(handler.into_handler()));
        self
    }

    /// Register a `GET` handler at `path`. Returns `&mut Self` for chaining.
    pub fn get<Marker, H>(&mut self, path: &str, handler: H) -> &mut Self
    where
        H: IntoHandler<Marker>,
    {
        self.method(Method::GET, path, handler)
    }
    /// Register a `POST` handler at `path`. Returns `&mut Self` for chaining.
    pub fn post<Marker, H>(&mut self, path: &str, handler: H) -> &mut Self
    where
        H: IntoHandler<Marker>,
    {
        self.method(Method::POST, path, handler)
    }
    /// Register a `PUT` handler at `path`. Returns `&mut Self` for chaining.
    pub fn put<Marker, H>(&mut self, path: &str, handler: H) -> &mut Self
    where
        H: IntoHandler<Marker>,
    {
        self.method(Method::PUT, path, handler)
    }
    /// Register a `DELETE` handler at `path`. Returns `&mut Self` for chaining.
    pub fn delete<Marker, H>(&mut self, path: &str, handler: H) -> &mut Self
    where
        H: IntoHandler<Marker>,
    {
        self.method(Method::DELETE, path, handler)
    }

    /// Open a nested scope: every route registered inside `f` has `path`
    /// prepended to its pattern. Scopes nest arbitrarily, so prefixes compose.
    /// Returns `&mut Self` for chaining.
    pub fn route(&mut self, path: &str, f: impl FnOnce(&mut RouteBuilder)) -> &mut Self {
        let prefix = self.full(path);
        let mut child = RouteBuilder {
            router: self.router,
            prefix,
        };
        f(&mut child);
        self
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::call::Call;
    use bytes::Bytes;
    use http::{HeaderMap, StatusCode, Uri};

    fn build() -> Router {
        let mut r = Router::new();
        {
            let mut b = RouteBuilder::new(&mut r);
            b.get("/", |_c: Call| async { "root" });
            b.route("/users", |b| {
                b.get("/{id}", |c: Call| async move {
                    format!("user {}", c.param_raw("id").unwrap())
                });
                b.post("/", |_c: Call| async { (StatusCode::CREATED, "created") });
            });
            b.get("/files/{path...}", |c: Call| async move {
                format!("file {}", c.param_raw("path").unwrap())
            });
        }
        r
    }

    fn run(r: &Router, m: Method, path: &str) -> Match {
        r.route(&m, path)
    }

    #[tokio::test]
    async fn matches_static_and_param() {
        let r = build();
        match run(&r, Method::GET, "/users/7") {
            Match::Found { handler, params } => {
                assert_eq!(params.get("id").unwrap(), "7");
                let mut c = Call::new(
                    Method::GET,
                    "/users/7".parse::<Uri>().unwrap(),
                    HeaderMap::new(),
                    Bytes::new(),
                );
                c.set_params(params);
                let res = handler.handle(c).await;
                assert_eq!(res.body, Bytes::from("user 7"));
            }
            _ => panic!("expected Found"),
        }
    }

    #[test]
    fn unknown_path_is_not_found() {
        let r = build();
        assert!(matches!(run(&r, Method::GET, "/nope"), Match::NotFound));
    }

    #[test]
    fn known_path_wrong_method_is_405() {
        let r = build();
        match run(&r, Method::DELETE, "/users/7") {
            Match::MethodNotAllowed { allow } => assert!(allow.contains(&Method::GET)),
            _ => panic!("expected 405"),
        }
    }

    #[test]
    fn wildcard_captures_rest() {
        let r = build();
        match run(&r, Method::GET, "/files/a/b/c.txt") {
            Match::Found { params, .. } => assert_eq!(params.get("path").unwrap(), "a/b/c.txt"),
            _ => panic!("expected wildcard Found"),
        }
    }

    // Regression guard for blocking issue #2: a pre-boxed `BoxHandler` must be
    // acceptable to the route builder methods, not only closures.
    #[tokio::test]
    async fn route_builder_accepts_boxed_handler() {
        let pre: BoxHandler = boxed((|_c: Call| async { "pre-boxed" }).into_handler());
        let mut r = Router::new();
        {
            let mut b = RouteBuilder::new(&mut r);
            b.get("/pre", pre);
        }
        match run(&r, Method::GET, "/pre") {
            Match::Found { handler, .. } => {
                let c = Call::new(
                    Method::GET,
                    "/pre".parse::<Uri>().unwrap(),
                    HeaderMap::new(),
                    Bytes::new(),
                );
                let res = handler.handle(c).await;
                assert_eq!(res.body, Bytes::from("pre-boxed"));
            }
            _ => panic!("expected Found"),
        }
    }
}