drought 0.0.1

The Directive Rougter.
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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
#![allow(unused)]

//! The core logic of `drought`.
//!
//! A [`Droughter`] acts as a single layer of directories. It may also be called
//! by consumers, as the root of a given directory tree. It keeps track of a set
//! of [`Drought`] trait objects. This allows for the manual implementation of
//! more structured router extensions, but `drought` provides facilities
//! for simply adding a stateless lambda function, in the case of simpler needs.
//!
//! # Droughts
//!
//! Each `Drought` in a `Droughter` has a given priority, and all droughts of
//! a given priority will be tested, before those of lower priority. If a
//! `Drought` returns a [`DroughtResult::NotFound`], the next `Drought` will be
//! checked. Otherwise, the [`DroughtResult`] will be returned up through the
//! chain of `Droughter`s that led to it being called. It should be noted that
//! the responsibility of deciding what resources to handle is down to the
//! discretion of each individual `Drought`, and that a `Drought` may choose to
//! serve any arbitrary number of resources.
//!
//! Subdirectories are handled by special `Drought`s, which wrap an internal
//! `Droughter`. They may be created via the [`insert_sub`][DroughterBuilder::insert_sub],
//! [`insert_typed`][DroughterBuilder::insert_typed], and [`insert_matched`][DroughterBuilder::insert_matched]
//! [`DroughterBuilder`] methods.
//!
//! `DroughtResult` is crucial to the internal logic of `drought`, and any
//! consumers should take time to read its documentation.
//!
//! # Irrigators
//!
//! As a request travels down the set of `Droughters`, and responses up again,
//! they will be passed through `Irrigator`s. `Irrigator`s allow for better
//! code reuse, as well as more efficient implementations of authentication,
//! caching, and so on. They are stored per-`Droughter`.
//!
//! [`RequestIrrigator`]s act as transformers for incoming requests. They may
//! insert headers, rewrite URLs, and even insert an early reply. See [IrrigatorResult]
//! for more information on what they can alter.
//!
//! [`ResponseIrrigator`]s act as transformers for outgoing responses. They
//! get a mutable reference to the `DroughtResult` returned by the previously
//! called `Drought`, and may alter it as they see fit. In particular, the
//! macro system uses this to insert proper 404 pages, as opposed to the
//! empty default.

use std::{collections::HashMap, future::Future, sync::Arc, str::FromStr, marker::PhantomData, any::{Any, TypeId}, marker::Copy, pin::Pin};

use http::{StatusCode, Request, response, Response, Uri};
use lazy_regex::Regex;

use crate::util::{uri_decode, uri_encode};

/// A single directory namespace.
///
/// See the [module-level docs][self] for more.
#[derive(Clone)]
pub struct Droughter {
    root: Option<Arc<dyn Drought>>,
    routes: Vec<Vec<Arc<dyn Drought>>>,
    req_irrigators: Vec<Arc<dyn RequestIrrigator>>,
    res_irrigators: Vec<Arc<dyn ResponseIrrigator>>
}
#[derive(Debug)]
pub enum DroughtResult {
    /// Indicates that the response should be sent back to the client.
    Handle(Response<Vec<u8>>),
    /// Indicates that the `Drought` was unable to handle the request,
    /// and another should be tried.
    NotFound,
    /// Indicates that the calling server should not reply to the
    /// request, as the droughter has already handled it. This is
    /// primarily intended for protocols such as websockets which
    /// bootstrap over HTTP.
    Ignore,
    /// Indicates that the connection in question should immediately
    /// be dropped.
    Drop,
    /// Indicates that the response should be sent, prior to dropping
    /// the connection.
    DropWith(Response<Vec<u8>>)
}
#[derive(Debug)]
pub enum IrrigatorResult {
    /// Interrupts the [`Droughter`], making it act as if a `Drought`
    /// had returned the wrapped [`DroughtResult`].
    ReplyNow(DroughtResult),
    /// Replace the current path and request with the wrapped ones.
    ContinueWith(Vec<String>, Request<Vec<u8>>),
    /// Replace the current path with the wrapped one.
    ContinueWithPath(Vec<String>),
    /// Replace the current request with the wrapped one.
    ContinueWithReq(Request<Vec<u8>>),
    /// Continue as normal, with no change to the environment.
    Continue
}
#[derive(Debug)]
pub enum DroughterResult {
    /// Indicates that the response should be sent back to the client.
    Handle(Response<Vec<u8>>),
    /// Indicates that the calling server should not reply to the
    /// request, as the droughter has already handled it. This is
    /// primarily intended for protocols such as websockets which
    /// bootstrap over HTTP.
    Ignore,
    /// Indicates that the connection in question should immediately
    /// be dropped.
    Drop,
    /// Indicates that the response should be sent, prior to dropping
    /// the connection.
    DropWith(Response<Vec<u8>>)
}

/// A trait to be `impl`emented by any part of the resource tree.
///
/// See the [module-level docs][self] for more.
pub trait Drought {
    fn handle<'a>(&'a self, original_path: &'a Vec<String>, path: &'a Vec<String>, req: &'a Request<Vec<u8>>, map: Matches) -> Pin<Box<dyn Future<Output = DroughtResult> + 'a>>;
}
pub trait RequestIrrigator {
    fn map<'a>(&'a self, original_path: &'a Vec<String>, path: &'a Vec<String>, req: &'a Request<Vec<u8>>, map: Matches) -> Pin<Box<dyn Future<Output = IrrigatorResult> + 'a>>;
}
pub trait ResponseIrrigator {
    fn map<'a>(&'a self, original_path: &'a Vec<String>, path: &'a Vec<String>, req: &'a Request<Vec<u8>>, res: &'a mut DroughtResult, map: &'a Matches) -> Pin<Box<dyn Future<Output = ()> + 'a>>;
}

/// A builder struct for [`Droughter`].
///
/// See the [module-level docs][self] for more.
#[derive(Default)]
pub struct DroughterBuilder {
    routes: HashMap<usize, Vec<Box<dyn Drought>>>,
    req_irrigators: Vec<Box<dyn RequestIrrigator>>,
    res_irrigators: Vec<Box<dyn ResponseIrrigator>>
}
impl DroughterBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    /// Adds an arbitrary `Drought` to the resulting `Droughter`,
    /// with the specified priority level.
    pub fn insert_drought(&mut self, priority: usize, drought: impl Drought + 'static) {
        if !self.routes.contains_key(&priority) { self.routes.insert(priority, Vec::new()); }
        self.routes.get_mut(&priority).unwrap().push(Box::new(drought));
    }
    /// A chainable version of [`insert_drought`][Self::insert_drought].
    pub fn with_drought(mut self, priority: usize, drought: impl Drought + 'static) -> Self {
        self.insert_drought(priority, drought);
        self
    }

    /// Creates a new `Drought`, which ferries requests to a
    /// `Droughter`, if the resource name matches `path`.
    pub fn insert_sub(&mut self, priority: usize, path: &str, droughter: Droughter) {
        self.insert_drought(priority, SubDrought{ path: path.to_string(), droughter });
    }
    /// A chainable version of [`insert_sub`][Self::insert_sub].
    pub fn with_sub(mut self, priority: usize, path: &str, droughter: Droughter) -> Self {
        self.insert_sub(priority, path, droughter);
        self
    }
    /// Creates a new `Drought`, which ferries requests to a
    /// `Droughter`, if the resource name is parseable as `T`.
    /// The match gets stored in the [`Matches`] as `name`.
    pub fn insert_typed<T: FromStr + 'static>(&mut self, priority: usize, name: &str, droughter: Droughter) {
        self.insert_drought(priority, TypedDrought::<T>{ name: name.to_string(), droughter, _pd: PhantomData::default() });
    }
    /// A chainable version of [`insert_typed`][Self::insert_typed].
    pub fn with_typed<T: FromStr + 'static>(mut self, priority: usize, name: &str, droughter: Droughter) -> Self {
        self.insert_typed::<T>(priority, name, droughter);
        self
    }
    /// Creates a new `Drought`, which ferries requests to a
    /// `Droughter`, if the resource name matches `regex`.
    /// The match gets stored in the [`Matches`] as `name`.
    pub fn insert_matched(&mut self, priority: usize, name: &str, regex: Regex, droughter: Droughter) {
        self.insert_drought(priority, MatchedDrought{ name: name.to_string(), regex, droughter });
    }
    /// A chainable version of [`insert_matched`][Self::insert_matched].
    pub fn with_matched(mut self, priority: usize, name: &str, regex: Regex, droughter: Droughter) -> Self {
        self.insert_matched(priority, name, regex, droughter);
        self
    }
    /// Creates a new `Drought`, which will directly pass calls to
    /// [`Drought::handle`] to `func`.
    pub fn insert_lambda(&mut self, priority: usize, func: for<'a> fn(&'a Vec<String>, &'a Vec<String>, &'a Request<Vec<u8>>, Matches) -> Pin<Box<dyn Future<Output = DroughtResult> + 'a>>) {
        self.insert_drought(priority, LambdaDrought{ func });
    }
    /// A chainable version of [`insert_lambda`][Self::insert_lambda].
    pub fn with_lambda(mut self, priority: usize, func: for<'a> fn(&'a Vec<String>, &'a Vec<String>, &'a Request<Vec<u8>>, Matches) -> Pin<Box<dyn Future<Output = DroughtResult> + 'a>>) -> Self {
        self.insert_lambda(priority, func);
        self
    }
    
    /// Adds an arbitrary [`RequestIrrigator`] to the resulting `Droughter`.
    pub fn insert_request_irrigator(&mut self, irrigator: impl RequestIrrigator + 'static) {
        self.req_irrigators.push(Box::new(irrigator))
    }
    /// A chainable version of [`insert_request_irrigator`][Self::insert_request_irrigator].
    pub fn with_request_irrigator(mut self, irrigator: impl RequestIrrigator + 'static) -> Self {
        self.insert_request_irrigator(irrigator);
        self
    }
    /// Creates a new `RequestIrrigator`, which will directly pass calls to
    /// [`RequestIrrigator::map`] to `func`.
    pub fn insert_request_irrigator_lambda(&mut self, func: for<'a> fn(&'a Vec<String>, &'a Vec<String>, &'a Request<Vec<u8>>, Matches) -> Pin<Box<dyn Future<Output = IrrigatorResult> + 'a>>) {
        self.insert_request_irrigator(LambdaRequestIrrigator{ func });
    }
    /// A chainable version of [`insert_request_irrigator_lambda`][Self::insert_request_irrigator_lambda].
    pub fn with_request_irrigator_lambda(mut self, func: for<'a> fn(&'a Vec<String>, &'a Vec<String>, &'a Request<Vec<u8>>, Matches) -> Pin<Box<dyn Future<Output = IrrigatorResult> + 'a>>) -> Self {
        self.insert_request_irrigator_lambda(func);
        self
    }

    /// Adds an arbitrary [`ResponseIrrigator`] to the resulting `Droughter`.
    pub fn insert_response_irrigator(&mut self, irrigator: impl ResponseIrrigator + 'static) {
        self.res_irrigators.push(Box::new(irrigator));
    }
    /// A chainable version of [`insert_response_irrigator`][Self::insert_response_irrigator].
    pub fn with_response_irrigator(mut self, irrigator: impl ResponseIrrigator + 'static) -> Self {
        self.insert_response_irrigator(irrigator);
        self
    }
    /// Creates a new `Drought`, which will directly pass calls to
    /// [`Drought::handle`] to `func`.
    pub fn insert_response_irrigator_lambda(&mut self, func: for<'a> fn(&'a Vec<String>, &'a Vec<String>, &'a Request<Vec<u8>>, &'a mut DroughtResult, &'a Matches) -> Pin<Box<dyn Future<Output = ()> + 'a>>) {
        self.insert_response_irrigator(LambdaResponseIrrigator{ func });
    }
    /// A chainable version of [`insert_lambda`][Self::insert_lambda].
    pub fn with_response_irrigator_lambda(mut self, func: for<'a> fn(&'a Vec<String>, &'a Vec<String>, &'a Request<Vec<u8>>, &'a mut DroughtResult, &'a Matches) -> Pin<Box<dyn Future<Output = ()> + 'a>>) -> Self {
        self.insert_response_irrigator_lambda(func);
        self
    }

    fn build_internal(self, root: Option<Arc<dyn Drought + 'static>>) -> Droughter {
        Droughter {
            root,
            
            routes: {
                let lowest_priority = self.routes.keys().reduce(|a,b| a.max(b)).cloned().unwrap_or(0);
                let mut routes = vec![];
                routes.resize_with(lowest_priority + 1, || Vec::new());

                for (priority, items) in self.routes {
                    for route in items {
                        routes[priority].push(route.into());
                    }
                }
                routes
            },
            
            req_irrigators: self.req_irrigators.into_iter().map(Into::into).collect(),
            res_irrigators: self.res_irrigators.into_iter().map(Into::into).collect()
        }
    }
    
    /// Builds the `Droughter` with no index.
    pub fn build(self) -> Droughter {
        self.build_internal(None)
    }
    /// Builds the `Droughter` with `root` as the index.
    pub fn build_with_root(self, root: impl Drought + 'static) -> Droughter {
        self.build_internal(Some(Arc::new(root)))
    }
    /// Builds the `Droughter` with `root` as the index.
    pub fn build_with_lambda(self, root: for<'a> fn(&'a Vec<String>, &'a Vec<String>, &'a Request<Vec<u8>>, Matches) -> Pin<Box<dyn Future<Output = DroughtResult> + 'a>>) -> Droughter {
        self.build_with_root(LambdaDrought{ func: root })
    }
}

impl Droughter {
    /// Runs the main Droughter code on the given request.
    pub async fn run(&self, req: &Request<Vec<u8>>) -> DroughterResult {
        // strip out bunk URIs
        let path = {
            let ogpath = req.uri().path().split("/").skip(1).map(uri_decode).collect::<Vec<_>>();
            if req.uri() == "/" {
                vec![]
            }
            else if ogpath.contains(&"".to_string()) || ogpath.contains(&"..".to_string()) {
                let mut redirpath: Vec<String> = Vec::new();
                for route in ogpath {
                    match route.as_str() {
                        "" => (),
                        ".." => { redirpath.pop(); },
                        val => { redirpath.push(uri_encode(val)); }
                    }
                }
                return DroughterResult::Handle(
                    Response::builder()
                        .status(301)
                        .header("Location", "/".to_string() + &redirpath.join("/") + req.uri().query().unwrap_or(""))
                        .body(Vec::new()).unwrap()
                )
            } else { ogpath }
        };

        let map = Matches::new();
        
        match self.run_internal(&path.clone(), &path, &req, map).await {
            DroughtResult::NotFound => DroughterResult::Handle(
                Response::builder()
                    .status(404)
                    .body(Vec::new())
                    .unwrap()
            ),            
            DroughtResult::Ignore => DroughterResult::Ignore,
            DroughtResult::Drop => DroughterResult::Drop,
            DroughtResult::DropWith(res) => DroughterResult::DropWith(res),
            DroughtResult::Handle(res) => DroughterResult::Handle(res)
        }
    }

    pub(self) async fn run_internal(&self, original_path: &Vec<String>, p_path: &Vec<String>, p_req: &Request<Vec<u8>>, mut map: Matches) -> DroughtResult {
        use IrrigatorResult::*;
        
        let mut abrupt_res = None;
        
        let (path, req) = {
            // call irrigators
            let mut path = None;
            let mut req = None;
            for req_irr in self.req_irrigators.iter() {
                match req_irr.map(original_path, path.as_ref().unwrap_or(p_path), req.as_ref().unwrap_or(p_req), map.clone()).await {
                    ReplyNow(response) => {
                        abrupt_res = Some(response);
                        break;
                    },
                    ContinueWith(newpath, newreq) => {
                        path = Some(newpath);
                        req = Some(newreq);
                    },
                    ContinueWithPath(newpath) => {
                        path = Some(newpath);
                    },
                    ContinueWithReq(newreq) => {
                        req = Some(newreq);
                    },
                    Continue => ()
                }
            }
            
            (path, req)
        };
        let (pathref, reqref) = (path.as_ref().unwrap_or(p_path), req.as_ref().unwrap_or(p_req));
        
        let mut response = if let Some(res) = abrupt_res {
            res
        }
        else {
            // test for index handler
            if pathref.is_empty() {
                if let Some(root) = &self.root {
                    root.handle(original_path, pathref, reqref, map.clone()).await
                }
                else {
                    DroughtResult::NotFound
                }
            }
            else {
                let mut res = DroughtResult::NotFound;
                
                'main: for priority in self.routes.iter() {
                    for route in priority {
                        res = route.handle(original_path, pathref, reqref, map.clone()).await;
                        
                        if let DroughtResult::NotFound = res {}
                        else { break 'main; }
                    }
                }
                res
            }
        };
        
        for res_irr in self.res_irrigators.iter() {
            res_irr.map(original_path, pathref, reqref, &mut response, &map).await;
        }

        response
    }
}

#[derive(Clone)]
struct SubDrought {
    path: String,
    droughter: Droughter
}
impl Drought for SubDrought {
    fn handle<'a>(&'a self, original_path: &'a Vec<String>, path: &'a Vec<String>, req: &'a Request<Vec<u8>>, map: Matches) -> Pin<Box<dyn Future<Output = DroughtResult> + 'a>> {
        Box::pin(
            async {
                if !path.is_empty() && path[0] == self.path {
                    self.droughter.run_internal(original_path, &path[1..].to_vec(), req, map).await
                }
                else { DroughtResult::NotFound }
            }
        )
    }
}

#[derive(Clone)]
struct TypedDrought<T: FromStr> {
    name: String,
    droughter: Droughter,
    _pd: PhantomData<T>
}
impl<T: FromStr> Drought for TypedDrought<T> {
    fn handle<'a>(&'a self, original_path: &'a Vec<String>, path: &'a Vec<String>, req: &'a Request<Vec<u8>>, mut map: Matches) -> Pin<Box<dyn Future<Output = DroughtResult> + 'a>> {
        Box::pin(
            async move {
                if !path.is_empty() {
                    if let Ok(_) = T::from_str(&path[0]) {
                        map.insert(&self.name, &path[0]);
                        
                        self.droughter.run_internal(original_path, &path[1..].to_vec(), req, map).await
                    }
                    else { DroughtResult::NotFound }
                }
                else { DroughtResult::NotFound }
            }
        )
    }
}
#[derive(Clone)]
struct MatchedDrought {
    name: String,
    regex: Regex,
    droughter: Droughter,
}
impl Drought for MatchedDrought {
    fn handle<'a>(&'a self, original_path: &'a Vec<String>, path: &'a Vec<String>, req: &'a Request<Vec<u8>>, mut map: Matches) -> Pin<Box<dyn Future<Output = DroughtResult> + 'a>> {
        Box::pin(
            async move {
                if !path.is_empty() && self.regex.is_match(&path[0]) {
                    map.insert(&self.name, &path[0]);
                    
                    self.droughter.run_internal(original_path, &path[1..].to_vec(), req, map).await
                }
                else { DroughtResult::NotFound }
            }
        )
    }
}
#[derive(Clone)]
struct LambdaDrought {
    func: for<'a> fn(&'a Vec<String>, &'a Vec<String>, &'a Request<Vec<u8>>, Matches) -> Pin<Box<dyn Future<Output = DroughtResult> + 'a>>
}
impl Drought for LambdaDrought {
    fn handle<'a>(&'a self, original_path: &'a Vec<String>, path: &'a Vec<String>, req: &'a Request<Vec<u8>>, mut map: Matches) -> Pin<Box<dyn Future<Output = DroughtResult> + 'a>> {
        (self.func)(original_path, path, req, map)
    }
}
#[derive(Clone)]
struct LambdaRequestIrrigator {
    func: for<'a> fn(&'a Vec<String>, &'a Vec<String>, &'a Request<Vec<u8>>, Matches) -> Pin<Box<dyn Future<Output = IrrigatorResult> + 'a>>
}
impl RequestIrrigator for LambdaRequestIrrigator {
    fn map<'a>(&'a self, original_path: &'a Vec<String>, path: &'a Vec<String>, req: &'a Request<Vec<u8>>, mut map: Matches) -> Pin<Box<dyn Future<Output = IrrigatorResult> + 'a>> {
        (self.func)(original_path, path, req, map)
    }
}
#[derive(Clone)]
struct LambdaResponseIrrigator {
    func: for<'a> fn(&'a Vec<String>, &'a Vec<String>, &'a Request<Vec<u8>>, &'a mut DroughtResult, &'a Matches) -> Pin<Box<dyn Future<Output = ()> + 'a>>
}
impl ResponseIrrigator for LambdaResponseIrrigator {
    fn map<'a>(&'a self, original_path: &'a Vec<String>, path: &'a Vec<String>, req: &'a Request<Vec<u8>>, res: &'a mut DroughtResult, mut map: &'a Matches) -> Pin<Box<dyn Future<Output = ()> + 'a>> {
        (self.func)(original_path, path, req, res, map)
    }
}

/// Storage for matches provided by typed or matched `Drought`s.
#[derive(Clone)]
pub struct Matches {
    map: HashMap<String, String>
}
impl Matches {
    pub(self) fn new() -> Self {
        Self { map: HashMap::new() }
    }
    pub(self) fn insert(&mut self, k: &str, v: &String) {
        self.map.insert(k.to_string(), v.clone());
    }
    /// Get something by key. T is the type to parse it to.
    pub fn get<T: FromStr>(&self, k: &str) -> Option<T> {
        self.map.get(&k.to_string()).and_then(|val| val.parse().ok())
    }
}

struct TestDrought;
impl Drought for TestDrought {
    fn handle<'a>(&'a self, original_path: &'a Vec<String>, path: &'a Vec<String>, req: &'a Request<Vec<u8>>, mut map: Matches) -> Pin<Box<dyn Future<Output = DroughtResult> + 'a>> {
        Box::pin(async{DroughtResult::NotFound})
    }
}

#[cfg(feature = "test")]
#[test]
fn construction() {
    use crate::simple;
    use lazy_regex::{regex, Lazy};
    
    let router_inner = DroughterBuilder::new()
        .build_with_lambda(simple!(|_,_,_,_| { "Test".into() }));

    let router = DroughterBuilder::new()
        .with_drought(0, TestDrought)
        .with_sub(3, "foo", router_inner.clone())
        .with_typed::<usize>(4, "usize", router_inner.clone())
        .with_matched(7, "regex", Lazy::force(regex!("^[A-Z]+$")).clone(), router_inner)
        .build();
}

macro_rules! path_body_test {
    ($router:ident, $path:literal, $teststr:literal) => {
        if let DroughterResult::Handle(res) = $router.run(&Request::builder().uri($path).body(vec![]).unwrap()).await {
            //println!("{res:#?}");
            assert_eq!(res.body(), $teststr);
        } else { panic!("Testing {} yielded non-`Handle` value!", $path) }
    }
}

#[cfg(feature = "test")]
#[test]
fn nesting() {
    use crate::simple;
    use lazy_regex::{regex, Lazy};
    use DroughterResult::*;

    let layer3_foo = DroughterBuilder::new()
        .build_with_lambda(simple!(|_,_,_,_| { "/?/?/foo!".into() }));
    let layer3_bar = DroughterBuilder::new()
        .build_with_lambda(simple!(|_,_,_,_| { "/?/?/bar!".into() }));
    let layer2_foo = DroughterBuilder::new()
        .with_sub(1, "foo", layer3_foo.clone())
        .with_sub(1, "bar", layer3_bar.clone())
        .build_with_lambda(simple!(|_,_,_,_| { "/?/foo!".into() }));
    let layer2_bar = DroughterBuilder::new()
        .with_sub(1, "foo", layer3_foo.clone())
        .with_sub(1, "bar", layer3_bar.clone())
        .build_with_lambda(simple!(|_,_,_,_| { "/?/bar!".into() }));
    let layer1_foo = DroughterBuilder::new()
        .with_sub(1, "foo", layer2_foo.clone())
        .with_sub(1, "bar", layer2_bar.clone())
        .build_with_lambda(simple!(|_,_,_,_| { "/foo!".into() }));
    let layer1_bar = DroughterBuilder::new()
        .with_sub(1, "foo", layer2_foo.clone())
        .with_sub(1, "bar", layer2_bar.clone())
        .build_with_lambda(simple!(|_,_,_,_| { "/bar!".into() }));
    let router = DroughterBuilder::new()
        .with_sub(1, "foo", layer1_foo.clone())
        .with_sub(1, "bar", layer1_bar.clone())
        .build_with_lambda(simple!(|_,_,_,_| { "/!".into() }));
    
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async {
            path_body_test!(router, "/", br#"/!"#);
            
            path_body_test!(router, "/foo", br#"/foo!"#);
            path_body_test!(router, "/bar", br#"/bar!"#);
            
            path_body_test!(router, "/foo/foo", br#"/?/foo!"#);
            path_body_test!(router, "/bar/foo", br#"/?/foo!"#);
            path_body_test!(router, "/foo/bar", br#"/?/bar!"#);
            path_body_test!(router, "/bar/bar", br#"/?/bar!"#);
            
            path_body_test!(router, "/foo/foo/foo", br#"/?/?/foo!"#);
            path_body_test!(router, "/bar/foo/foo", br#"/?/?/foo!"#);
            path_body_test!(router, "/foo/bar/foo", br#"/?/?/foo!"#);
            path_body_test!(router, "/bar/bar/foo", br#"/?/?/foo!"#);
            path_body_test!(router, "/foo/foo/bar", br#"/?/?/bar!"#);
            path_body_test!(router, "/bar/foo/bar", br#"/?/?/bar!"#);
            path_body_test!(router, "/foo/bar/bar", br#"/?/?/bar!"#);
            path_body_test!(router, "/bar/bar/bar", br#"/?/?/bar!"#);
        })
}

#[cfg(feature = "test")]
#[test]
fn irrigators() {
    use crate::{simple, lambda};
    use lazy_regex::{regex, Lazy};
    use DroughtResult::*;
    use IrrigatorResult::*;

    let layer1_foo = DroughterBuilder::new()
        .build_with_lambda(simple!(|_,_,_,_| { "/foo!".into() }));
    let layer1_bar = DroughterBuilder::new()
        .build_with_lambda(simple!(|_,_,_,_| { "/bar!".into() }));
    let router = DroughterBuilder::new()
        .with_sub(1, "foo", layer1_foo.clone())
        .with_sub(1, "bar", layer1_bar.clone())

        .with_request_irrigator_lambda(lambda!(|_,_,_,_| { Continue }))
        .with_request_irrigator_lambda(lambda!(|path,_,_,_| {
            if path == &vec!["bar".to_string()] { ContinueWithPath(vec!["foo".to_string()]) }
            else { Continue }
        }))
        
        .with_response_irrigator_lambda(lambda!(|_,_,_,dr,_| {
            match dr {
                Handle(ref mut res) => res.body_mut().push(b'~'),
                _ => ()
            }
        }))
        
        .build_with_lambda(simple!(|_,_,_,_| { "/!".into() }));
    
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async {
            path_body_test!(router, "/", br#"/!~"#);
            
            path_body_test!(router, "/foo", br#"/foo!~"#);
            path_body_test!(router, "/bar", br#"/foo!~"#);
        })
}

#[cfg(feature = "test")]
#[test]
fn matchers() {
    use crate::simple;
    use lazy_regex::{regex, Lazy};
    use DroughterResult::*;
    
    let router_usize = DroughterBuilder::new()
        .build_with_lambda(simple!(|_,_,_,map| { format!("matched usize: {:?}", map.get::<usize>("usize")).into() }));

    let router_regex2 = DroughterBuilder::new()
        .build_with_lambda(simple!(|_,_,_,map| { format!("matched regexes: {:?}, {:?}", map.get::<String>("regex"), map.get::<String>("regex2")).into() }));
    let router_regex = DroughterBuilder::new()
        .with_matched(1, "regex2", Lazy::force(regex!("^[A-Z0-9]+$")).clone(), router_regex2)
        .build_with_lambda(simple!(|_,_,_,map| { format!("matched regex: {:?}", map.get::<String>("regex")).into() }));

    let router = DroughterBuilder::new()
        .with_typed::<usize>(1, "usize", router_usize)
        .with_matched(2, "regex", Lazy::force(regex!("^[A-Z]+$")).clone(), router_regex)
        .build();
    
    tokio::runtime::Builder::new_current_thread()
        .enable_all()
        .build()
        .unwrap()
        .block_on(async {
            path_body_test!(router, "/TEST", br#"matched regex: Some("TEST")"#);
            path_body_test!(router, "/TEST/TEST2", br#"matched regexes: Some("TEST"), Some("TEST2")"#);
            path_body_test!(router, "/42", br#"matched usize: Some(42)"#);
            path_body_test!(router, "/00000", br#"matched usize: Some(0)"#);
        })
}