axol 0.1.5

Axol 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
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
use std::{fmt, sync::Arc};

use crate::{
    EarlyResponseHook, EarlyResponseHookExpansion, Error, ErrorHook, ErrorHookExpansion, Handler,
    HandlerExpansion, LateResponseHook, LateResponseHookExpansion, MatchedPath, Plugin,
    RequestHook, RequestHookExpansion, Result, Wrap,
};
use axol_http::{response::Response, Extensions, Method};
use log::warn;

type Route = Arc<dyn Handler>;

#[derive(PartialEq, Clone, Debug)]
enum Segment {
    Literal(String),
    Variable(Arc<str>),
}

impl fmt::Display for Segment {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Segment::Literal(x) => write!(f, "{x}"),
            Segment::Variable(x) => write!(f, ":{x}"),
        }
    }
}

impl Default for Segment {
    fn default() -> Self {
        Segment::Literal(String::new())
    }
}

#[derive(Default, Clone)]
pub struct Router {
    segment: Segment,
    routed_path: Arc<String>,
    subpaths: Vec<Router>,
    methods: Vec<(Method, Route)>,
    request_hooks: Vec<Arc<dyn RequestHook>>,
    early_response_hooks: Vec<Arc<dyn EarlyResponseHook>>,
    late_response_hooks: Vec<Arc<dyn LateResponseHook>>,
    error_hooks: Vec<Arc<dyn ErrorHook>>,
    wraps: Vec<Arc<dyn Wrap>>,
    outer_wraps: Vec<Arc<dyn Wrap>>,
    fallback: Option<Route>,
    extensions: Extensions,
}

impl fmt::Debug for Router {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Router")
            .field("segment", &self.segment)
            .field("routed_path", &self.routed_path)
            .field("subpaths", &self.subpaths)
            .field("methods", &self.methods.len())
            .field("request_hooks", &self.request_hooks.len())
            .field("early_response_hooks", &self.early_response_hooks.len())
            .field("late_response_hooks", &self.late_response_hooks.len())
            .field("error_hooks", &self.error_hooks.len())
            .field("wraps", &self.wraps.len())
            .field("fallback", &self.fallback.is_some())
            .field("extensions", &self.extensions)
            .finish()
    }
}

pub struct PathVariables(pub Vec<(Arc<str>, String)>);

fn split_path_reverse(path: &str) -> Vec<Segment> {
    path.trim()
        .split('/')
        .filter(|x| !x.is_empty())
        .map(|x| x.trim())
        .rev()
        .map(|x| {
            if x.starts_with(':') {
                Segment::Variable(x[1..].to_string().into())
            } else {
                Segment::Literal(x.to_string())
            }
        })
        .collect()
}

fn split_raw_path(path: &str) -> Vec<&str> {
    path.trim()
        .split('/')
        .filter(|x| !x.is_empty())
        .map(|x| x.trim())
        .collect()
}

async fn default_route() -> Result<Response> {
    Err(Error::NotFound)
}

lazy_static::lazy_static! {
    static ref DEFAULT_ROUTE: Arc<dyn Handler> = {
        let route: Box<dyn HandlerExpansion<()>> = Box::new(default_route);
        let handler: Arc<dyn Handler> = Arc::new(route);
        handler
    };
}

pub struct ObservedRoute<'a> {
    pub route: &'a Route,
    pub extensions: Extensions,
    pub variables: PathVariables,
    //TODO: clean these up to not clone arcs
    pub request_hooks: Vec<Arc<dyn RequestHook>>,
    pub error_hooks: Vec<Arc<dyn ErrorHook>>,
    pub early_response_hooks: Vec<Arc<dyn EarlyResponseHook>>,
    pub late_response_hooks: Vec<Arc<dyn LateResponseHook>>,
    pub wraps: Vec<Arc<dyn Wrap>>,
    pub outer_wraps: Vec<Arc<dyn Wrap>>,
}

impl<'a> ObservedRoute<'a> {
    fn check(&self) -> ObservedRouteCheck {
        ObservedRouteCheck {
            variables: self.variables.0.len(),
            request_hooks: self.request_hooks.len(),
            error_hooks: self.error_hooks.len(),
            early_response_hooks: self.early_response_hooks.len(),
            late_response_hooks: self.late_response_hooks.len(),
        }
    }

    fn reset(&mut self, check: ObservedRouteCheck) {
        self.variables.0.truncate(check.variables);
        self.request_hooks.truncate(check.request_hooks);
        self.error_hooks.truncate(check.error_hooks);
        self.early_response_hooks
            .truncate(check.early_response_hooks);
        self.late_response_hooks.truncate(check.late_response_hooks);
    }
}

struct ObservedRouteCheck {
    variables: usize,
    request_hooks: usize,
    error_hooks: usize,
    early_response_hooks: usize,
    late_response_hooks: usize,
}

impl Router {
    pub fn new() -> Self {
        Router::default()
    }

    pub fn resolve_path(&self, method: Method, path: &str) -> ObservedRoute<'_> {
        let mut out = ObservedRoute {
            route: &DEFAULT_ROUTE,
            extensions: Extensions::default(),
            variables: PathVariables(vec![]),
            request_hooks: vec![],
            error_hooks: vec![],
            early_response_hooks: vec![],
            late_response_hooks: vec![],
            wraps: vec![],
            outer_wraps: vec![],
        };
        if let Some(route) = self.do_resolve_path(&mut out, method, &split_raw_path(path)) {
            out.route = &*route;
        }
        out
    }

    fn do_resolve_path<'a>(
        &self,
        observed: &mut ObservedRoute<'_>,
        method: Method,
        segments: &[&str],
    ) -> Option<&Route> {
        observed
            .request_hooks
            .extend(self.request_hooks.iter().cloned());
        observed
            .error_hooks
            .extend(self.error_hooks.iter().cloned());
        observed
            .late_response_hooks
            .extend(self.late_response_hooks.iter().cloned());
        observed
            .early_response_hooks
            .extend(self.early_response_hooks.iter().cloned());
        observed.wraps.extend(self.wraps.iter().cloned());
        observed
            .outer_wraps
            .extend(self.outer_wraps.iter().cloned());
        observed.extensions.extend(&self.extensions);
        let Some(segment) = segments.first() else {
            observed.extensions.insert(MatchedPath(self.routed_path.clone()));
            if let Some((_, route)) = self.methods.iter().find(|x| x.0 == method) {
                return Some(route);
            }
            if method == Method::Head {
                if let Some((_, route)) = self.methods.iter().find(|x| x.0 == Method::Get) {
                    return Some(route);
                }
            }
            return self.fallback.as_ref();
        };
        // find existing segment
        let mut variable_subpath: Option<&Router> = None;
        for subpath in self.subpaths.iter() {
            match &subpath.segment {
                Segment::Literal(literal) => {
                    if literal == segment {
                        let check = observed.check();
                        if let Some(route) =
                            subpath.do_resolve_path(observed, method, &segments[1..])
                        {
                            return Some(route);
                        }
                        observed.reset(check);
                    }
                }
                Segment::Variable(_) => {
                    variable_subpath = Some(subpath);
                    // we delay using the variable path in case there is a literal that supersedes it below
                }
            }
        }
        if let Some(subpath) = variable_subpath {
            let name = match &subpath.segment {
                Segment::Variable(x) => x,
                _ => unreachable!(),
            };
            let check = observed.check();
            observed
                .variables
                .0
                .push((name.clone(), segment.to_string()));
            if let Some(route) = subpath.do_resolve_path(observed, method, &segments[1..]) {
                return Some(route);
            }
            observed.reset(check);
        }

        self.fallback.as_ref()
    }

    fn resolve_segments_mut(&mut self, mut segments: Vec<Segment>) -> &mut Router {
        let Some(segment) = segments.pop() else {
            return self;
        };
        // find existing segment
        let mut subpath_index = None::<usize>;
        for (i, subpath) in self.subpaths.iter().enumerate() {
            if subpath.segment == segment {
                subpath_index = Some(i);
            }
        }
        // bizarre borrow checker shenanigans
        if let Some(i) = subpath_index {
            return self.subpaths[i].resolve_segments_mut(segments);
        }
        if matches!(segment, Segment::Variable(_))
            && self
                .subpaths
                .iter()
                .filter(|x| matches!(x.segment, Segment::Variable(_)))
                .count()
                > 0
        {
            panic!("each routing level at the same superpath must use the same variable name. i.e. `/api/:var` and `/api/:variable` are invalid");
        }
        let mut subrouter = Router::new();
        subrouter.segment = segment;
        self.subpaths.push(subrouter);
        self.subpaths
            .last_mut()
            .unwrap()
            .resolve_segments_mut(segments)
    }

    pub(crate) fn set_paths(&mut self, mut path: &str) {
        while path.ends_with('/') {
            path = &path[..path.len() - 1];
        }
        self.routed_path = Arc::new(format!("{path}/{}", self.segment));
        for child in &mut self.subpaths {
            child.set_paths(&self.routed_path);
        }
    }

    fn append_segment(&mut self, segments: Vec<Segment>, method: Method, route: Route) {
        let target = self.resolve_segments_mut(segments);
        if let Some(handler) = target
            .methods
            .iter_mut()
            .find(|(current_method, _)| current_method == &method)
        {
            warn!("overwriting route for method {method}");
            handler.1 = route;
        } else {
            target.methods.push((method, route));
        }
    }

    pub fn method<G: 'static>(
        mut self,
        path: &str,
        method: Method,
        route: impl HandlerExpansion<G>,
    ) -> Self {
        let route: Box<dyn HandlerExpansion<G>> = Box::new(route);
        let handler: Arc<dyn Handler> = Arc::new(route);
        self.append_segment(split_path_reverse(path), method, handler);
        self
    }

    pub fn get<G: 'static>(self, path: &str, route: impl HandlerExpansion<G>) -> Self {
        self.method(path, Method::Get, route)
    }

    pub fn post<G: 'static>(self, path: &str, route: impl HandlerExpansion<G>) -> Self {
        self.method(path, Method::Post, route)
    }

    pub fn put<G: 'static>(self, path: &str, route: impl HandlerExpansion<G>) -> Self {
        self.method(path, Method::Put, route)
    }

    pub fn delete<G: 'static>(self, path: &str, route: impl HandlerExpansion<G>) -> Self {
        self.method(path, Method::Delete, route)
    }

    pub fn head<G: 'static>(self, path: &str, route: impl HandlerExpansion<G>) -> Self {
        self.method(path, Method::Head, route)
    }

    pub fn options<G: 'static>(self, path: &str, route: impl HandlerExpansion<G>) -> Self {
        self.method(path, Method::Options, route)
    }

    pub fn connect<G: 'static>(self, path: &str, route: impl HandlerExpansion<G>) -> Self {
        self.method(path, Method::Connect, route)
    }

    pub fn patch<G: 'static>(self, path: &str, route: impl HandlerExpansion<G>) -> Self {
        self.method(path, Method::Patch, route)
    }

    pub fn trace<G: 'static>(self, path: &str, route: impl HandlerExpansion<G>) -> Self {
        self.method(path, Method::Trace, route)
    }

    pub fn fallback<G: 'static>(mut self, path: &str, fallback: impl HandlerExpansion<G>) -> Self {
        let segments = split_path_reverse(path);
        let fallback: Box<dyn HandlerExpansion<G>> = Box::new(fallback);
        let handler: Arc<dyn Handler> = Arc::new(fallback);
        let target = self.resolve_segments_mut(segments);
        if let Some(fallback) = target.fallback.as_mut() {
            warn!("overwriting route for fallback");
            *fallback = handler;
        } else {
            target.fallback = Some(handler);
        }
        self
    }

    pub fn extension<T: Send + Sync + 'static>(mut self, path: &str, extension: T) -> Self {
        let segments = split_path_reverse(path);
        let target = self.resolve_segments_mut(segments);
        target.extensions.insert(extension);
        self
    }

    pub fn error_hook<G: 'static>(self, path: &str, hook: impl ErrorHookExpansion<G>) -> Self {
        let hook: Box<dyn ErrorHookExpansion<G>> = Box::new(hook);
        self.error_hook_direct(path, hook)
    }

    pub fn request_hook<G: 'static>(self, path: &str, hook: impl RequestHookExpansion<G>) -> Self {
        let hook: Box<dyn RequestHookExpansion<G>> = Box::new(hook);
        self.request_hook_direct(path, hook)
    }

    pub fn early_response_hook<G: 'static>(
        self,
        path: &str,
        hook: impl EarlyResponseHookExpansion<G>,
    ) -> Self {
        let hook: Box<dyn EarlyResponseHookExpansion<G>> = Box::new(hook);
        self.early_response_hook_direct(path, hook)
    }

    pub fn late_response_hook<G: 'static>(
        self,
        path: &str,
        hook: impl LateResponseHookExpansion<G>,
    ) -> Self {
        let hook: Box<dyn LateResponseHookExpansion<G>> = Box::new(hook);
        self.late_response_hook_direct(path, hook)
    }

    pub fn wrap(mut self, path: &str, hook: impl Wrap) -> Self {
        let segments = split_path_reverse(path);
        let hook: Arc<dyn Wrap> = Arc::new(hook);
        let target = self.resolve_segments_mut(segments);
        target.wraps.push(hook);
        self
    }

    pub fn outer_wrap(mut self, path: &str, hook: impl Wrap) -> Self {
        let segments = split_path_reverse(path);
        let hook: Arc<dyn Wrap> = Arc::new(hook);
        let target = self.resolve_segments_mut(segments);
        target.outer_wraps.push(hook);
        self
    }

    pub fn error_hook_direct(mut self, path: &str, hook: impl ErrorHook) -> Self {
        let segments = split_path_reverse(path);
        let hook: Arc<dyn ErrorHook> = Arc::new(hook);
        let target = self.resolve_segments_mut(segments);
        target.error_hooks.push(hook);
        self
    }

    pub fn request_hook_direct(mut self, path: &str, hook: impl RequestHook) -> Self {
        let segments = split_path_reverse(path);
        let hook: Arc<dyn RequestHook> = Arc::new(hook);
        let target = self.resolve_segments_mut(segments);
        target.request_hooks.push(hook);
        self
    }

    pub fn early_response_hook_direct(mut self, path: &str, hook: impl EarlyResponseHook) -> Self {
        let segments = split_path_reverse(path);
        let hook: Arc<dyn EarlyResponseHook> = Arc::new(hook);
        let target = self.resolve_segments_mut(segments);
        target.early_response_hooks.push(hook);
        self
    }

    pub fn late_response_hook_direct(mut self, path: &str, hook: impl LateResponseHook) -> Self {
        let segments = split_path_reverse(path);
        let hook: Arc<dyn LateResponseHook> = Arc::new(hook);
        let target = self.resolve_segments_mut(segments);
        target.late_response_hooks.push(hook);
        self
    }

    pub fn plugin(self, path: &str, hook: impl Plugin) -> Self {
        hook.apply(self, path)
    }

    pub fn nest(mut self, path: &str, router: Router) -> Self {
        let segments = split_path_reverse(path);
        let target = self.resolve_segments_mut(segments);
        target.do_merge(router);
        self
    }

    /// Same as nest with path = '/'
    pub fn merge(self, router: Router) -> Self {
        self.nest("/", router)
    }

    fn do_merge(&mut self, router: Router) {
        for (method, route) in router.methods {
            self.append_segment(vec![], method, route);
        }
        if let Some(fallback) = router.fallback {
            self.fallback = Some(fallback);
        }
        for subpath in router.subpaths {
            let subtarget = self.resolve_segments_mut(vec![subpath.segment.clone()]);
            subtarget.do_merge(subpath);
        }
    }
}