rama-http 0.3.0-rc1

rama http layers, services and other utilities
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
use crate::{
    Body, Request, Response, StatusCode,
    layer::error_handling::ErrorHandlerLayer,
    matcher::HttpMatcher,
    mime::Mime,
    service::{
        fs::{DirectoryServeMode, ServeDir},
        web::{
            IntoEndpointServiceWithState, endpoint::response::IntoResponse, response::ErrorResponse,
        },
    },
};

use rama_core::{
    Layer,
    extensions::Extensions,
    extensions::ExtensionsRef,
    matcher::Matcher,
    service::{BoxService, Service, service_fn},
    telemetry::tracing,
};
use rama_http_types::OriginalRouterUri;
use rama_net::uri::PathMatchOptions;
use rama_utils::{include_dir, str::arcstr::ArcStr};

use std::{convert::Infallible, path::Path, sync::Arc};

use super::{IntoEndpointService, endpoint::Endpoint};

type DefaultLayer = ErrorHandlerLayer;

/// A basic web service that can be used to serve HTTP requests.
///
/// Note that this service boxes all the internal services, so it is not as efficient as it could be.
/// For those locations where you need do not desire the convenience over performance,
/// you can instead use a tuple of `(M, S)` tuples, where M is a matcher and S is a service,
/// e.g. `((MethodMatcher::GET, service_a), (MethodMatcher::POST, service_b), service_fallback)`.
#[derive(Debug, Clone)]
pub struct WebService<State = ()> {
    endpoints: Vec<Arc<Endpoint>>,
    not_found: BoxService<Request, Response, Infallible>,
    state: State,
}

impl WebService {
    #[must_use]
    /// create a new web service
    pub fn new() -> Self {
        Self {
            endpoints: Vec::new(),
            not_found: service_fn(async || Ok(StatusCode::NOT_FOUND.into_response())).boxed(),
            state: (),
        }
    }
}

impl<State> WebService<State>
where
    State: Send + Sync + Clone + 'static,
{
    pub fn new_with_state(state: State) -> Self {
        Self {
            endpoints: Vec::new(),
            not_found: service_fn(async || Ok(StatusCode::NOT_FOUND.into_response())).boxed(),
            state,
        }
    }

    /// add a GET route to the web service, using the given service.
    #[must_use]
    #[inline]
    pub fn with_get<I, T>(self, path: &str, service: I) -> Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_get().and_path(path);
        self.with_matcher(matcher, service)
    }

    /// add a GET route to the web service, using the given service.
    #[inline]
    pub fn set_get<I, T>(&mut self, path: &str, service: I) -> &mut Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_get().and_path(path);
        self.set_matcher(matcher, service)
    }

    /// add a POST route to the web service, using the given service.
    #[must_use]
    #[inline]
    pub fn with_post<I, T>(self, path: &str, service: I) -> Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_post().and_path(path);
        self.with_matcher(matcher, service)
    }

    /// add a POST route to the web service, using the given service.
    #[inline]
    pub fn set_post<I, T>(&mut self, path: &str, service: I) -> &mut Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_post().and_path(path);
        self.set_matcher(matcher, service)
    }

    /// add a PUT route to the web service, using the given service.
    #[must_use]
    #[inline]
    pub fn with_put<I, T>(self, path: &str, service: I) -> Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_put().and_path(path);
        self.with_matcher(matcher, service)
    }

    /// add a PUT route to the web service, using the given service.
    #[inline]
    pub fn set_put<I, T>(&mut self, path: &str, service: I) -> &mut Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_put().and_path(path);
        self.set_matcher(matcher, service)
    }

    /// add a DELETE route to the web service, using the given service.
    #[must_use]
    #[inline]
    pub fn with_delete<I, T>(self, path: &str, service: I) -> Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_delete().and_path(path);
        self.with_matcher(matcher, service)
    }

    /// add a DELETE route to the web service, using the given service.
    #[inline]
    pub fn set_delete<I, T>(&mut self, path: &str, service: I) -> &mut Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_delete().and_path(path);
        self.set_matcher(matcher, service)
    }

    /// add a PATCH route to the web service, using the given service.
    #[must_use]
    #[inline]
    pub fn with_patch<I, T>(self, path: &str, service: I) -> Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_patch().and_path(path);
        self.with_matcher(matcher, service)
    }

    /// add a PATCH route to the web service, using the given service.
    #[inline]
    pub fn set_patch<I, T>(&mut self, path: &str, service: I) -> &mut Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_patch().and_path(path);
        self.set_matcher(matcher, service)
    }

    /// add a HEAD route to the web service, using the given service.
    #[must_use]
    #[inline]
    pub fn with_head<I, T>(self, path: &str, service: I) -> Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_head().and_path(path);
        self.with_matcher(matcher, service)
    }

    /// add a HEAD route to the web service, using the given service.
    #[inline]
    pub fn set_head<I, T>(&mut self, path: &str, service: I) -> &mut Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_head().and_path(path);
        self.set_matcher(matcher, service)
    }

    /// add a OPTIONS route to the web service, using the given service.
    #[must_use]
    #[inline]
    pub fn with_options<I, T>(self, path: &str, service: I) -> Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_options().and_path(path);
        self.with_matcher(matcher, service)
    }

    /// add a OPTIONS route to the web service, using the given service.
    #[inline]
    pub fn set_options<I, T>(&mut self, path: &str, service: I) -> &mut Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_options().and_path(path);
        self.set_matcher(matcher, service)
    }

    /// add a TRACE route to the web service, using the given service.
    #[must_use]
    #[inline]
    pub fn with_trace<I, T>(self, path: &str, service: I) -> Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_trace().and_path(path);
        self.with_matcher(matcher, service)
    }

    /// add a TRACE route to the web service, using the given service.
    #[inline]
    pub fn set_trace<I, T>(&mut self, path: &str, service: I) -> &mut Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let matcher = HttpMatcher::method_trace().and_path(path);
        self.set_matcher(matcher, service)
    }

    /// Nest a web service under the given path.
    ///
    /// The nested service will receive a request with the path prefix removed.
    ///
    /// Note: this sub-webservice is configured with the same State this router has.
    #[must_use]
    pub fn with_nest_make_fn(self, prefix: &str, configure_svc: impl FnOnce(Self) -> Self) -> Self {
        let web_service = Self::new_with_state(self.state.clone());
        let web_service = configure_svc(web_service);
        self.with_nest_inner(prefix, web_service)
    }

    /// Nest a web service under the given path.
    ///
    /// The nested service will receive a request with the path prefix removed.
    ///
    /// Note: this sub-webservice is configured with the same State this router has.
    pub fn set_nest_make_fn(
        &mut self,
        prefix: &str,
        configure_svc: impl FnOnce(Self) -> Self,
    ) -> &mut Self {
        let web_service = Self::new_with_state(self.state.clone());
        let web_service = configure_svc(web_service);
        self.set_nest_inner(prefix, web_service)
    }

    /// Nest a web service under the given path.
    ///
    /// The nested service will receive a request with the path prefix removed.
    ///
    /// Warning: This sub-service has no notion of the state this webservice has. If you want
    /// to create a nested-service that shares the same state this webservice has, use [WebService::set_nest_make_fn] instead.
    #[must_use]
    #[inline(always)]
    pub fn with_nest_service<I, T>(self, prefix: impl AsRef<str>, service: I) -> Self
    where
        I: IntoEndpointService<T>,
        I::Service: Service<Request, Output = Response, Error = Infallible>,
    {
        self.with_nest_inner(prefix, service.into_endpoint_service())
    }

    /// Nest a web service under the given path.
    ///
    /// The nested service will receive a request with the path prefix removed.
    ///
    /// Warning: This sub-service has no notion of the state this webservice has. If you want
    /// to create a nested-service that shares the same state this webservice has, use [WebService::set_nest_make_fn] instead.
    #[inline(always)]
    pub fn set_nest_service<I, T>(&mut self, prefix: impl AsRef<str>, service: I) -> &mut Self
    where
        I: IntoEndpointService<T>,
        I::Service: Service<Request, Output = Response, Error = Infallible>,
    {
        self.set_nest_inner(prefix, service.into_endpoint_service())
    }

    #[inline]
    fn with_nest_inner<S>(mut self, prefix: impl AsRef<str>, inner: S) -> Self
    where
        S: Service<Request, Output = Response, Error = Infallible>,
    {
        self.set_nest_inner(prefix, inner);
        self
    }

    fn set_nest_inner<S>(&mut self, prefix: impl AsRef<str>, inner: S) -> &mut Self
    where
        S: Service<Request, Output = Response, Error = Infallible>,
    {
        let prefix = prefix
            .as_ref()
            .trim_end_matches(['/', '*'])
            .trim_start_matches('/');
        let matcher = HttpMatcher::path_prefix(prefix);
        let service = NestedService {
            inner,
            prefix: ArcStr::from(prefix),
        };
        self.set_matcher(matcher, service)
    }

    /// serve the given file under the given path.
    #[must_use]
    pub fn with_file(self, prefix: &str, path: impl AsRef<Path>, mime: Mime) -> Self {
        let service = ServeDir::new_single_file(path, mime).fallback(self.not_found.clone());
        self.with_nest_inner(prefix, service)
    }

    /// serve the given file under the given path.
    pub fn set_file(&mut self, prefix: &str, path: impl AsRef<Path>, mime: Mime) -> &mut Self {
        let service = ServeDir::new_single_file(path, mime).fallback(self.not_found.clone());
        self.set_nest_inner(prefix, service)
    }

    /// serve the given directory under the given path.
    #[inline]
    #[must_use]
    pub fn with_dir(self, prefix: &str, path: impl AsRef<Path>) -> Self {
        self.with_dir_with_serve_mode(prefix, path, Default::default())
    }

    /// serve the given directory under the given path.
    #[inline]
    pub fn set_dir(&mut self, prefix: &str, path: impl AsRef<Path>) -> &mut Self {
        self.set_dir_with_serve_mode(prefix, path, Default::default())
    }

    /// serve the given directory under the given path,
    /// with a custom serve move.
    #[must_use]
    pub fn with_dir_with_serve_mode(
        self,
        prefix: &str,
        path: impl AsRef<Path>,
        mode: DirectoryServeMode,
    ) -> Self {
        let service = ServeDir::new(path)
            .fallback(self.not_found.clone())
            .with_directory_serve_mode(mode);
        self.with_nest_service(prefix, service)
    }

    /// serve the given directory under the given path,
    /// with a custom serve move.
    pub fn set_dir_with_serve_mode(
        &mut self,
        prefix: &str,
        path: impl AsRef<Path>,
        mode: DirectoryServeMode,
    ) -> &mut Self {
        let service = ServeDir::new(path)
            .fallback(self.not_found.clone())
            .with_directory_serve_mode(mode);
        self.set_nest_service(prefix, service)
    }

    /// serve the given embedded directory under the given path.
    #[inline]
    #[must_use]
    pub fn with_dir_embed(self, prefix: &str, dir: include_dir::Dir<'static>) -> Self {
        self.with_dir_embed_with_serve_mode(prefix, dir, Default::default())
    }

    /// serve the given embedded directory under the given path.
    #[inline]
    pub fn set_dir_embed(&mut self, prefix: &str, dir: include_dir::Dir<'static>) -> &mut Self {
        self.set_dir_embed_with_serve_mode(prefix, dir, Default::default())
    }

    /// serve the given embedded directory under the given path
    /// with a custom serve move.
    #[must_use]
    pub fn with_dir_embed_with_serve_mode(
        self,
        prefix: &str,
        dir: include_dir::Dir<'static>,
        mode: DirectoryServeMode,
    ) -> Self {
        let service = ServeDir::new_embedded(dir)
            .fallback(self.not_found.clone())
            .with_directory_serve_mode(mode);
        self.with_nest_service(prefix, service)
    }

    /// serve the given embedded directory under the given path
    /// with a custom serve move.
    pub fn set_dir_embed_with_serve_mode(
        &mut self,
        prefix: &str,
        dir: include_dir::Dir<'static>,
        mode: DirectoryServeMode,
    ) -> &mut Self {
        let service = ServeDir::new_embedded(dir)
            .fallback(self.not_found.clone())
            .with_directory_serve_mode(mode);
        self.set_nest_service(prefix, service)
    }

    /// add a route to the web service which matches the given matcher, using the given service.
    #[must_use]
    pub fn with_matcher<I, T>(mut self, matcher: HttpMatcher<Body>, service: I) -> Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let endpoint = Endpoint {
            matcher,
            service: DefaultLayer::default()
                .into_layer(service.into_endpoint_service_with_state(self.state.clone()))
                .boxed(),
        };
        self.endpoints.push(Arc::new(endpoint));
        self
    }

    /// add a route to the web service which matches the given matcher, using the given service.
    pub fn set_matcher<I, T>(&mut self, matcher: HttpMatcher<Body>, service: I) -> &mut Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        let endpoint = Endpoint {
            matcher,
            service: DefaultLayer::default()
                .into_layer(service.into_endpoint_service_with_state(self.state.clone()))
                .boxed(),
        };
        self.endpoints.push(Arc::new(endpoint));
        self
    }

    /// use the given service in case no match could be found.
    #[must_use]
    pub fn with_not_found<I, T>(mut self, service: I) -> Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        self.not_found = DefaultLayer::default()
            .into_layer(service.into_endpoint_service_with_state(self.state.clone()))
            .boxed();
        self
    }

    /// use the given service in case no match could be found.
    pub fn set_not_found<I, T>(&mut self, service: I) -> &mut Self
    where
        I: IntoEndpointServiceWithState<T, State>,
        I::Service: Service<Request, Output: IntoResponse, Error: Into<ErrorResponse>>,
    {
        self.not_found = DefaultLayer::default()
            .into_layer(service.into_endpoint_service_with_state(self.state.clone()))
            .boxed();
        self
    }
}

#[derive(Debug, Clone)]
struct NestedService<S> {
    inner: S,
    prefix: ArcStr,
}

impl<S> Service<Request> for NestedService<S>
where
    S: Service<Request>,
{
    type Output = S::Output;
    type Error = S::Error;

    fn serve(
        &self,
        req: Request,
    ) -> impl Future<Output = Result<Self::Output, Self::Error>> + Send + '_ {
        // set the nested path
        let (mut parts, body) = req.into_parts();

        let original_uri = parts.uri.clone();
        if parts.uri.path_mut().strip_prefix_with_opts(
            self.prefix.as_str(),
            PathMatchOptions {
                ignore_ascii_case: true,
                ..Default::default()
            },
        ) {
            if !parts.extensions.contains::<OriginalRouterUri>() {
                parts.extensions.insert(OriginalRouterUri(original_uri));
            }
        } else {
            tracing::debug!(
                "failed to strip prefix '{}' from Uri (bug??) preserve og uri as is",
                self.prefix,
            );
        }

        let req = Request::from_parts(parts, body);

        // make the actual request
        self.inner.serve(req)
    }
}

impl Default for WebService {
    fn default() -> Self {
        Self::new()
    }
}

impl<State> Service<Request> for WebService<State>
where
    State: Send + Sync + Clone + 'static,
{
    type Output = Response;
    type Error = Infallible;

    async fn serve(&self, req: Request) -> Result<Self::Output, Self::Error> {
        for endpoint in &self.endpoints {
            let ext = Extensions::new();
            if endpoint.matcher.matches(Some(&ext), &req) {
                // insert the extensions that might be generated by the matcher(s) into the context
                req.extensions().extend(&ext);
                return endpoint.service.serve(req).await;
            }
        }
        self.not_found.serve(req).await
    }
}

#[doc(hidden)]
#[macro_export]
/// Create a new [`Service`] from a chain of matcher-service tuples.
///
/// Think of it like the Rust match statement, but for http services.
/// Which is nothing more then a convenient wrapper to create a tuple of matcher-service tuples,
/// with the last tuple being the fallback service. And all services implement
/// the [`IntoEndpointService`] trait.
///
/// # Example
///
/// ```rust
/// use rama_http::matcher::{HttpMatcher, MethodMatcher};
/// use rama_http::{Body, Request, Response, StatusCode};
/// use rama_http::body::util::BodyExt;
/// use rama_core::{Service};
///
/// #[tokio::main]
/// async fn main() {
///   let svc = rama_http::service::web::match_service! {
///     HttpMatcher::get("/hello") => "hello",
///     HttpMatcher::post("/world") => "world",
///     MethodMatcher::CONNECT => "connect",
///     _ => StatusCode::NOT_FOUND,
///   };
///
///   let resp = svc.serve(
///       Request::post("https://www.test.io/world").body(Body::empty()).unwrap(),
///   ).await.unwrap();
///   assert_eq!(resp.status(), StatusCode::OK);
///   let body = resp.into_body().collect().await.unwrap().to_bytes();
///   assert_eq!(body, "world");
/// }
/// ```
///
/// Which is short for the following:
///
/// ```rust
/// use rama_http::matcher::{HttpMatcher, MethodMatcher};
/// use rama_http::{Body, Request, Response, StatusCode};
/// use rama_http::body::util::BodyExt;
/// use rama_http::service::web::IntoEndpointService;
/// use rama_http::layer::error_handling::ErrorHandler;
/// use rama_core::{Service};
/// use rama_core::matcher::MatcherRouter;
///
/// #[tokio::main]
/// async fn main() {
///   let svc = MatcherRouter((
///     (HttpMatcher::get("/hello"), ErrorHandler::new("hello".into_endpoint_service())),
///     (HttpMatcher::post("/world"), ErrorHandler::new("world".into_endpoint_service())),
///     (MethodMatcher::CONNECT, ErrorHandler::new("connect".into_endpoint_service())),
///     ErrorHandler::new(StatusCode::NOT_FOUND.into_endpoint_service()),
///   ));
///
///   let resp = svc.serve(
///
///      Request::post("https://www.test.io/world").body(Body::empty()).unwrap(),
///   ).await.unwrap();
///   assert_eq!(resp.status(), StatusCode::OK);
///   let body = resp.into_body().collect().await.unwrap().to_bytes();
///   assert_eq!(body, "world");
/// }
/// ```
///
/// As you can see it is pretty much the same, except that you need to explicitly ensure
/// that each service is an actual Endpoint service.
macro_rules! __match_service {
    ($($M:expr_2021 => $S:expr_2021),+, _ => $F:expr $(,)?) => {{
        use $crate::service::web::IntoEndpointService;
        use $crate::layer::error_handling::ErrorHandler;
        use $crate::__macro_dep::__core::matcher::MatcherRouter;
        MatcherRouter((
            $(($M, ErrorHandler::new($S.into_endpoint_service()))),+,
            ErrorHandler::new($F.into_endpoint_service()))
        )
    }};
}

#[doc(inline)]
pub use crate::__match_service as match_service;

#[cfg(test)]
mod test {
    use crate::matcher::MethodMatcher;
    use crate::service::web::extract::State;
    use crate::{Body, body::util::BodyExt};

    use super::*;

    async fn get_response<S>(service: &S, uri: &str) -> Response
    where
        S: Service<Request, Output = Response, Error = Infallible>,
    {
        let req = Request::get(uri).body(Body::empty()).unwrap();
        service.serve(req).await.unwrap()
    }

    async fn post_response<S>(service: &S, uri: &str) -> Response
    where
        S: Service<Request, Output = Response, Error = Infallible>,
    {
        let req = Request::post(uri).body(Body::empty()).unwrap();
        service.serve(req).await.unwrap()
    }

    async fn connect_response<S>(service: &S, uri: &str) -> Response
    where
        S: Service<Request, Output = Response, Error = Infallible>,
    {
        let req = Request::connect(uri).body(Body::empty()).unwrap();
        service.serve(req).await.unwrap()
    }

    #[tokio::test]
    async fn test_web_service() {
        let svc = WebService::new()
            .with_get("/hello", "hello")
            .with_post("/world", "world");

        let res = get_response(&svc, "https://www.test.io/hello").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "hello");

        let res = post_response(&svc, "https://www.test.io/world").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "world");

        let res = get_response(&svc, "https://www.test.io/world").await;
        assert_eq!(res.status(), StatusCode::NOT_FOUND);

        let res = get_response(&svc, "https://www.test.io").await;
        assert_eq!(res.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_web_service_not_found() {
        let svc = WebService::new().with_not_found("not found");

        let res = get_response(&svc, "https://www.test.io/hello").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "not found");
    }

    #[tokio::test]
    async fn test_web_service_nest() {
        let state = "state".to_owned();

        let svc = WebService::new_with_state(state)
            .with_get("/state", async |State(state): State<String>| state)
            .with_nest_make_fn("/api", |web| {
                web.with_get("/hello", "hello")
                    .with_post("/world", "world")
                    .with_get("/state", async |State(state): State<String>| state)
            });

        let res = get_response(&svc, "https://www.test.io/api/hello").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "hello");

        let res = post_response(&svc, "https://www.test.io/api/world").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "world");

        let res = get_response(&svc, "https://www.test.io/api/world").await;
        assert_eq!(res.status(), StatusCode::NOT_FOUND);

        let res = get_response(&svc, "https://www.test.io").await;
        assert_eq!(res.status(), StatusCode::NOT_FOUND);

        let res = get_response(&svc, "https://www.test.io/state").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "state");

        let res = get_response(&svc, "https://www.test.io/api/state").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "state");
    }

    #[tokio::test]
    async fn test_web_service_dir() {
        let tmp_dir = tempfile::tempdir().unwrap();
        let file_path = tmp_dir.path().join("index.html");
        std::fs::write(&file_path, "<h1>Hello, World!</h1>").unwrap();
        let style_dir = tmp_dir.path().join("style");
        std::fs::create_dir(&style_dir).unwrap();
        let file_path = style_dir.join("main.css");
        std::fs::write(&file_path, "body { background-color: red }").unwrap();

        let svc = WebService::new()
            .with_get("/api/version", "v1")
            .with_post("/api", StatusCode::FORBIDDEN)
            .with_dir("/", tmp_dir.path().to_str().unwrap());

        let res = get_response(&svc, "https://www.test.io/index.html").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "<h1>Hello, World!</h1>");

        let res = get_response(&svc, "https://www.test.io/style/main.css").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "body { background-color: red }");

        let res = get_response(&svc, "https://www.test.io/api/version").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "v1");

        let res = post_response(&svc, "https://www.test.io/api").await;
        assert_eq!(res.status(), StatusCode::FORBIDDEN);

        let res = get_response(&svc, "https://www.test.io/notfound.html").await;
        assert_eq!(res.status(), StatusCode::NOT_FOUND);

        let res = get_response(&svc, "https://www.test.io/").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "<h1>Hello, World!</h1>");
    }

    #[tokio::test]
    async fn test_matcher_service_tuples() {
        let svc = match_service! {
            HttpMatcher::get("/hello") => "hello",
            HttpMatcher::post("/world") => "world",
            MethodMatcher::CONNECT => "connect",
            _ => StatusCode::NOT_FOUND,
        };

        let res = get_response(&svc, "https://www.test.io/hello").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "hello");

        let res = post_response(&svc, "https://www.test.io/world").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "world");

        let res = connect_response(&svc, "https://www.test.io").await;
        assert_eq!(res.status(), StatusCode::OK);
        let body = res.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "connect");

        let res = get_response(&svc, "https://www.test.io/world").await;
        assert_eq!(res.status(), StatusCode::NOT_FOUND);

        let res = get_response(&svc, "https://www.test.io").await;
        assert_eq!(res.status(), StatusCode::NOT_FOUND);
    }
}