Skip to main content

glacier/
app.rs

1//! The application builder and the HTTP server.
2
3use std::any::Any;
4use std::convert::Infallible;
5use std::future::Future;
6use std::panic::AssertUnwindSafe;
7use std::sync::Arc;
8use std::time::Duration;
9
10use bytes::Bytes;
11use futures_util::FutureExt;
12use http::{Extensions, Method, StatusCode, header};
13use http_body_util::{BodyExt, Full, LengthLimitError, Limited};
14use hyper::body::Incoming;
15use hyper::service::service_fn;
16use hyper_util::rt::{TokioExecutor, TokioIo};
17use hyper_util::server::conn::auto;
18use hyper_util::server::graceful::GracefulShutdown;
19use tokio::net::{TcpListener, ToSocketAddrs};
20use tracing::Instrument;
21use tracing::field::Empty;
22
23use crate::config::{Config, Env};
24use crate::context::Context;
25use crate::cookies::{Cookies, Key};
26use crate::db::migration::{Migration, Migrator};
27use crate::db::{self, Repo};
28use crate::error::{Bare, Error, ErrorReport, Result};
29use crate::handler::{BoxFuture, Handler};
30use crate::html::escape;
31use crate::middleware::{Middleware, Next};
32use crate::request;
33use crate::response::{IntoResponse, Response};
34use crate::router::{Match, Router};
35use crate::session::Session;
36use crate::telemetry::Telemetry;
37
38const DEFAULT_MAX_BODY_SIZE: usize = 2 * 1024 * 1024;
39const SHUTDOWN_GRACE_PERIOD: Duration = Duration::from_secs(10);
40const MIN_SECRET_LEN: usize = 32;
41const HEALTH_CHECK_PATH: &str = "/up";
42/// How long `/up` waits for the database before reporting it down.
43const HEALTH_CHECK_TIMEOUT: Duration = Duration::from_secs(2);
44
45/// Set by the CLI (`glacier routes`, `glacier db migrate`, ...) to run a
46/// task instead of serving.
47const TASK_VAR: &str = "GLACIER_TASK";
48
49/// Configures an application: routes, middleware and shared state.
50pub struct App {
51    router: Router,
52    middleware: Vec<Arc<dyn Middleware>>,
53    state: Extensions,
54    max_body_size: usize,
55    pub(crate) env: Option<Env>,
56    key: Option<Key>,
57    repo: Option<Repo>,
58    named: Vec<(String, Named)>,
59    migrations: Vec<Migration>,
60    named_migrations: Vec<(String, Vec<Migration>)>,
61    seeds: Option<Seeds>,
62    tasks: Vec<crate::task::Task>,
63    health_check: Option<String>,
64    hosts: Option<crate::hosts::Hosts>,
65    telemetry: Vec<Telemetry>,
66}
67
68impl Default for App {
69    fn default() -> Self {
70        Self::new()
71    }
72}
73
74impl App {
75    pub fn new() -> Self {
76        Self {
77            router: Router::new(),
78            middleware: Vec::new(),
79            state: Extensions::new(),
80            max_body_size: DEFAULT_MAX_BODY_SIZE,
81            env: None,
82            key: None,
83            repo: None,
84            named: Vec::new(),
85            migrations: Vec::new(),
86            named_migrations: Vec::new(),
87            seeds: None,
88            tasks: Vec::new(),
89            health_check: Some(HEALTH_CHECK_PATH.into()),
90            hosts: None,
91            telemetry: Vec::new(),
92        }
93    }
94
95    /// Sends traces somewhere besides the logs, e.g. an OpenTelemetry
96    /// collector: `.telemetry(glacier_otel::from_env("blog")?)`. Installed
97    /// when the app starts serving, and flushed when it stops.
98    pub fn telemetry(mut self, telemetry: Telemetry) -> Self {
99        if telemetry.is_enabled() {
100            self.telemetry.push(telemetry);
101        }
102        self
103    }
104
105    /// Serves the health check at `path` instead of `/up`.
106    ///
107    /// The health check answers `GET` (and `HEAD`) with `200 ok` when the
108    /// app is up and its database answers, or `503` when the database
109    /// doesn't within two seconds, so a deploy agent or load balancer knows
110    /// when to send traffic. It runs before any middleware: no logging, no
111    /// cookies, no HTTPS redirect. A route of the app's own at the same path
112    /// takes its place.
113    pub fn health_check(mut self, path: &str) -> Self {
114        self.health_check = Some(path.into());
115        self
116    }
117
118    /// Answers only requests for these hosts, refusing others with `403`;
119    /// `.example.com` also allows its subdomains. The config's `hosts` and
120    /// `url` set this (see `glacier::hosts`).
121    pub fn hosts<I, S>(mut self, hosts: I) -> Self
122    where
123        I: IntoIterator<Item = S>,
124        S: AsRef<str>,
125    {
126        self.hosts = Some(crate::hosts::Hosts::new(hosts));
127        self
128    }
129
130    /// Turns the built-in health check off.
131    pub fn without_health_check(mut self) -> Self {
132        self.health_check = None;
133        self
134    }
135
136    /// Applies a loaded `Config`: environment, `secret_key_base`,
137    /// `server.max_body_size` and the hosts the app answers for (`hosts`
138    /// and `url`). The config is also registered as state, so
139    /// handlers can read it with `ctx.state::<Config>()`.
140    pub fn config(mut self, config: Config) -> Result<Self> {
141        self.env = Some(config.env());
142        if let Some(secret) = config.get_opt::<String>("secret_key_base")? {
143            self = self.secret_key_base(&secret)?;
144        }
145        // Earlier secrets, so changing `secret_key_base` doesn't sign
146        // everyone out: cookies and tokens they made are still read.
147        let previous: Vec<String> = config
148            .get_opt("previous_secret_key_bases")?
149            .unwrap_or_default();
150        crate::request::install_previous_keys(
151            previous
152                .iter()
153                .map(|secret| Key::derive_from(secret.as_bytes()))
154                .collect(),
155        );
156        crate::mail::configure(&config)?;
157        crate::cache::configure(&config)?;
158        crate::storage::configure(&config)?;
159        crate::time::configure(&config)?;
160        crate::encryption::configure(&config)?;
161        crate::context::configure_proxies(&config)?;
162        config.make_current();
163        if let Some(size) = config.get_opt::<usize>("server.max_body_size")? {
164            self.max_body_size = size;
165        }
166        if let Some(hosts) = crate::hosts::Hosts::from_config(&config)? {
167            self.hosts = Some(hosts);
168        }
169        // `[databases.<name>]`: connected when a request first needs it,
170        // unless `named_database` gives one.
171        let databases: std::collections::BTreeMap<String, toml::Value> =
172            config.get_opt("databases")?.unwrap_or_default();
173        for name in databases.into_keys() {
174            if !self.named.iter().any(|(n, _)| *n == name) {
175                let lazy = Named::FromConfig(Arc::default(), config.clone());
176                self.named.push((name, lazy));
177            }
178        }
179        Ok(self.state(config))
180    }
181
182    /// The secret that signs and encrypts cookies (including the session).
183    /// Without one, a random key is generated per boot, which logs everyone
184    /// out on restart; that's refused in production.
185    pub fn secret_key_base(mut self, secret: &str) -> Result<Self> {
186        if secret.len() < MIN_SECRET_LEN {
187            return Err(Error::internal(format!(
188                "secret_key_base must be at least {MIN_SECRET_LEN} bytes"
189            )));
190        }
191        let key = Key::derive_from(secret.as_bytes());
192        crate::request::install_key(&key);
193        self.key = Some(key);
194        Ok(self)
195    }
196
197    /// Makes `repo` the ambient database for every request, so model calls
198    /// need no connection argument. It's also registered as state.
199    pub fn database(mut self, repo: Repo) -> Self {
200        self.repo = Some(repo.clone());
201        self.state(repo)
202    }
203
204    /// Another database, for models declared with `database: :name`
205    /// (`#[glacier::model(database = "name")]`): ambient in every request,
206    /// with replica reads as the main database has them.
207    pub fn named_database(mut self, name: &str, repo: Repo) -> Self {
208        self.named.retain(|(n, _)| n != name);
209        self.named.push((name.to_owned(), Named::Ready(repo)));
210        self
211    }
212
213    /// Registers the app's tasks (`tasks::all()`, from
214    /// `src/tasks.glacier`), which `glacier run <task>` and the binary's
215    /// `app <task>` run.
216    pub fn tasks(mut self, tasks: Vec<crate::task::Task>) -> Self {
217        self.tasks.extend(tasks);
218        self
219    }
220
221    /// Registers the data a new database starts with (usually
222    /// `seeds::run`, from `src/seeds.glacier`), which `glacier db seed`
223    /// loads in one transaction.
224    pub fn seeds<F, Fut>(mut self, seeds: F) -> Self
225    where
226        F: Fn() -> Fut + Send + Sync + 'static,
227        Fut: Future<Output = Result<()>> + Send + 'static,
228    {
229        self.seeds = Some(Arc::new(move || Box::pin(seeds())));
230        self
231    }
232
233    /// Registers a named database's migrations
234    /// (`analytics_migrations::all()`), which `glacier db migrate` runs
235    /// after the app's own.
236    pub fn named_migrations(mut self, name: &str, migrations: Vec<Migration>) -> Self {
237        self.named_migrations.retain(|(n, _)| n != name);
238        self.named_migrations.push((name.to_owned(), migrations));
239        self
240    }
241
242    /// Registers the app's migrations (usually `migrations::all()`), so
243    /// `glacier db migrate` can run them and development warns about
244    /// pending ones.
245    pub fn migrations(mut self, migrations: Vec<Migration>) -> Self {
246        self.migrations = migrations;
247        self
248    }
249
250    /// Overrides the environment, which otherwise comes from the config or
251    /// `GLACIER_ENV`.
252    pub fn env(mut self, env: Env) -> Self {
253        self.env = Some(env);
254        self
255    }
256
257    pub fn routes(mut self, draw: impl FnOnce(&mut Router)) -> Self {
258        draw(&mut self.router);
259        self
260    }
261
262    /// Adds middleware that wraps every request, including 404s. The first
263    /// one added is the outermost. For middleware on some routes only, see
264    /// `Router::pipe_through`.
265    pub fn middleware(mut self, middleware: impl Middleware) -> Self {
266        self.middleware.push(Arc::new(middleware));
267        self
268    }
269
270    /// The background jobs the app runs: `serve` starts their workers on
271    /// the app's database. Also registered as state, for tests
272    /// (`TestClient::perform_jobs`).
273    pub fn jobs(self, jobs: crate::jobs::Jobs) -> Self {
274        self.state(jobs)
275    }
276
277    /// The providers whose webhooks the app receives, at
278    /// `post "/webhooks/:provider" => glacier::webhooks::receive`; see
279    /// [`crate::webhooks`].
280    pub fn webhooks(self, webhooks: crate::webhooks::Webhooks) -> Self {
281        crate::webhooks::install(webhooks.clone());
282        self.state(webhooks)
283    }
284
285    /// How the app takes payments; see [`crate::billing`].
286    pub fn billing(self, billing: crate::billing::Billing) -> Self {
287        crate::billing::install(billing.clone());
288        self.state(billing)
289    }
290
291    /// The page `/dev/components` shows in development: each
292    /// component's examples, in the app's layout. `glacier::app!()`
293    /// registers it.
294    pub fn component_previews(self, gallery: fn() -> String) -> Self {
295        self.state(crate::view::ComponentGallery(gallery))
296    }
297
298    /// The mail previews `/dev/mail` shows in development; see
299    /// [`crate::mail::Previews`].
300    pub fn mail_previews(self, previews: crate::mail::Previews) -> Self {
301        self.state(previews)
302    }
303
304    /// The app's own error pages: `render(404)` gives the page for a
305    /// status, in the app's layout, or `None` for a status without one.
306    /// `glacier::app!()` registers the templates in `src/views/errors/`
307    /// (`404.html`, `500.html`).
308    pub fn error_pages(self, render: fn(u16) -> Option<String>) -> Self {
309        self.state(ErrorPages(render))
310    }
311
312    /// Sends mail through `delivery` instead of what `[mail]` configures.
313    pub fn mail_delivery(self, delivery: impl crate::mail::Delivery) -> Self {
314        crate::mail::set_delivery(Arc::new(delivery));
315        self
316    }
317
318    /// Registers shared state, retrieved in handlers with `ctx.state::<T>()`.
319    /// One value per type; registering a type twice replaces the first.
320    pub fn state<T: Clone + Send + Sync + 'static>(mut self, value: T) -> Self {
321        self.state.insert(value);
322        self
323    }
324
325    /// Requests with larger bodies are rejected with `413 Payload Too Large`.
326    pub fn max_body_size(mut self, bytes: usize) -> Self {
327        self.max_body_size = bytes;
328        self
329    }
330
331    /// Freezes the configuration into a cheaply cloneable `Service`.
332    pub fn build(self) -> Service {
333        let env = self.env.unwrap_or_else(Env::current);
334        // Development's own pages (mail previews and the inbox), tried when
335        // none of the app's routes match, and never listed with them.
336        // Tests have them too, to check them.
337        let dev = (env.is_development() || env == Env::Test).then(|| {
338            let mut router = Router::new();
339            crate::mail::preview::draw(&mut router);
340            router.get("/dev/components", crate::view::component_gallery);
341            router.get("/__glacier/reload", crate::view::reload::endpoint);
342            Arc::new(Dispatcher {
343                router: Arc::new(router),
344                dev: None,
345            })
346        });
347        // The app's own route at the health check's path wins.
348        let health_check = self
349            .health_check
350            .filter(|path| !self.router.routes().iter().any(|r| r.pattern() == path));
351        let router = Arc::new(self.router);
352        Service {
353            inner: Arc::new(Inner {
354                stack: self.middleware.into(),
355                endpoint: Arc::new(Dispatcher {
356                    router: router.clone(),
357                    dev,
358                }),
359                router,
360                state: Arc::new(self.state),
361                max_body_size: self.max_body_size,
362                env,
363                has_secret: self.key.is_some(),
364                repo: self.repo,
365                named: self.named,
366                migrations: self.migrations,
367                named_migrations: self.named_migrations,
368                seeds: self.seeds,
369                tasks: {
370                    crate::task::install(&self.tasks);
371                    self.tasks
372                },
373                health_check,
374                hosts: self.hosts,
375                telemetry: std::sync::Mutex::new(self.telemetry),
376                key: Arc::new(self.key.unwrap_or_else(Key::generate)),
377            }),
378        }
379    }
380
381    /// Builds the app and serves it until Ctrl-C or SIGTERM.
382    pub async fn serve(self, addr: impl ToSocketAddrs) -> Result<()> {
383        self.build().serve(addr).await
384    }
385}
386
387/// A built application, ready to handle requests.
388#[derive(Clone)]
389pub struct Service {
390    inner: Arc<Inner>,
391}
392
393struct Inner {
394    stack: Arc<[Arc<dyn Middleware>]>,
395    endpoint: Arc<dyn Handler>,
396    router: Arc<Router>,
397    state: Arc<Extensions>,
398    max_body_size: usize,
399    env: Env,
400    has_secret: bool,
401    key: Arc<Key>,
402    repo: Option<Repo>,
403    named: Vec<(String, Named)>,
404    migrations: Vec<Migration>,
405    named_migrations: Vec<(String, Vec<Migration>)>,
406    seeds: Option<Seeds>,
407    tasks: Vec<crate::task::Task>,
408    health_check: Option<String>,
409    hosts: Option<crate::hosts::Hosts>,
410    /// Taken by `serve`, which installs it.
411    telemetry: std::sync::Mutex<Vec<Telemetry>>,
412}
413
414impl Service {
415    /// Shared state registered with `App::state`.
416    pub(crate) fn state<T: Send + Sync + 'static>(&self) -> Option<&T> {
417        self.inner.state.get::<T>()
418    }
419
420    pub fn router(&self) -> &Router {
421        &self.inner.router
422    }
423
424    pub fn env(&self) -> Env {
425        self.inner.env
426    }
427
428    /// Runs one request through middleware and the router. Panics in
429    /// handlers are caught and turned into a 500.
430    pub async fn call(&self, req: http::Request<Bytes>) -> Response {
431        if self.is_health_check(&req) {
432            return self.health().await;
433        }
434        let (parts, body) = req.into_parts();
435        if let Some(hosts) = &self.inner.hosts {
436            let host = crate::hosts::of(&parts).unwrap_or_default();
437            if !hosts.allows(host) {
438                tracing::warn!(target: "glacier", host, "refused a request for a host not in `hosts`");
439                return Response::text(format!("Blocked host: {host}"))
440                    .with_status(StatusCode::FORBIDDEN);
441            }
442        }
443        let method = parts.method.clone();
444        let path = parts.uri.path().to_owned();
445        let accept = parts
446            .headers
447            .get(header::ACCEPT)
448            .and_then(|v| v.to_str().ok())
449            .map(str::to_owned);
450        let cookies = Cookies::from_headers(&parts.headers, self.inner.key.clone());
451        let session = Session::new(cookies.clone(), self.inner.env.is_production());
452        let scope = request::Scope {
453            session: session.clone(),
454            path: path.clone(),
455            base_url: request::base_url_of(&parts),
456            query: parts.uri.query().map(str::to_owned),
457            key: self.inner.key.clone(),
458            assigns: Default::default(),
459            deferred: Default::default(),
460        };
461        let request_id = request::id_from(
462            parts
463                .headers
464                .get("x-request-id")
465                .and_then(|v| v.to_str().ok()),
466        );
467        let ctx = Context::new(
468            parts,
469            body,
470            self.inner.state.clone(),
471            cookies.clone(),
472            session.clone(),
473        );
474        let next = Next::new(self.inner.stack.clone(), self.inner.endpoint.clone());
475
476        // The request's span, named and fielded per OpenTelemetry's HTTP
477        // conventions; the router fills in `http.route` when it matches.
478        let span = tracing::info_span!(
479            target: "glacier",
480            "glacier.request",
481            otel.name = %method,
482            otel.kind = "server",
483            otel.status_code = Empty,
484            http.request.method = %method,
485            url.path = %path,
486            http.route = Empty,
487            http.response.status_code = Empty,
488            glacier.access = Empty,
489            glacier.request_id = %request_id,
490        );
491        // An error page is drawn in the request, so its layout has the
492        // flash, the CSRF token and the rest.
493        let pages = self.inner.state.get::<ErrorPages>().copied();
494        let (page_path, page_accept) = (path.clone(), accept.clone());
495        let (testing, deferred_repo) = (self.inner.env == Env::Test, self.inner.repo.clone());
496        let run = request::with_id(
497            request_id.clone(),
498            request::scope(
499                scope,
500                crate::current::with_current(crate::db::query_cache::scope(Box::pin(async move {
501                    let mut response = next.run(ctx).await;
502                    // A response for someone (an access was set) is theirs:
503                    // private, unless the action said otherwise.
504                    if crate::current::get::<crate::access::RequestAccess>().is_some() {
505                        private_by_default(&mut response);
506                    }
507                    if pages.is_some()
508                        && response.extensions().get::<Bare>().is_some()
509                        && !response.is_head()
510                    {
511                        response =
512                            public_exception(response, &page_path, page_accept.as_deref(), pages)
513                                .await;
514                    }
515                    // `after_response` work: now in tests, so they see it; else
516                    // in the background, with the app's database.
517                    for work in request::take_deferred() {
518                        if testing {
519                            if let Err(err) = work.await {
520                                tracing::error!(target: "glacier", "after_response: {err}");
521                            }
522                            continue;
523                        }
524                        let repo = deferred_repo.clone();
525                        tokio::spawn(async move {
526                            let done = match repo {
527                                Some(repo) => db::with(&repo, work).await,
528                                None => work.await,
529                            };
530                            if let Err(err) = done {
531                                tracing::error!(target: "glacier", "after_response: {err}");
532                            }
533                        });
534                    }
535                    response
536                }))),
537            ),
538        )
539        .instrument(span.clone());
540        // Keep an already-active connection (e.g. a test sandbox's
541        // transaction) rather than replacing it with the app's repo.
542        // With a replica, a GET or HEAD reads from it, unless this browser
543        // wrote moments ago and would miss its own change.
544        let reads_replica = (method == http::Method::GET || method == http::Method::HEAD)
545            && !wrote_recently(&cookies);
546        // Connections to databases with replicas, to see if they wrote.
547        let mut replicated = Vec::new();
548        // Named databases a test hasn't already put in a sandbox.
549        let mut named = Vec::new();
550        for (name, database) in &self.inner.named {
551            if db::has_named(name) {
552                continue;
553            }
554            let repo = match database {
555                Named::Ready(repo) => repo.clone(),
556                Named::FromConfig(cell, config) => {
557                    match cell
558                        .get_or_try_init(|| Repo::from_config_named(config, name))
559                        .await
560                    {
561                        Ok(repo) => repo.clone(),
562                        Err(err) => {
563                            tracing::error!(target: "glacier", database = %name, "connecting: {err}");
564                            continue;
565                        }
566                    }
567                }
568            };
569            let conn = db::request_connection(&repo, reads_replica);
570            if repo.has_replica() {
571                replicated.push(conn.clone());
572            }
573            named.push((name.clone(), conn));
574        }
575        let run = db::scope_named(named, run);
576        // In development, note each statement to spot N+1 queries.
577        let development = self.inner.env.is_development();
578        let run = async move {
579            if !development {
580                return run.await;
581            }
582            let (res, queries) = db::logging_queries(db::development_checks(run)).await;
583            for (sql, times) in db::repeated_selects(&queries, db::REPEATED_QUERY_THRESHOLD) {
584                tracing::warn!(
585                    target: "glacier",
586                    "N+1 query: `{sql}` ran {times} times in one request; load the \
587                     records in one query instead, with `preload` or `where(id: ids)`"
588                );
589            }
590            res
591        };
592        let result = match &self.inner.repo {
593            Some(repo) if !db::active() => {
594                let conn = db::request_connection(repo, reads_replica);
595                if repo.has_replica() {
596                    replicated.push(conn.clone());
597                }
598                AssertUnwindSafe(db::scope(conn, run)).catch_unwind().await
599            }
600            _ => AssertUnwindSafe(run).catch_unwind().await,
601        };
602        if replicated.iter().any(db::Connection::wrote) {
603            cookies.add(
604                cookie::Cookie::build((
605                    db::LAST_WRITE_COOKIE,
606                    crate::time::now().timestamp().to_string(),
607                ))
608                .path("/")
609                .http_only(true)
610                .build(),
611            );
612        }
613        let mut res = match result {
614            Ok(res) => res,
615            Err(panic) => span.in_scope(|| {
616                Error::internal(format!("panic: {}", panic_message(&*panic))).into_response()
617            }),
618        };
619        if let Ok(value) = http::HeaderValue::from_str(&request_id) {
620            res.headers_mut().entry("x-request-id").or_insert(value);
621        }
622        // i64: OpenTelemetry has no unsigned integers.
623        span.record(
624            "http.response.status_code",
625            i64::from(res.status().as_u16()),
626        );
627        if res.status().is_server_error() {
628            span.record("otel.status_code", "ERROR");
629        }
630
631        let is_json = res
632            .header(header::CONTENT_TYPE)
633            .is_some_and(|ct| ct.starts_with("application/json"));
634        // APIs keep their JSON error; the HTML page is for browsers.
635        if self.inner.env.is_development()
636            && res.status().is_server_error()
637            && !is_json
638            && let Some(report) = res.extensions().get::<ErrorReport>()
639        {
640            res = debug_page(report, &method, &path);
641        }
642        if res.extensions().get::<Bare>().is_some() && !res.is_head() {
643            let pages = self.inner.state.get::<ErrorPages>().copied();
644            res = public_exception(res, &path, accept.as_deref(), pages).await;
645        }
646        session.commit();
647        cookies.write_to(res.headers_mut());
648        res
649    }
650
651    fn is_health_check(&self, req: &http::Request<Bytes>) -> bool {
652        matches!(*req.method(), Method::GET | Method::HEAD)
653            && self.inner.health_check.as_deref() == Some(req.uri().path())
654    }
655
656    /// `200 ok` when the database (if any) answers in time, else `503`.
657    async fn health(&self) -> Response {
658        let database = match &self.inner.repo {
659            None => Ok(()),
660            Some(repo) => {
661                let ping = db::sql("SELECT 1").on(repo).execute();
662                match tokio::time::timeout(HEALTH_CHECK_TIMEOUT, ping).await {
663                    Ok(Ok(_)) => Ok(()),
664                    Ok(Err(err)) => Err(err.to_string()),
665                    Err(_) => Err("timed out".to_owned()),
666                }
667            }
668        };
669        let mut res = match database {
670            Ok(()) => Response::text("ok"),
671            Err(reason) => {
672                tracing::warn!(target: "glacier", reason, "health check: database unavailable");
673                Response::text("database unavailable").with_status(StatusCode::SERVICE_UNAVAILABLE)
674            }
675        };
676        res.headers_mut().insert(
677            header::CACHE_CONTROL,
678            http::HeaderValue::from_static("no-store"),
679        );
680        res
681    }
682
683    async fn call_hyper(&self, req: hyper::Request<Incoming>) -> http::Response<Full<Bytes>> {
684        let (parts, body) = req.into_parts();
685        let body = match Limited::new(body, self.inner.max_body_size).collect().await {
686            Ok(collected) => collected.to_bytes(),
687            Err(err) if err.is::<LengthLimitError>() => {
688                return Response::text("Payload Too Large")
689                    .with_status(StatusCode::PAYLOAD_TOO_LARGE)
690                    .into_http();
691            }
692            Err(err) => {
693                tracing::debug!("failed to read request body: {err}");
694                return Response::text("Bad Request")
695                    .with_status(StatusCode::BAD_REQUEST)
696                    .into_http();
697            }
698        };
699        self.call(http::Request::from_parts(parts, body))
700            .await
701            .into_http()
702    }
703
704    /// Binds `addr` and serves until Ctrl-C or SIGTERM. Run with a command
705    /// instead, the app binary does that and exits, for production, where
706    /// there's no `glacier` CLI: `app migrate`, `app rollback 2`, `app
707    /// seed`, `app status` (the migrations) and `app routes`.
708    pub async fn serve(self, addr: impl ToSocketAddrs) -> Result<()> {
709        if let Ok(task) = std::env::var(TASK_VAR) {
710            return self.run_task(&task).await;
711        }
712        let args: Vec<String> = std::env::args().skip(1).collect();
713        if let Some(command) = args.first() {
714            let task = match command.as_str() {
715                "migrate" => "db:migrate",
716                "rollback" => {
717                    if let Some(steps) = args.get(1) {
718                        // SAFETY: before any other thread reads the environment.
719                        unsafe { std::env::set_var("GLACIER_STEPS", steps) };
720                    }
721                    "db:rollback"
722                }
723                "seed" => "db:seed",
724                "status" => "db:status",
725                "routes" => "routes",
726                "tasks" => "tasks",
727                "cache:clear" => "cache:clear",
728                "typescript" => "typescript",
729                "serve" | "web" | "work" => "",
730                other => {
731                    if self.inner.tasks.iter().any(|t| t.name == other) {
732                        return self.run_app_task(other, args[1..].to_vec()).await;
733                    }
734                    return Err(Error::internal(format!(
735                        "unknown command `{other}`: expected serve (the default: the web \
736                         server and the jobs), web, work, migrate, rollback [steps], seed, \
737                         status, routes, tasks, cache:clear, typescript, or one of the app's tasks"
738                    )));
739                }
740            };
741            if !task.is_empty() {
742                return self.run_task(task).await;
743            }
744        }
745        // `app web`: the web server without the jobs; `app work`: the jobs
746        // without it (a process each, to scale apart).
747        let role = args.first().map_or("serve", String::as_str);
748        let telemetry = std::mem::take(&mut *self.inner.telemetry.lock().unwrap());
749        let guard = crate::telemetry::init(self.inner.env, telemetry);
750        self.warn_about_pending_migrations().await;
751        let workers = match (
752            role,
753            self.inner.state.get::<crate::jobs::Jobs>(),
754            self.inner.repo.clone(),
755        ) {
756            ("serve" | "work", Some(jobs), Some(repo)) => Some(jobs.start(repo)),
757            _ => None,
758        };
759        let served = if role == "work" {
760            match &workers {
761                Some(_) => tracing::info!(target: "glacier", "working jobs (Ctrl-C to stop)"),
762                None => {
763                    tracing::warn!(target: "glacier", "no jobs to work: the app has no jobs or no database")
764                }
765            }
766            shutdown_signal().await;
767            Ok(())
768        } else {
769            let listener = TcpListener::bind(addr).await?;
770            self.serve_with_shutdown(listener, shutdown_signal()).await
771        };
772        // Requests have finished; the jobs running finish too, for a while.
773        if let Some(workers) = workers {
774            workers.stop().await;
775        }
776        // Flushing can block (an exporter sending its last batch).
777        let _ = tokio::task::spawn_blocking(move || guard.shutdown()).await;
778        served
779    }
780
781    fn migrator(&self) -> Result<Migrator> {
782        let repo =
783            self.inner.repo.as_ref().ok_or_else(|| {
784                Error::internal("no database registered; call App::database(repo)")
785            })?;
786        Migrator::new(repo, self.inner.migrations.clone())
787    }
788
789    /// A named database's repo, connecting a configured one if needed.
790    async fn named_repo(&self, name: &str) -> Result<Repo> {
791        let database = self
792            .inner
793            .named
794            .iter()
795            .find(|(n, _)| n == name)
796            .map(|(_, database)| database)
797            .ok_or_else(|| {
798                Error::internal(format!(
799                    "no `{name}` database: add [databases.{name}] to the config \
800                     or call App::named_database"
801                ))
802            })?;
803        match database {
804            Named::Ready(repo) => Ok(repo.clone()),
805            Named::FromConfig(cell, config) => Ok(cell
806                .get_or_try_init(|| Repo::from_config_named(config, name))
807                .await?
808                .clone()),
809        }
810    }
811
812    /// Every named database, connected: for the test harness.
813    pub(crate) async fn named_databases(&self) -> Result<Vec<(String, Repo)>> {
814        let mut databases = Vec::new();
815        for (name, _) in &self.inner.named {
816            databases.push((name.clone(), self.named_repo(name).await?));
817        }
818        Ok(databases)
819    }
820
821    async fn named_migrator(&self, name: &str) -> Result<Migrator> {
822        let migrations = self
823            .inner
824            .named_migrations
825            .iter()
826            .find(|(n, _)| n == name)
827            .map(|(_, migrations)| migrations.clone())
828            .unwrap_or_default();
829        Migrator::new(&self.named_repo(name).await?, migrations)
830    }
831
832    /// Runs the named databases' migrations: for tests, whose databases
833    /// start empty. `glacier db migrate` runs them too.
834    pub async fn migrate_named(&self) -> Result<Vec<String>> {
835        let mut done = Vec::new();
836        for (name, _) in &self.inner.named_migrations {
837            for migration in self.named_migrator(name).await?.migrate().await? {
838                done.push(format!("{name}/{migration}"));
839            }
840        }
841        Ok(done)
842    }
843
844    /// The migrator for `GLACIER_DATABASE` (a named database), or the
845    /// app's own when it isn't set.
846    async fn chosen_migrator(&self) -> Result<Migrator> {
847        match std::env::var("GLACIER_DATABASE") {
848            Ok(name) if !name.is_empty() => self.named_migrator(&name).await,
849            _ => self.migrator(),
850        }
851    }
852
853    /// Runs a CLI task: `routes`, `db:migrate` (every database),
854    /// `db:rollback` (steps from `GLACIER_STEPS`, default 1, on
855    /// `GLACIER_DATABASE` or the app's own) or `db:status`.
856    pub async fn run_task(&self, task: &str) -> Result<()> {
857        match task {
858            "routes" => print!("{}", self.router().describe()),
859            "tasks" => print!("{}", crate::task::listing(&self.inner.tasks)),
860            "cache:clear" => {
861                let cleared = match &self.inner.repo {
862                    Some(repo) => db::with(repo, crate::cache::clear()).await?,
863                    None => crate::cache::clear().await?,
864                };
865                println!("Cleared {cleared} cached values.");
866            }
867            "db:migrate" => {
868                let mut done = self.migrator()?.migrate().await?;
869                done.extend(self.migrate_named().await?);
870                if done.is_empty() {
871                    println!("Already up to date.");
872                }
873                for name in done {
874                    println!("migrated  {name}");
875                }
876                self.dump_in_development().await?;
877            }
878            "db:rollback" => {
879                let steps = std::env::var("GLACIER_STEPS")
880                    .ok()
881                    .and_then(|s| s.parse().ok())
882                    .unwrap_or(1);
883                let done = self.chosen_migrator().await?.rollback(steps).await?;
884                if done.is_empty() {
885                    println!("Nothing to roll back.");
886                }
887                for name in done {
888                    println!("reverted  {name}");
889                }
890                self.dump_in_development().await?;
891            }
892            "db:status" => {
893                let mut status: Vec<(String, bool)> = self
894                    .migrator()?
895                    .status()
896                    .await?
897                    .into_iter()
898                    .map(|s| (s.migration.name().to_owned(), s.applied))
899                    .collect();
900                for (name, _) in &self.inner.named_migrations {
901                    for s in self.named_migrator(name).await?.status().await? {
902                        status.push((format!("{name}/{}", s.migration.name()), s.applied));
903                    }
904                }
905                if status.is_empty() {
906                    println!("No migrations.");
907                }
908                for (name, applied) in status {
909                    let state = if applied { "up  " } else { "down" };
910                    println!("{state}  {name}");
911                }
912            }
913            "openapi" => println!("{}", serde_json::to_string_pretty(&self.openapi())?),
914            "typescript" => print!("{}", crate::openapi::typescript(&self.openapi())),
915            "db:dump" => {
916                for path in self.dump_schema().await? {
917                    println!("wrote  {path}");
918                }
919            }
920            "db:seed" => {
921                self.seed().await?;
922                println!("Seeded.");
923            }
924            // For tools (the MCP): JSON on stdout.
925            "db:schema" => println!("{}", crate::tasks::schema(self.database()?).await?),
926            "db:query" => {
927                let sql = std::env::var("GLACIER_SQL")
928                    .map_err(|_| Error::internal("db:query needs GLACIER_SQL"))?;
929                println!("{}", crate::tasks::query(self.database()?, &sql).await?);
930            }
931            "jobs" => println!("{}", crate::tasks::jobs(self.database()?).await?),
932            "jobs:schedules" => {
933                let schedules = self
934                    .inner
935                    .state
936                    .get::<crate::jobs::Jobs>()
937                    .map(crate::jobs::Jobs::schedules)
938                    .unwrap_or_default();
939                // For tools (the MCP): JSON with `GLACIER_JSON=1`.
940                if std::env::var_os("GLACIER_JSON").is_some() {
941                    println!("{}", serde_json::json!({ "schedules": schedules }));
942                } else {
943                    println!("{}", crate::tasks::schedules(&schedules));
944                }
945            }
946            "webhooks" => println!("{}", crate::tasks::webhooks(self.database()?).await?),
947            "webhooks:replay" => {
948                let id = std::env::var("GLACIER_EVENT_ID")
949                    .ok()
950                    .and_then(|id| id.parse::<i64>().ok())
951                    .ok_or_else(|| Error::internal("webhooks:replay needs GLACIER_EVENT_ID"))?;
952                if db::with(self.database()?, crate::webhooks::Webhooks::replay(id)).await? {
953                    println!("Webhook event #{id} queued to be handled again.");
954                } else {
955                    return Err(Error::new(
956                        StatusCode::NOT_FOUND,
957                        format!("no webhook event #{id}"),
958                    ));
959                }
960            }
961            "jobs:retry" => {
962                let id = std::env::var("GLACIER_JOB_ID")
963                    .ok()
964                    .and_then(|id| id.parse::<i64>().ok())
965                    .ok_or_else(|| Error::internal("jobs:retry needs GLACIER_JOB_ID"))?;
966                if db::with(self.database()?, crate::jobs::Jobs::retry(id)).await? {
967                    println!("Job #{id} queued to run again.");
968                } else {
969                    return Err(Error::new(
970                        StatusCode::NOT_FOUND,
971                        format!("no failed job #{id}"),
972                    ));
973                }
974            }
975            other => {
976                return Err(Error::internal(format!(
977                    "unknown task `{other}`; expected routes, tasks, cache:clear, typescript, db:migrate, db:rollback, \
978                     db:status, db:seed, db:dump, db:schema, db:query, openapi, jobs, jobs:schedules, jobs:retry, webhooks or webhooks:replay"
979                )));
980            }
981        }
982        Ok(())
983    }
984
985    /// The app's OpenAPI document, named and versioned from its package
986    /// (as `cargo run` sets `CARGO_PKG_NAME` and `CARGO_PKG_VERSION`).
987    /// With `GLACIER_API_VERSION`, for that API version (see
988    /// `Router::version`).
989    pub fn openapi(&self) -> serde_json::Value {
990        let title = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "app".to_owned());
991        let version = std::env::var("CARGO_PKG_VERSION").unwrap_or_else(|_| "0.1.0".to_owned());
992        let api_version = std::env::var("GLACIER_API_VERSION")
993            .ok()
994            .filter(|v| !v.is_empty());
995        crate::openapi::document(self.router(), &title, &version, api_version.as_deref())
996    }
997
998    /// Writes each database's schema as SQL: `db/schema.sql`, and
999    /// `db/<name>/schema.sql` for named databases with migrations.
1000    /// Returns the paths written.
1001    pub async fn dump_schema(&self) -> Result<Vec<String>> {
1002        let mut dumps = vec![(
1003            "db/schema.sql".to_owned(),
1004            crate::tasks::dump(self.database()?).await?,
1005        )];
1006        for (name, _) in &self.inner.named_migrations {
1007            let repo = self.named_repo(name).await?;
1008            dumps.push((
1009                format!("db/{name}/schema.sql"),
1010                crate::tasks::dump(&repo).await?,
1011            ));
1012        }
1013        std::fs::create_dir_all("db")?;
1014        let mut written = Vec::new();
1015        for (path, sql) in dumps {
1016            if let Some(dir) = std::path::Path::new(&path).parent() {
1017                std::fs::create_dir_all(dir)?;
1018            }
1019            std::fs::write(&path, sql)?;
1020            written.push(path);
1021        }
1022        Ok(written)
1023    }
1024
1025    /// After migrating in development, as Rails' `schema.rb`.
1026    async fn dump_in_development(&self) -> Result<()> {
1027        if self.inner.env.is_development() {
1028            for path in self.dump_schema().await? {
1029                println!("wrote     {path}");
1030            }
1031        }
1032        Ok(())
1033    }
1034
1035    /// Loads the seeds in one transaction on the app's database, with the
1036    /// named databases ambient.
1037    pub async fn seed(&self) -> Result<()> {
1038        let seeds =
1039            self.inner.seeds.clone().ok_or_else(|| {
1040                Error::internal("no seeds registered; call App::seeds(seeds::run)")
1041            })?;
1042        let repo = self.database()?.clone();
1043        let named = self
1044            .named_databases()
1045            .await?
1046            .into_iter()
1047            .map(|(name, repo)| (name, db::Connection::from(&repo)))
1048            .collect();
1049        db::with(&repo, db::scope_named(named, db::transaction(seeds()))).await
1050    }
1051
1052    /// The app's task called `name`.
1053    pub(crate) fn task(&self, name: &str) -> Option<crate::task::Task> {
1054        self.inner.tasks.iter().find(|t| t.name == name).cloned()
1055    }
1056
1057    /// Runs the app's task `name` with `args`, with the app's databases
1058    /// (when it has them), outside any request.
1059    pub async fn run_app_task(&self, name: &str, args: Vec<String>) -> Result<()> {
1060        let task = self
1061            .inner
1062            .tasks
1063            .iter()
1064            .find(|t| t.name == name)
1065            .ok_or_else(|| Error::internal(format!("no task `{name}`; `app tasks` lists them")))?;
1066        let run = (task.run)(args);
1067        let Some(repo) = self.inner.repo.clone() else {
1068            return run.await;
1069        };
1070        let named = self
1071            .named_databases()
1072            .await?
1073            .into_iter()
1074            .map(|(name, repo)| (name, db::Connection::from(&repo)))
1075            .collect();
1076        db::with(&repo, db::scope_named(named, run)).await
1077    }
1078
1079    /// The app's database, for tasks that need one.
1080    fn database(&self) -> Result<&Repo> {
1081        self.inner
1082            .repo
1083            .as_ref()
1084            .ok_or_else(|| Error::internal("the app has no database (App::database)"))
1085    }
1086
1087    async fn warn_about_pending_migrations(&self) {
1088        if !self.inner.env.is_development() || self.inner.migrations.is_empty() {
1089            return;
1090        }
1091        let pending = match self.migrator() {
1092            Ok(migrator) => migrator.pending().await,
1093            Err(err) => Err(err),
1094        };
1095        match pending {
1096            Ok(pending) if !pending.is_empty() => {
1097                let names: Vec<&str> = pending.iter().map(|m| m.name()).collect();
1098                tracing::warn!(
1099                    target: "glacier",
1100                    "pending migrations: {}; run `glacier db migrate`",
1101                    names.join(", ")
1102                );
1103            }
1104            Ok(_) => {}
1105            Err(err) => tracing::warn!(target: "glacier", "couldn't check migrations: {err}"),
1106        }
1107    }
1108
1109    /// Serves connections from `listener` until `signal` resolves, then
1110    /// gives in-flight requests a grace period to finish.
1111    pub async fn serve_with_shutdown(
1112        self,
1113        listener: TcpListener,
1114        signal: impl Future<Output = ()>,
1115    ) -> Result<()> {
1116        if self.inner.env.is_production() && !self.inner.has_secret {
1117            return Err(Error::internal(
1118                "secret_key_base is required in production; set GLACIER__SECRET_KEY_BASE",
1119            ));
1120        }
1121        tracing::info!(
1122            target: "glacier",
1123            "listening on http://{} ({})",
1124            listener.local_addr()?,
1125            self.inner.env
1126        );
1127        let graceful = GracefulShutdown::new();
1128        let mut signal = std::pin::pin!(signal);
1129
1130        loop {
1131            let (stream, peer) = tokio::select! {
1132                conn = listener.accept() => match conn {
1133                    Ok(conn) => conn,
1134                    Err(err) => {
1135                        tracing::warn!("failed to accept connection: {err}");
1136                        continue;
1137                    }
1138                },
1139                () = &mut signal => break,
1140            };
1141
1142            let service = self.clone();
1143            let watcher = graceful.watcher();
1144            tokio::spawn(async move {
1145                let handler = service_fn(move |mut req: hyper::Request<Incoming>| {
1146                    let service = service.clone();
1147                    req.extensions_mut()
1148                        .insert(crate::context::RemoteAddr(peer));
1149                    async move { Ok::<_, Infallible>(service.call_hyper(req).await) }
1150                });
1151                let builder = auto::Builder::new(TokioExecutor::new());
1152                let conn = builder.serve_connection(TokioIo::new(stream), handler);
1153                if let Err(err) = watcher.watch(conn).await {
1154                    tracing::debug!("connection from {peer} ended with error: {err}");
1155                }
1156            });
1157        }
1158
1159        tracing::info!(target: "glacier", "shutting down");
1160        tokio::select! {
1161            () = graceful.shutdown() => {}
1162            () = tokio::time::sleep(SHUTDOWN_GRACE_PERIOD) => {
1163                tracing::warn!(target: "glacier", "grace period elapsed; dropping open connections");
1164            }
1165        }
1166        Ok(())
1167    }
1168}
1169
1170/// The innermost handler: looks up the route and runs its pipeline.
1171struct Dispatcher {
1172    router: Arc<Router>,
1173    /// Development's own pages, for paths the app doesn't route.
1174    dev: Option<Arc<Dispatcher>>,
1175}
1176
1177impl Handler for Dispatcher {
1178    fn call(&self, mut ctx: Context) -> BoxFuture<Response> {
1179        let version = crate::router::requested_version(ctx.headers());
1180        match self
1181            .router
1182            .recognize_version(ctx.method(), ctx.path(), version.as_deref())
1183        {
1184            Match::Found(route, params) => {
1185                let span = tracing::Span::current();
1186                span.record("http.route", route.pattern());
1187                span.record("otel.name", format!("{} {}", ctx.method(), route.pattern()));
1188                // What `head :ok` says it is, as Rails: the requested type.
1189                let head_type =
1190                    crate::mime::requested(params.get("format"), ctx.header(header::ACCEPT))
1191                        .unwrap_or("text/html");
1192                crate::current::set(crate::router::RouteParams(params.clone()));
1193                ctx.set_params(params);
1194                ctx.set_controller(route.label());
1195                let response = if route.stack.is_empty() {
1196                    route.handler.call(ctx)
1197                } else {
1198                    Box::pin(Next::new(route.stack.clone(), route.handler.clone()).run(ctx))
1199                };
1200                Box::pin(async move {
1201                    let mut response = response.await;
1202                    let status = response.status();
1203                    let empty = status.is_informational()
1204                        || status == StatusCode::NO_CONTENT
1205                        || status == StatusCode::NOT_MODIFIED;
1206                    if response.is_head()
1207                        && !empty
1208                        && !response.headers().contains_key(header::CONTENT_TYPE)
1209                    {
1210                        response.headers_mut().insert(
1211                            header::CONTENT_TYPE,
1212                            http::HeaderValue::from_static(head_type),
1213                        );
1214                    }
1215                    response
1216                })
1217            }
1218            Match::MethodNotAllowed(allowed) => {
1219                let allow = allowed
1220                    .iter()
1221                    .map(Method::as_str)
1222                    .collect::<Vec<_>>()
1223                    .join(", ");
1224                let mut res = Response::text("Method Not Allowed")
1225                    .with_status(StatusCode::METHOD_NOT_ALLOWED)
1226                    .with_header(header::ALLOW, allow);
1227                res.extensions_mut().insert(Bare);
1228                Box::pin(async move { res })
1229            }
1230            Match::NotFound => match &self.dev {
1231                Some(dev) => dev.call(ctx),
1232                None => Box::pin(async { Error::not_found().into_response() }),
1233            },
1234        }
1235    }
1236}
1237
1238/// The app's error pages, from `App::error_pages`.
1239#[derive(Clone, Copy)]
1240struct ErrorPages(fn(u16) -> Option<String>);
1241
1242/// An error with no body of its own, in the format the request asked for,
1243/// as Rails' public exceptions: JSON as `{"status": 404, "error": "Not
1244/// Found"}`, HTML as the app's error page (`src/views/errors/404.html`, in
1245/// its layout) or else its `public/404.html` when it has one, anything
1246/// else as the bare status line.
1247async fn public_exception(
1248    res: Response,
1249    path: &str,
1250    accept: Option<&str>,
1251    pages: Option<ErrorPages>,
1252) -> Response {
1253    // `/report.json` asks by extension; `/versions/1.0.0` has none.
1254    let format = path
1255        .rsplit('/')
1256        .next()
1257        .and_then(|segment| segment.rsplit_once('.'))
1258        .map(|(_, extension)| extension)
1259        .filter(|extension| crate::mime::for_format(extension).is_some());
1260    let status = res.status();
1261    let mut page = match crate::mime::requested(format, accept).unwrap_or("text/html") {
1262        "application/json" => Response::json(&serde_json::json!({
1263            "status": status.as_u16(),
1264            "error": status.canonical_reason().unwrap_or("Error"),
1265        })),
1266        "text/html" => match pages.and_then(|ErrorPages(render)| render(status.as_u16())) {
1267            Some(html) => Response::html(html),
1268            None => {
1269                match tokio::fs::read_to_string(format!("public/{}.html", status.as_u16())).await {
1270                    Ok(html) => Response::html(html),
1271                    Err(_) => return res,
1272                }
1273            }
1274        },
1275        _ => return res,
1276    }
1277    .with_status(status);
1278    // Keep headers such as `Allow` on a 405, and the error report.
1279    for (name, value) in res.headers() {
1280        if name != header::CONTENT_TYPE && name != header::CONTENT_LENGTH {
1281            page.headers_mut().insert(name.clone(), value.clone());
1282        }
1283    }
1284    if let Some(report) = res.extensions().get::<ErrorReport>() {
1285        page.extensions_mut().insert(report.clone());
1286    }
1287    page
1288}
1289
1290/// The development-only error page. Production shows a bare status line.
1291fn debug_page(report: &ErrorReport, method: &Method, path: &str) -> Response {
1292    let causes: String = report
1293        .causes
1294        .iter()
1295        .map(|c| format!("<li>{}</li>", escape(c)))
1296        .collect();
1297    let causes = if causes.is_empty() {
1298        String::new()
1299    } else {
1300        format!("<h2>Caused by</h2><ol>{causes}</ol>")
1301    };
1302    Response::html(format!(
1303        r#"<!doctype html>
1304<html lang="en">
1305<head><meta charset="utf-8"><title>{status} · Glacier</title>
1306<style>
1307  body {{ font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f6f8fa; color: #1f2328; }}
1308  header {{ background: #0b3d5c; color: #fff; padding: 24px 32px; }}
1309  header p {{ margin: 0; opacity: .8; font-family: ui-monospace, monospace; }}
1310  h1 {{ margin: 4px 0 0; font-size: 22px; }}
1311  main {{ padding: 24px 32px; }}
1312  pre {{ background: #fff; border: 1px solid #d0d7de; border-radius: 6px; padding: 16px; white-space: pre-wrap; }}
1313  footer {{ padding: 0 32px 24px; color: #59636e; font-size: 13px; }}
1314</style></head>
1315<body>
1316<header><p>{status} · {method} {path}</p><h1>{title}</h1></header>
1317<main><pre>{message}</pre>{causes}</main>
1318<footer>You are seeing this page because the app is running in development. Production responses show only the status.</footer>
1319</body>
1320</html>"#,
1321        status = report.status.as_u16(),
1322        method = escape(method.as_str()),
1323        path = escape(path),
1324        title = escape(report.status.canonical_reason().unwrap_or("Error")),
1325        message = escape(&report.message),
1326    ))
1327    .with_status(report.status)
1328}
1329
1330async fn shutdown_signal() {
1331    let ctrl_c = async {
1332        let _ = tokio::signal::ctrl_c().await;
1333    };
1334
1335    #[cfg(unix)]
1336    let terminate = async {
1337        use tokio::signal::unix::{SignalKind, signal};
1338        match signal(SignalKind::terminate()) {
1339            Ok(mut sigterm) => {
1340                sigterm.recv().await;
1341            }
1342            Err(_) => std::future::pending().await,
1343        }
1344    };
1345    #[cfg(not(unix))]
1346    let terminate = std::future::pending::<()>();
1347
1348    tokio::select! {
1349        () = ctrl_c => {}
1350        () = terminate => {}
1351    }
1352}
1353
1354fn panic_message(payload: &(dyn Any + Send)) -> &str {
1355    if let Some(s) = payload.downcast_ref::<&str>() {
1356        s
1357    } else if let Some(s) = payload.downcast_ref::<String>() {
1358        s
1359    } else {
1360        "<non-string panic payload>"
1361    }
1362}
1363
1364/// Whether this browser wrote within the replica delay, by its cookie.
1365fn wrote_recently(cookies: &Cookies) -> bool {
1366    cookies
1367        .get(db::LAST_WRITE_COOKIE)
1368        .and_then(|at| at.parse::<i64>().ok())
1369        .is_some_and(|at| crate::time::now().timestamp() - at < db::REPLICA_DELAY_SECONDS)
1370}
1371
1372/// A named database: given, or from `[databases.<name>]` in the config,
1373/// connected on first use.
1374#[derive(Clone)]
1375enum Named {
1376    Ready(Repo),
1377    FromConfig(Arc<tokio::sync::OnceCell<Repo>>, Config),
1378}
1379
1380/// `App::seeds`'s function, boxed.
1381type Seeds = Arc<dyn Fn() -> crate::handler::BoxFuture<Result<()>> + Send + Sync>;
1382
1383/// `Cache-Control: private` and `Vary: Cookie` on a response for a
1384/// signed-in user, so no shared cache (a CDN, a proxy) serves it to
1385/// anyone else; an action that set `Cache-Control` keeps its own.
1386fn private_by_default(response: &mut Response) {
1387    let headers = response.headers_mut();
1388    if !headers.contains_key(header::CACHE_CONTROL) {
1389        headers.insert(
1390            header::CACHE_CONTROL,
1391            http::HeaderValue::from_static("private"),
1392        );
1393    }
1394    headers.append(header::VARY, http::HeaderValue::from_static("Cookie"));
1395}