glacier-web 0.1.1

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
//! The application builder and the HTTP server.

use std::any::Any;
use std::convert::Infallible;
use std::future::Future;
use std::panic::AssertUnwindSafe;
use std::sync::Arc;
use std::time::Duration;

use bytes::Bytes;
use futures_util::FutureExt;
use http::{Extensions, Method, StatusCode, header};
use http_body_util::{BodyExt, Full, LengthLimitError, Limited};
use hyper::body::Incoming;
use hyper::service::service_fn;
use hyper_util::rt::{TokioExecutor, TokioIo};
use hyper_util::server::conn::auto;
use hyper_util::server::graceful::GracefulShutdown;
use tokio::net::{TcpListener, ToSocketAddrs};
use tracing::Instrument;
use tracing::field::Empty;

use crate::config::{Config, Env};
use crate::context::Context;
use crate::cookies::{Cookies, Key};
use crate::db::migration::{Migration, Migrator};
use crate::db::{self, Repo};
use crate::error::{Error, ErrorReport, Result};
use crate::handler::{BoxFuture, Handler};
use crate::html::escape;
use crate::middleware::{Middleware, Next};
use crate::request;
use crate::response::{IntoResponse, Response};
use crate::router::{Match, Router};
use crate::session::Session;
use crate::telemetry::Telemetry;

const DEFAULT_MAX_BODY_SIZE: usize = 2 * 1024 * 1024;
const SHUTDOWN_GRACE_PERIOD: Duration = Duration::from_secs(10);
const MIN_SECRET_LEN: usize = 32;
const HEALTH_CHECK_PATH: &str = "/up";
/// How long `/up` waits for the database before reporting it down.
const HEALTH_CHECK_TIMEOUT: Duration = Duration::from_secs(2);

/// Set by the CLI (`glacier routes`, `glacier db migrate`, ...) to run a
/// task instead of serving.
const TASK_VAR: &str = "GLACIER_TASK";

/// Configures an application: routes, middleware and shared state.
pub struct App {
    router: Router,
    middleware: Vec<Arc<dyn Middleware>>,
    state: Extensions,
    max_body_size: usize,
    pub(crate) env: Option<Env>,
    key: Option<Key>,
    repo: Option<Repo>,
    migrations: Vec<Migration>,
    health_check: Option<String>,
    telemetry: Vec<Telemetry>,
}

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

impl App {
    pub fn new() -> Self {
        Self {
            router: Router::new(),
            middleware: Vec::new(),
            state: Extensions::new(),
            max_body_size: DEFAULT_MAX_BODY_SIZE,
            env: None,
            key: None,
            repo: None,
            migrations: Vec::new(),
            health_check: Some(HEALTH_CHECK_PATH.into()),
            telemetry: Vec::new(),
        }
    }

    /// Sends traces somewhere besides the logs, e.g. an OpenTelemetry
    /// collector: `.telemetry(glacier_otel::from_env("blog")?)`. Installed
    /// when the app starts serving, and flushed when it stops.
    pub fn telemetry(mut self, telemetry: Telemetry) -> Self {
        if telemetry.is_enabled() {
            self.telemetry.push(telemetry);
        }
        self
    }

    /// Serves the health check at `path` instead of `/up`.
    ///
    /// The health check answers `GET` (and `HEAD`) with `200 ok` when the
    /// app is up and its database answers, or `503` when the database
    /// doesn't within two seconds, so a deploy agent or load balancer knows
    /// when to send traffic. It runs before any middleware: no logging, no
    /// cookies, no HTTPS redirect. A route of the app's own at the same path
    /// takes its place.
    pub fn health_check(mut self, path: &str) -> Self {
        self.health_check = Some(path.into());
        self
    }

    /// Turns the built-in health check off.
    pub fn without_health_check(mut self) -> Self {
        self.health_check = None;
        self
    }

    /// Applies a loaded `Config`: environment, `secret_key_base` and
    /// `server.max_body_size`. The config is also registered as state, so
    /// handlers can read it with `ctx.state::<Config>()`.
    pub fn config(mut self, config: Config) -> Result<Self> {
        self.env = Some(config.env());
        if let Some(secret) = config.get_opt::<String>("secret_key_base")? {
            self = self.secret_key_base(&secret)?;
        }
        if let Some(size) = config.get_opt::<usize>("server.max_body_size")? {
            self.max_body_size = size;
        }
        Ok(self.state(config))
    }

    /// The secret that signs and encrypts cookies (including the session).
    /// Without one, a random key is generated per boot, which logs everyone
    /// out on restart; that's refused in production.
    pub fn secret_key_base(mut self, secret: &str) -> Result<Self> {
        if secret.len() < MIN_SECRET_LEN {
            return Err(Error::internal(format!(
                "secret_key_base must be at least {MIN_SECRET_LEN} bytes"
            )));
        }
        self.key = Some(Key::derive_from(secret.as_bytes()));
        Ok(self)
    }

    /// Makes `repo` the ambient database for every request, so model calls
    /// need no connection argument. It's also registered as state.
    pub fn database(mut self, repo: Repo) -> Self {
        self.repo = Some(repo.clone());
        self.state(repo)
    }

    /// Registers the app's migrations (usually `migrations::all()`), so
    /// `glacier db migrate` can run them and development warns about
    /// pending ones.
    pub fn migrations(mut self, migrations: Vec<Migration>) -> Self {
        self.migrations = migrations;
        self
    }

    /// Overrides the environment, which otherwise comes from the config or
    /// `GLACIER_ENV`.
    pub fn env(mut self, env: Env) -> Self {
        self.env = Some(env);
        self
    }

    pub fn routes(mut self, draw: impl FnOnce(&mut Router)) -> Self {
        draw(&mut self.router);
        self
    }

    /// Adds middleware that wraps every request, including 404s. The first
    /// one added is the outermost. For middleware on some routes only, see
    /// `Router::pipe_through`.
    pub fn middleware(mut self, middleware: impl Middleware) -> Self {
        self.middleware.push(Arc::new(middleware));
        self
    }

    /// The background jobs the app runs: `serve` starts their workers on
    /// the app's database. Also registered as state, for tests
    /// (`TestClient::perform_jobs`).
    pub fn jobs(self, jobs: crate::jobs::Jobs) -> Self {
        self.state(jobs)
    }

    /// Registers shared state, retrieved in handlers with `ctx.state::<T>()`.
    /// One value per type; registering a type twice replaces the first.
    pub fn state<T: Clone + Send + Sync + 'static>(mut self, value: T) -> Self {
        self.state.insert(value);
        self
    }

    /// Requests with larger bodies are rejected with `413 Payload Too Large`.
    pub fn max_body_size(mut self, bytes: usize) -> Self {
        self.max_body_size = bytes;
        self
    }

    /// Freezes the configuration into a cheaply cloneable `Service`.
    pub fn build(self) -> Service {
        // The app's own route at the health check's path wins.
        let health_check = self
            .health_check
            .filter(|path| !self.router.routes().iter().any(|r| r.pattern() == path));
        let router = Arc::new(self.router);
        let env = self.env.unwrap_or_else(Env::current);
        Service {
            inner: Arc::new(Inner {
                stack: self.middleware.into(),
                endpoint: Arc::new(Dispatcher(router.clone())),
                router,
                state: Arc::new(self.state),
                max_body_size: self.max_body_size,
                env,
                has_secret: self.key.is_some(),
                repo: self.repo,
                migrations: self.migrations,
                health_check,
                telemetry: std::sync::Mutex::new(self.telemetry),
                key: Arc::new(self.key.unwrap_or_else(Key::generate)),
            }),
        }
    }

    /// Builds the app and serves it until Ctrl-C or SIGTERM.
    pub async fn serve(self, addr: impl ToSocketAddrs) -> Result<()> {
        self.build().serve(addr).await
    }
}

/// A built application, ready to handle requests.
#[derive(Clone)]
pub struct Service {
    inner: Arc<Inner>,
}

struct Inner {
    stack: Arc<[Arc<dyn Middleware>]>,
    endpoint: Arc<dyn Handler>,
    router: Arc<Router>,
    state: Arc<Extensions>,
    max_body_size: usize,
    env: Env,
    has_secret: bool,
    key: Arc<Key>,
    repo: Option<Repo>,
    migrations: Vec<Migration>,
    health_check: Option<String>,
    /// Taken by `serve`, which installs it.
    telemetry: std::sync::Mutex<Vec<Telemetry>>,
}

impl Service {
    /// Shared state registered with `App::state`.
    pub(crate) fn state<T: Send + Sync + 'static>(&self) -> Option<&T> {
        self.inner.state.get::<T>()
    }

    pub fn router(&self) -> &Router {
        &self.inner.router
    }

    pub fn env(&self) -> Env {
        self.inner.env
    }

    /// Runs one request through middleware and the router. Panics in
    /// handlers are caught and turned into a 500.
    pub async fn call(&self, req: http::Request<Bytes>) -> Response {
        if self.is_health_check(&req) {
            return self.health().await;
        }
        let (parts, body) = req.into_parts();
        let method = parts.method.clone();
        let path = parts.uri.path().to_owned();
        let cookies = Cookies::from_headers(&parts.headers, self.inner.key.clone());
        let session = Session::new(cookies.clone(), self.inner.env.is_production());
        let scope = request::Scope {
            session: session.clone(),
            path: path.clone(),
            base_url: request::base_url_of(&parts),
            query: parts.uri.query().map(str::to_owned),
        };
        let ctx = Context::new(
            parts,
            body,
            self.inner.state.clone(),
            cookies.clone(),
            session.clone(),
        );
        let next = Next::new(self.inner.stack.clone(), self.inner.endpoint.clone());

        // The request's span, named and fielded per OpenTelemetry's HTTP
        // conventions; the router fills in `http.route` when it matches.
        let span = tracing::info_span!(
            target: "glacier",
            "glacier.request",
            otel.name = %method,
            otel.kind = "server",
            otel.status_code = Empty,
            http.request.method = %method,
            url.path = %path,
            http.route = Empty,
            http.response.status_code = Empty,
        );
        let run = request::scope(scope, next.run(ctx)).instrument(span.clone());
        // Keep an already-active connection (e.g. a test sandbox's
        // transaction) rather than replacing it with the app's repo.
        let result = match &self.inner.repo {
            Some(repo) if !db::active() => {
                AssertUnwindSafe(db::scope(repo.into(), run))
                    .catch_unwind()
                    .await
            }
            _ => AssertUnwindSafe(run).catch_unwind().await,
        };
        let mut res = match result {
            Ok(res) => res,
            Err(panic) => span.in_scope(|| {
                Error::internal(format!("panic: {}", panic_message(&*panic))).into_response()
            }),
        };
        // i64: OpenTelemetry has no unsigned integers.
        span.record(
            "http.response.status_code",
            i64::from(res.status().as_u16()),
        );
        if res.status().is_server_error() {
            span.record("otel.status_code", "ERROR");
        }

        let is_json = res
            .header(header::CONTENT_TYPE)
            .is_some_and(|ct| ct.starts_with("application/json"));
        // APIs keep their JSON error; the HTML page is for browsers.
        if self.inner.env.is_development()
            && res.status().is_server_error()
            && !is_json
            && let Some(report) = res.extensions().get::<ErrorReport>()
        {
            res = debug_page(report, &method, &path);
        }
        session.commit();
        cookies.write_to(res.headers_mut());
        res
    }

    fn is_health_check(&self, req: &http::Request<Bytes>) -> bool {
        matches!(*req.method(), Method::GET | Method::HEAD)
            && self.inner.health_check.as_deref() == Some(req.uri().path())
    }

    /// `200 ok` when the database (if any) answers in time, else `503`.
    async fn health(&self) -> Response {
        let database = match &self.inner.repo {
            None => Ok(()),
            Some(repo) => {
                let ping = db::sql("SELECT 1").on(repo).execute();
                match tokio::time::timeout(HEALTH_CHECK_TIMEOUT, ping).await {
                    Ok(Ok(_)) => Ok(()),
                    Ok(Err(err)) => Err(err.to_string()),
                    Err(_) => Err("timed out".to_owned()),
                }
            }
        };
        let mut res = match database {
            Ok(()) => Response::text("ok"),
            Err(reason) => {
                tracing::warn!(target: "glacier", reason, "health check: database unavailable");
                Response::text("database unavailable").with_status(StatusCode::SERVICE_UNAVAILABLE)
            }
        };
        res.headers_mut().insert(
            header::CACHE_CONTROL,
            http::HeaderValue::from_static("no-store"),
        );
        res
    }

    async fn call_hyper(&self, req: hyper::Request<Incoming>) -> http::Response<Full<Bytes>> {
        let (parts, body) = req.into_parts();
        let body = match Limited::new(body, self.inner.max_body_size).collect().await {
            Ok(collected) => collected.to_bytes(),
            Err(err) if err.is::<LengthLimitError>() => {
                return Response::text("Payload Too Large")
                    .with_status(StatusCode::PAYLOAD_TOO_LARGE)
                    .into_http();
            }
            Err(err) => {
                tracing::debug!("failed to read request body: {err}");
                return Response::text("Bad Request")
                    .with_status(StatusCode::BAD_REQUEST)
                    .into_http();
            }
        };
        self.call(http::Request::from_parts(parts, body))
            .await
            .into_http()
    }

    /// Binds `addr` and serves until Ctrl-C or SIGTERM.
    pub async fn serve(self, addr: impl ToSocketAddrs) -> Result<()> {
        if let Ok(task) = std::env::var(TASK_VAR) {
            return self.run_task(&task).await;
        }
        let telemetry = std::mem::take(&mut *self.inner.telemetry.lock().unwrap());
        let guard = crate::telemetry::init(self.inner.env, telemetry);
        self.warn_about_pending_migrations().await;
        if let (Some(jobs), Some(repo)) = (
            self.inner.state.get::<crate::jobs::Jobs>(),
            self.inner.repo.clone(),
        ) {
            jobs.start(repo);
        }
        let listener = TcpListener::bind(addr).await?;
        let served = self.serve_with_shutdown(listener, shutdown_signal()).await;
        // Flushing can block (an exporter sending its last batch).
        let _ = tokio::task::spawn_blocking(move || guard.shutdown()).await;
        served
    }

    fn migrator(&self) -> Result<Migrator> {
        let repo =
            self.inner.repo.as_ref().ok_or_else(|| {
                Error::internal("no database registered; call App::database(repo)")
            })?;
        Migrator::new(repo, self.inner.migrations.clone())
    }

    /// Runs a CLI task: `routes`, `db:migrate`, `db:rollback` (steps from
    /// `GLACIER_STEPS`, default 1) or `db:status`.
    pub async fn run_task(&self, task: &str) -> Result<()> {
        match task {
            "routes" => print!("{}", self.router().describe()),
            "db:migrate" => {
                let done = self.migrator()?.migrate().await?;
                if done.is_empty() {
                    println!("Already up to date.");
                }
                for name in done {
                    println!("migrated  {name}");
                }
            }
            "db:rollback" => {
                let steps = std::env::var("GLACIER_STEPS")
                    .ok()
                    .and_then(|s| s.parse().ok())
                    .unwrap_or(1);
                let done = self.migrator()?.rollback(steps).await?;
                if done.is_empty() {
                    println!("Nothing to roll back.");
                }
                for name in done {
                    println!("reverted  {name}");
                }
            }
            "db:status" => {
                let status = self.migrator()?.status().await?;
                if status.is_empty() {
                    println!("No migrations.");
                }
                for s in status {
                    let state = if s.applied { "up  " } else { "down" };
                    println!("{state}  {}", s.migration.name());
                }
            }
            other => {
                return Err(Error::internal(format!(
                    "unknown task `{other}`; expected routes, db:migrate, db:rollback or db:status"
                )));
            }
        }
        Ok(())
    }

    async fn warn_about_pending_migrations(&self) {
        if !self.inner.env.is_development() || self.inner.migrations.is_empty() {
            return;
        }
        let pending = match self.migrator() {
            Ok(migrator) => migrator.pending().await,
            Err(err) => Err(err),
        };
        match pending {
            Ok(pending) if !pending.is_empty() => {
                let names: Vec<&str> = pending.iter().map(|m| m.name()).collect();
                tracing::warn!(
                    target: "glacier",
                    "pending migrations: {}; run `glacier db migrate`",
                    names.join(", ")
                );
            }
            Ok(_) => {}
            Err(err) => tracing::warn!(target: "glacier", "couldn't check migrations: {err}"),
        }
    }

    /// Serves connections from `listener` until `signal` resolves, then
    /// gives in-flight requests a grace period to finish.
    pub async fn serve_with_shutdown(
        self,
        listener: TcpListener,
        signal: impl Future<Output = ()>,
    ) -> Result<()> {
        if self.inner.env.is_production() && !self.inner.has_secret {
            return Err(Error::internal(
                "secret_key_base is required in production; set GLACIER__SECRET_KEY_BASE",
            ));
        }
        tracing::info!(
            target: "glacier",
            "listening on http://{} ({})",
            listener.local_addr()?,
            self.inner.env
        );
        let graceful = GracefulShutdown::new();
        let mut signal = std::pin::pin!(signal);

        loop {
            let (stream, peer) = tokio::select! {
                conn = listener.accept() => match conn {
                    Ok(conn) => conn,
                    Err(err) => {
                        tracing::warn!("failed to accept connection: {err}");
                        continue;
                    }
                },
                () = &mut signal => break,
            };

            let service = self.clone();
            let watcher = graceful.watcher();
            tokio::spawn(async move {
                let handler = service_fn(move |mut req: hyper::Request<Incoming>| {
                    let service = service.clone();
                    req.extensions_mut()
                        .insert(crate::context::RemoteAddr(peer));
                    async move { Ok::<_, Infallible>(service.call_hyper(req).await) }
                });
                let builder = auto::Builder::new(TokioExecutor::new());
                let conn = builder.serve_connection(TokioIo::new(stream), handler);
                if let Err(err) = watcher.watch(conn).await {
                    tracing::debug!("connection from {peer} ended with error: {err}");
                }
            });
        }

        tracing::info!(target: "glacier", "shutting down");
        tokio::select! {
            () = graceful.shutdown() => {}
            () = tokio::time::sleep(SHUTDOWN_GRACE_PERIOD) => {
                tracing::warn!(target: "glacier", "grace period elapsed; dropping open connections");
            }
        }
        Ok(())
    }
}

/// The innermost handler: looks up the route and runs its pipeline.
struct Dispatcher(Arc<Router>);

impl Handler for Dispatcher {
    fn call(&self, mut ctx: Context) -> BoxFuture<Response> {
        match self.0.recognize(ctx.method(), ctx.path()) {
            Match::Found(route, params) => {
                let span = tracing::Span::current();
                span.record("http.route", route.pattern());
                span.record("otel.name", format!("{} {}", ctx.method(), route.pattern()));
                // What `head :ok` says it is, as Rails: the requested type.
                let head_type =
                    crate::mime::requested(params.get("format"), ctx.header(header::ACCEPT))
                        .unwrap_or("text/html");
                ctx.set_params(params);
                ctx.set_controller(route.label());
                let response = if route.stack.is_empty() {
                    route.handler.call(ctx)
                } else {
                    Box::pin(Next::new(route.stack.clone(), route.handler.clone()).run(ctx))
                };
                Box::pin(async move {
                    let mut response = response.await;
                    let status = response.status();
                    let empty = status.is_informational()
                        || status == StatusCode::NO_CONTENT
                        || status == StatusCode::NOT_MODIFIED;
                    if response.is_head()
                        && !empty
                        && !response.headers().contains_key(header::CONTENT_TYPE)
                    {
                        response.headers_mut().insert(
                            header::CONTENT_TYPE,
                            http::HeaderValue::from_static(head_type),
                        );
                    }
                    response
                })
            }
            Match::MethodNotAllowed(allowed) => {
                let allow = allowed
                    .iter()
                    .map(Method::as_str)
                    .collect::<Vec<_>>()
                    .join(", ");
                let res = Response::text("Method Not Allowed")
                    .with_status(StatusCode::METHOD_NOT_ALLOWED)
                    .with_header(header::ALLOW, allow);
                Box::pin(async move { res })
            }
            Match::NotFound => Box::pin(async { Error::not_found().into_response() }),
        }
    }
}

/// The development-only error page. Production shows a bare status line.
fn debug_page(report: &ErrorReport, method: &Method, path: &str) -> Response {
    let causes: String = report
        .causes
        .iter()
        .map(|c| format!("<li>{}</li>", escape(c)))
        .collect();
    let causes = if causes.is_empty() {
        String::new()
    } else {
        format!("<h2>Caused by</h2><ol>{causes}</ol>")
    };
    Response::html(format!(
        r#"<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>{status} · Glacier</title>
<style>
  body {{ font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f6f8fa; color: #1f2328; }}
  header {{ background: #0b3d5c; color: #fff; padding: 24px 32px; }}
  header p {{ margin: 0; opacity: .8; font-family: ui-monospace, monospace; }}
  h1 {{ margin: 4px 0 0; font-size: 22px; }}
  main {{ padding: 24px 32px; }}
  pre {{ background: #fff; border: 1px solid #d0d7de; border-radius: 6px; padding: 16px; white-space: pre-wrap; }}
  footer {{ padding: 0 32px 24px; color: #59636e; font-size: 13px; }}
</style></head>
<body>
<header><p>{status} · {method} {path}</p><h1>{title}</h1></header>
<main><pre>{message}</pre>{causes}</main>
<footer>You are seeing this page because the app is running in development. Production responses show only the status.</footer>
</body>
</html>"#,
        status = report.status.as_u16(),
        method = escape(method.as_str()),
        path = escape(path),
        title = escape(report.status.canonical_reason().unwrap_or("Error")),
        message = escape(&report.message),
    ))
    .with_status(report.status)
}

async fn shutdown_signal() {
    let ctrl_c = async {
        let _ = tokio::signal::ctrl_c().await;
    };

    #[cfg(unix)]
    let terminate = async {
        use tokio::signal::unix::{SignalKind, signal};
        match signal(SignalKind::terminate()) {
            Ok(mut sigterm) => {
                sigterm.recv().await;
            }
            Err(_) => std::future::pending().await,
        }
    };
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();

    tokio::select! {
        () = ctrl_c => {}
        () = terminate => {}
    }
}

fn panic_message(payload: &(dyn Any + Send)) -> &str {
    if let Some(s) = payload.downcast_ref::<&str>() {
        s
    } else if let Some(s) = payload.downcast_ref::<String>() {
        s
    } else {
        "<non-string panic payload>"
    }
}