typeway-server 0.1.0

Server runtime for the typeway type-level 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
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
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
//! The type-safe [`Server`] builder and [`serve`] convenience function.

use std::convert::Infallible;
use std::future::Future;
use std::marker::PhantomData;
use std::net::SocketAddr;
use std::sync::Arc;

use hyper_util::rt::{TokioExecutor, TokioIo};
use tokio::net::TcpListener;

use typeway_core::ApiSpec;

use crate::body::BoxBody;
use crate::router::{Router, RouterService};
use crate::serves::Serves;

/// A type-safe HTTP server parameterized by an API specification.
///
/// The `A` type parameter is the API type — a tuple of endpoints. The server
/// ensures at compile time (via [`Serves`]) that every endpoint has a handler.
///
/// # Example
///
/// ```ignore
/// type API = (
///     GetEndpoint<path!("hello"), String>,
/// );
///
/// let server = Server::<API>::new((hello_handler,));
/// server.serve("127.0.0.1:3000".parse().unwrap()).await?;
/// ```
pub struct Server<A: ApiSpec> {
    router: Arc<Router>,
    _api: PhantomData<A>,
}

impl<A: ApiSpec> Server<A> {
    /// Create a new server with handlers covering the full API.
    ///
    /// Fails to compile if the handler tuple doesn't match the API type.
    pub fn new<H: Serves<A>>(handlers: H) -> Self {
        let mut router = Router::new();
        handlers.register(&mut router);
        Server {
            router: Arc::new(router),
            _api: PhantomData,
        }
    }

    /// Create a server from a pre-built router.
    ///
    /// Used internally by [`EffectfulServer::ready`](crate::effects::EffectfulServer).
    pub(crate) fn from_router(router: Arc<Router>) -> Self {
        Server {
            router,
            _api: PhantomData,
        }
    }

    /// Set a path prefix for all routes in this server.
    ///
    /// Only requests whose path starts with the prefix will match. The prefix
    /// is stripped before route matching.
    ///
    /// # Example
    ///
    /// ```ignore
    /// // Routes are /api/v1/hello, /api/v1/users, etc.
    /// Server::<API>::new(handlers)
    ///     .nest("/api/v1")
    ///     .serve(addr)
    ///     .await?;
    /// ```
    pub fn nest(self, prefix: &str) -> Self {
        self.router.set_prefix(prefix);
        self
    }

    /// Set the maximum request body size in bytes.
    ///
    /// Bodies exceeding this limit are rejected with 413 Payload Too Large.
    /// Default: 2 MiB (2,097,152 bytes).
    pub fn max_body_size(self, max: usize) -> Self {
        self.router.set_max_body_size(max);
        self
    }

    /// Add shared state accessible via [`State<T>`](crate::extract::State) extractors.
    pub fn with_state<T: Clone + Send + Sync + 'static>(self, state: T) -> Self {
        self.router.set_state_injector(Arc::new(move |ext| {
            ext.insert(state.clone());
        }));
        self
    }

    /// Enable OpenAPI spec serving at `/openapi.json` and Swagger UI at `/docs`.
    ///
    /// Requires `feature = "openapi"` and that the API type implements
    /// [`ApiToSpec`](typeway_openapi::ApiToSpec).
    ///
    /// # Example
    ///
    /// ```ignore
    /// Server::<API>::new(handlers)
    ///     .with_openapi("My API", "1.0.0")
    ///     .serve(addr)
    ///     .await?;
    /// ```
    #[cfg(feature = "openapi")]
    pub fn with_openapi(self, title: &str, version: &str) -> Self
    where
        A: typeway_openapi::ApiToSpec,
    {
        let spec = A::to_spec(title, version);
        let spec_json = std::sync::Arc::new(
            serde_json::to_string_pretty(&spec).expect("OpenAPI spec serialization failed"),
        );

        let router = &self.router;

        let spec_json_str =
            serde_json::to_string(&spec).expect("OpenAPI spec serialization failed");

        router.add_route(
            http::Method::GET,
            "/openapi.json".to_string(),
            crate::openapi::exact_match(&["openapi.json"]),
            crate::openapi::spec_handler(spec_json.clone()),
        );

        router.add_route(
            http::Method::GET,
            "/docs".to_string(),
            crate::openapi::exact_match(&["docs"]),
            crate::openapi::docs_handler(title, version, &spec_json_str),
        );

        self
    }

    /// Enable OpenAPI spec serving with handler documentation applied.
    ///
    /// Like [`with_openapi`](Self::with_openapi), but patches the generated
    /// spec with documentation metadata extracted from handler functions via
    /// the `#[documented_handler]` attribute macro.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use typeway_macros::documented_handler;
    ///
    /// /// List all users.
    /// ///
    /// /// Returns a paginated list of users with optional filtering.
    /// #[documented_handler(tags = "users")]
    /// async fn list_users() -> Json<Vec<User>> { /* ... */ }
    ///
    /// /// Get a user by ID.
    /// #[documented_handler(tags = "users")]
    /// async fn get_user(id: Path<u32>) -> Json<User> { /* ... */ }
    ///
    /// Server::<API>::new(handlers)
    ///     .with_openapi_docs("My API", "1.0.0", &[LIST_USERS_DOC, GET_USER_DOC])
    ///     .serve(addr)
    ///     .await?;
    /// ```
    #[cfg(feature = "openapi")]
    pub fn with_openapi_docs(
        self,
        title: &str,
        version: &str,
        docs: &[typeway_core::HandlerDoc],
    ) -> Self
    where
        A: typeway_openapi::ApiToSpec,
    {
        let mut spec = A::to_spec(title, version);
        typeway_openapi::apply_handler_docs(&mut spec, docs);

        let spec_json = std::sync::Arc::new(
            serde_json::to_string_pretty(&spec).expect("OpenAPI spec serialization failed"),
        );

        let router = &self.router;

        let spec_json_str =
            serde_json::to_string(&spec).expect("OpenAPI spec serialization failed");

        router.add_route(
            http::Method::GET,
            "/openapi.json".to_string(),
            crate::openapi::exact_match(&["openapi.json"]),
            crate::openapi::spec_handler(spec_json.clone()),
        );

        router.add_route(
            http::Method::GET,
            "/docs".to_string(),
            crate::openapi::exact_match(&["docs"]),
            crate::openapi::docs_handler(title, version, &spec_json_str),
        );

        self
    }

    /// Serve static files from a directory at a given URL prefix.
    ///
    /// Requests to `{prefix}/{path}` will serve files from `{dir}/{path}`.
    /// 404 is returned if the file doesn't exist.
    ///
    /// # Example
    ///
    /// ```ignore
    /// Server::<API>::new(handlers)
    ///     .with_static_files("/static", "./public")
    ///     .serve(addr)
    ///     .await?;
    /// ```
    pub fn with_static_files(self, prefix: &str, dir: impl Into<std::path::PathBuf>) -> Self {
        let dir: std::path::PathBuf = dir.into();
        let prefix_segments: Vec<String> = prefix
            .split('/')
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string())
            .collect();
        let prefix_len = prefix_segments.len();

        let router = &self.router;

        let dir = Arc::new(dir);
        let prefix_segs = Arc::new(prefix_segments);

        // Add a catch-all route for the prefix (matches /static, /static/, /static/foo).
        router.add_route(
            http::Method::GET,
            format!("{prefix}/{{*path}}"),
            {
                let prefix_segs = prefix_segs.clone();
                Box::new(move |segments: &[&str]| {
                    // Match: prefix exactly, or prefix + any file path
                    segments.len() >= prefix_segs.len()
                        && segments[..prefix_segs.len()]
                            .iter()
                            .zip(prefix_segs.iter())
                            .all(|(a, b)| *a == b.as_str())
                })
            },
            {
                let dir = dir.clone();
                std::sync::Arc::new(move |parts: http::request::Parts, _body: bytes::Bytes| {
                    let dir = dir.clone();
                    Box::pin(async move {
                        let path = parts.uri.path();
                        // Strip prefix to get the file path.
                        let file_path: String = path
                            .splitn(prefix_len + 2, '/')
                            .skip(prefix_len + 1)
                            .collect::<Vec<_>>()
                            .join("/");

                        // Prevent directory traversal.
                        if file_path.contains("..") {
                            let mut res = http::Response::new(crate::body::body_from_string(
                                "Forbidden".to_string(),
                            ));
                            *res.status_mut() = http::StatusCode::FORBIDDEN;
                            return res;
                        }

                        let full_path = if file_path.is_empty() {
                            // /static or /static/ → try index.html
                            dir.join("index.html")
                        } else {
                            let p = dir.join(&file_path);
                            // If it's a directory, try index.html inside it
                            if p.is_dir() {
                                p.join("index.html")
                            } else {
                                p
                            }
                        };

                        match tokio::fs::read(&full_path).await {
                            Ok(contents) => {
                                let mime = mime_from_path(&full_path);
                                let body =
                                    crate::body::body_from_bytes(bytes::Bytes::from(contents));
                                let mut res = http::Response::new(body);
                                if let Ok(val) = http::HeaderValue::from_str(mime) {
                                    res.headers_mut().insert(http::header::CONTENT_TYPE, val);
                                }
                                res
                            }
                            Err(_) => {
                                let mut res = http::Response::new(crate::body::body_from_string(
                                    "Not Found".to_string(),
                                ));
                                *res.status_mut() = http::StatusCode::NOT_FOUND;
                                res
                            }
                        }
                    }) as crate::handler::ResponseFuture
                })
            },
        );

        self
    }

    /// Serve a file as the fallback for unmatched routes (SPA mode).
    ///
    /// When no API route matches, the given file (typically `index.html`)
    /// is served. This enables client-side routing in single-page apps.
    ///
    /// # Example
    ///
    /// ```ignore
    /// Server::<API>::new(handlers)
    ///     .with_static_files("/static", "./public")
    ///     .with_spa_fallback("./public/index.html")
    ///     .serve(addr)
    ///     .await?;
    /// ```
    pub fn with_spa_fallback(self, index_path: impl Into<std::path::PathBuf>) -> Self {
        let index_path: std::path::PathBuf = index_path.into();

        // Try to read the file at startup. If it fails, serve an error page instead.
        let html = match std::fs::read_to_string(&index_path) {
            Ok(contents) => Arc::new(contents),
            Err(e) => {
                tracing::warn!(
                    "WARNING: SPA fallback file not found: {} ({}). \
                     Unmatched routes will show an error page.",
                    index_path.display(),
                    e
                );
                let error_page = format!(
                    "<!DOCTYPE html><html><body>\
                     <h1>Frontend Not Available</h1>\
                     <p>The SPA fallback file <code>{}</code> could not be loaded: {}</p>\
                     <p>If running locally, build the frontend first:</p>\
                     <pre>cd examples/realworld/frontend\nelm make src/Main.elm --output=public/elm.js</pre>\
                     </body></html>",
                    index_path.display(),
                    e
                );
                Arc::new(error_page)
            }
        };

        self.set_fallback_raw(Arc::new(move |req| {
            let html = html.clone();
            let path = req.uri().path().to_string();
            Box::pin(async move {
                // Don't serve SPA HTML for paths that look like file requests
                // (contain a dot in the last segment, e.g. /foo/bar.js).
                let last_segment = path.rsplit('/').next().unwrap_or("");
                if last_segment.contains('.') {
                    let mut res =
                        http::Response::new(crate::body::body_from_string("Not Found".to_string()));
                    *res.status_mut() = http::StatusCode::NOT_FOUND;
                    return res;
                }

                let body = crate::body::body_from_string(html.to_string());
                let mut res = http::Response::new(body);
                res.headers_mut().insert(
                    http::header::CONTENT_TYPE,
                    http::HeaderValue::from_static("text/html; charset=utf-8"),
                );
                res
            })
        }));

        self
    }

    /// Set a raw fallback function on the router.
    ///
    /// Used by `with_fallback` and `with_axum_fallback`.
    pub(crate) fn set_fallback_raw(&self, fallback: crate::router::FallbackService) {
        let router = &self.router;
        router.set_fallback(fallback);
    }

    /// Set a fallback Tower service for requests that don't match any typeway route.
    ///
    /// This enables embedding an Axum router (or any Tower service) inside
    /// a typeway server — the reverse of `into_axum_router()`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let axum_routes = axum::Router::new()
    ///     .route("/health", get(|| async { "ok" }));
    ///
    /// Server::<API>::new(handlers)
    ///     .with_fallback(axum_routes)
    ///     .serve(addr)
    ///     .await?;
    /// ```
    pub fn with_fallback<S>(self, service: S) -> Self
    where
        S: tower_service::Service<
                http::Request<hyper::body::Incoming>,
                Response = http::Response<BoxBody>,
                Error = Infallible,
            > + Clone
            + Send
            + Sync
            + 'static,
        S::Future: Send + 'static,
    {
        self.set_fallback_raw(Arc::new(
            move |req: http::Request<hyper::body::Incoming>| {
                let mut svc = service.clone();
                Box::pin(async move {
                    tower_service::Service::call(&mut svc, req)
                        .await
                        .unwrap_or_else(|e| match e {})
                })
            },
        ));
        self
    }

    /// Create a unified REST + gRPC server.
    ///
    /// Returns a [`GrpcServer`](crate::grpc::GrpcServer) that serves both REST
    /// and gRPC on the same port. Incoming requests with
    /// `content-type: application/grpc*` are translated to REST calls via the
    /// gRPC bridge, while all other requests are routed normally.
    ///
    /// Requires `feature = "grpc"`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// Server::<API>::new(handlers)
    ///     .with_state(state)
    ///     .with_grpc("UserService", "users.v1")
    ///     .serve("0.0.0.0:3000".parse()?)
    ///     .await?;
    /// ```
    #[cfg(feature = "grpc")]
    pub fn with_grpc(self, service_name: &str, package: &str) -> crate::grpc::GrpcServer<A>
    where
        A: typeway_grpc::CollectRpcs + typeway_grpc::GrpcReady,
    {
        crate::grpc::make_grpc_server(self.router, service_name, package)
    }

    /// Apply a Tower middleware layer to the server.
    ///
    /// The layer wraps the entire router service. This is the same API
    /// as Axum's `.layer()` — any `tower::Layer` that accepts the router
    /// service type can be used.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use tower_http::trace::TraceLayer;
    /// use tower_http::cors::CorsLayer;
    ///
    /// Server::<API>::new(handlers)
    ///     .layer(TraceLayer::new_for_http())
    ///     .layer(CorsLayer::permissive())
    ///     .serve(addr)
    ///     .await?;
    /// ```
    pub fn layer<L>(self, layer: L) -> LayeredServer<L::Service>
    where
        L: tower_layer::Layer<RouterService>,
        L::Service: tower_service::Service<
                http::Request<hyper::body::Incoming>,
                Response = http::Response<BoxBody>,
                Error = Infallible,
            > + Clone
            + Send
            + 'static,
        <L::Service as tower_service::Service<http::Request<hyper::body::Incoming>>>::Future:
            Send + 'static,
    {
        let router = self.router.clone();
        let svc = RouterService::new(self.router);
        let layered = layer.layer(svc);
        LayeredServer {
            service: layered,
            router,
        }
    }

    /// Start serving HTTPS with TLS.
    ///
    /// Requires `feature = "tls"`.
    ///
    /// ```ignore
    /// let tls = TlsConfig::from_pem("cert.pem", "key.pem")?;
    /// Server::<API>::new(handlers)
    ///     .serve_tls("0.0.0.0:443".parse()?, tls)
    ///     .await?;
    /// ```
    #[cfg(feature = "tls")]
    pub async fn serve_tls(
        self,
        addr: SocketAddr,
        tls: crate::tls::TlsConfig,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let listener = TcpListener::bind(addr).await?;
        tracing::info!("Listening on https://{addr}");
        let router = self.router.clone();
        crate::tls::serve_tls_loop(listener, tls, move || {
            hyper_util::service::TowerToHyperService::new(RouterService::new(router.clone()))
        })
        .await
    }

    /// Get the inner [`RouterService`] as a Tower service.
    pub fn into_service(self) -> RouterService {
        RouterService::new(self.router)
    }

    /// Get the inner router (for integration with other frameworks).
    pub fn into_router(self) -> Router {
        Arc::try_unwrap(self.router).unwrap_or_else(|_| {
            panic!("cannot unwrap router — it has been cloned");
        })
    }

    /// Start serving HTTP requests on the given address.
    pub async fn serve(
        self,
        addr: SocketAddr,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let listener = TcpListener::bind(addr).await?;
        tracing::info!("Listening on http://{addr}");
        self.serve_with_shutdown(listener, std::future::pending())
            .await
    }

    /// Start serving with graceful shutdown.
    ///
    /// Supports both HTTP/1.1 and HTTP/2 via automatic protocol detection.
    /// The server stops accepting new connections when the `shutdown` future
    /// completes. Existing connections are allowed to finish.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let server = Server::<API>::new(handlers);
    /// let listener = TcpListener::bind("0.0.0.0:3000").await?;
    ///
    /// server.serve_with_shutdown(listener, async {
    ///     tokio::signal::ctrl_c().await.ok();
    /// }).await?;
    /// ```
    pub async fn serve_with_shutdown(
        self,
        listener: TcpListener,
        shutdown: impl Future<Output = ()> + Send,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        tokio::pin!(shutdown);

        loop {
            tokio::select! {
                result = listener.accept() => {
                    let (stream, _) = result?;
                    let io = TokioIo::new(stream);
                    let svc = RouterService::new(self.router.clone());
                    let hyper_svc = hyper_util::service::TowerToHyperService::new(svc);

                    tokio::task::spawn(async move {
                        if let Err(e) = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
                            .serve_connection(io, hyper_svc)
                            .await
                        {
                            tracing::debug!("Connection closed: {e}");
                        }
                    });
                }
                () = &mut shutdown => {
                    tracing::info!("Shutting down gracefully...");
                    return Ok(());
                }
            }
        }
    }
}

/// A server with Tower middleware layers applied.
///
/// Created by [`Server::layer`]. Supports further `.layer()` calls and `.serve()`.
pub struct LayeredServer<S> {
    /// The layered service. Exposed for advanced use cases (e.g., manual serving).
    pub service: S,
    /// Reference to the underlying router for post-layer configuration.
    pub(crate) router: Arc<Router>,
}

impl<S> LayeredServer<S> {
    /// Add shared state accessible via [`State<T>`](crate::extract::State) extractors.
    pub fn with_state<T: Clone + Send + Sync + 'static>(self, state: T) -> Self {
        self.router.set_state_injector(Arc::new(move |ext| {
            ext.insert(state.clone());
        }));
        self
    }

    /// Set the maximum request body size.
    pub fn max_body_size(self, max: usize) -> Self {
        self.router.set_max_body_size(max);
        self
    }

    /// Set a path prefix for all routes.
    pub fn nest(self, prefix: &str) -> Self {
        self.router.set_prefix(prefix);
        self
    }

    /// Serve static files from a directory.
    pub fn with_static_files(self, prefix: &str, dir: impl Into<std::path::PathBuf>) -> Self {
        // Delegate to the shared router's add_route via the same logic as Server.
        let dir: std::path::PathBuf = dir.into();
        let prefix_segments: Vec<String> = prefix
            .split('/')
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string())
            .collect();
        let prefix_len = prefix_segments.len();
        let dir = Arc::new(dir);
        let prefix_segs = Arc::new(prefix_segments);

        self.router.add_route(
            http::Method::GET,
            format!("{prefix}/{{*path}}"),
            {
                let prefix_segs = prefix_segs.clone();
                Box::new(move |segments: &[&str]| {
                    segments.len() >= prefix_segs.len()
                        && segments[..prefix_segs.len()]
                            .iter()
                            .zip(prefix_segs.iter())
                            .all(|(a, b)| *a == b.as_str())
                })
            },
            {
                let dir = dir.clone();
                std::sync::Arc::new(move |parts: http::request::Parts, _body: bytes::Bytes| {
                    let dir = dir.clone();
                    Box::pin(async move {
                        let path = parts.uri.path();
                        let file_path: String = path
                            .splitn(prefix_len + 2, '/')
                            .skip(prefix_len + 1)
                            .collect::<Vec<_>>()
                            .join("/");
                        if file_path.contains("..") {
                            let mut res = http::Response::new(crate::body::body_from_string(
                                "Forbidden".to_string(),
                            ));
                            *res.status_mut() = http::StatusCode::FORBIDDEN;
                            return res;
                        }
                        let full_path = if file_path.is_empty() {
                            dir.join("index.html")
                        } else {
                            let p = dir.join(&file_path);
                            if p.is_dir() {
                                p.join("index.html")
                            } else {
                                p
                            }
                        };
                        match tokio::fs::read(&full_path).await {
                            Ok(contents) => {
                                let mime = mime_from_path(&full_path);
                                let body =
                                    crate::body::body_from_bytes(bytes::Bytes::from(contents));
                                let mut res = http::Response::new(body);
                                if let Ok(val) = http::HeaderValue::from_str(mime) {
                                    res.headers_mut().insert(http::header::CONTENT_TYPE, val);
                                }
                                res
                            }
                            Err(_) => {
                                let mut res = http::Response::new(crate::body::body_from_string(
                                    "Not Found".to_string(),
                                ));
                                *res.status_mut() = http::StatusCode::NOT_FOUND;
                                res
                            }
                        }
                    }) as crate::handler::ResponseFuture
                })
            },
        );
        self
    }

    /// Serve a file as SPA fallback for unmatched routes.
    pub fn with_spa_fallback(self, index_path: impl Into<std::path::PathBuf>) -> Self {
        let index_path: std::path::PathBuf = index_path.into();
        let html = match std::fs::read_to_string(&index_path) {
            Ok(contents) => Arc::new(contents),
            Err(e) => {
                tracing::warn!(
                    "WARNING: SPA fallback file not found: {} ({})",
                    index_path.display(),
                    e
                );
                Arc::new(format!(
                    "<!DOCTYPE html><html><body>\
                     <h1>Frontend Not Available</h1>\
                     <p><code>{}</code>: {}</p></body></html>",
                    index_path.display(),
                    e
                ))
            }
        };
        self.router.set_fallback(Arc::new(move |req| {
            let html = html.clone();
            let path = req.uri().path().to_string();
            Box::pin(async move {
                let last_segment = path.rsplit('/').next().unwrap_or("");
                if last_segment.contains('.') {
                    let mut res =
                        http::Response::new(crate::body::body_from_string("Not Found".to_string()));
                    *res.status_mut() = http::StatusCode::NOT_FOUND;
                    return res;
                }
                let body = crate::body::body_from_string(html.to_string());
                let mut res = http::Response::new(body);
                res.headers_mut().insert(
                    http::header::CONTENT_TYPE,
                    http::HeaderValue::from_static("text/html; charset=utf-8"),
                );
                res
            })
        }));
        self
    }
}

impl<S> LayeredServer<S>
where
    S: tower_service::Service<
            http::Request<hyper::body::Incoming>,
            Response = http::Response<BoxBody>,
            Error = Infallible,
        > + Clone
        + Send
        + 'static,
    S::Future: Send + 'static,
{
    /// Apply another Tower middleware layer.
    pub fn layer<L>(self, layer: L) -> LayeredServer<L::Service>
    where
        L: tower_layer::Layer<S>,
        L::Service: tower_service::Service<
                http::Request<hyper::body::Incoming>,
                Response = http::Response<BoxBody>,
                Error = Infallible,
            > + Clone
            + Send
            + 'static,
        <L::Service as tower_service::Service<http::Request<hyper::body::Incoming>>>::Future:
            Send + 'static,
    {
        LayeredServer {
            service: layer.layer(self.service),
            router: self.router,
        }
    }

    /// Start serving HTTP requests on the given address.
    pub async fn serve(
        self,
        addr: SocketAddr,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let listener = TcpListener::bind(addr).await?;
        tracing::info!("Listening on http://{addr}");
        self.serve_with_shutdown(listener, std::future::pending())
            .await
    }

    /// Start serving with graceful shutdown.
    pub async fn serve_with_shutdown(
        self,
        listener: TcpListener,
        shutdown: impl Future<Output = ()> + Send,
    ) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        tokio::pin!(shutdown);

        loop {
            tokio::select! {
                result = listener.accept() => {
                    let (stream, _) = result?;
                    let io = TokioIo::new(stream);
                    let svc = self.service.clone();
                    let hyper_svc = hyper_util::service::TowerToHyperService::new(svc);

                    tokio::task::spawn(async move {
                        if let Err(e) = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new())
                            .serve_connection(io, hyper_svc)
                            .await
                        {
                            tracing::debug!("Connection closed: {e}");
                        }
                    });
                }
                () = &mut shutdown => {
                    tracing::info!("Shutting down gracefully...");
                    return Ok(());
                }
            }
        }
    }
}

/// Convenience function to create and serve an API.
///
/// # Example
///
/// ```ignore
/// serve::<API, _>("127.0.0.1:3000".parse().unwrap(), (handler1, handler2)).await?;
/// ```
pub async fn serve<A: ApiSpec, H: Serves<A>>(
    addr: SocketAddr,
    handlers: H,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    Server::<A>::new(handlers).serve(addr).await
}

/// Guess MIME type from file extension.
fn mime_from_path(path: &std::path::Path) -> &'static str {
    match path.extension().and_then(|e| e.to_str()) {
        Some("html") | Some("htm") => "text/html; charset=utf-8",
        Some("css") => "text/css; charset=utf-8",
        Some("js") | Some("mjs") => "application/javascript; charset=utf-8",
        Some("json") => "application/json",
        Some("png") => "image/png",
        Some("jpg") | Some("jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("svg") => "image/svg+xml",
        Some("ico") => "image/x-icon",
        Some("woff") => "font/woff",
        Some("woff2") => "font/woff2",
        Some("ttf") => "font/ttf",
        Some("txt") => "text/plain; charset=utf-8",
        Some("xml") => "application/xml",
        Some("wasm") => "application/wasm",
        _ => "application/octet-stream",
    }
}