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";
const HEALTH_CHECK_TIMEOUT: Duration = Duration::from_secs(2);
const TASK_VAR: &str = "GLACIER_TASK";
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(),
}
}
pub fn telemetry(mut self, telemetry: Telemetry) -> Self {
if telemetry.is_enabled() {
self.telemetry.push(telemetry);
}
self
}
pub fn health_check(mut self, path: &str) -> Self {
self.health_check = Some(path.into());
self
}
pub fn without_health_check(mut self) -> Self {
self.health_check = None;
self
}
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))
}
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)
}
pub fn database(mut self, repo: Repo) -> Self {
self.repo = Some(repo.clone());
self.state(repo)
}
pub fn migrations(mut self, migrations: Vec<Migration>) -> Self {
self.migrations = migrations;
self
}
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
}
pub fn middleware(mut self, middleware: impl Middleware) -> Self {
self.middleware.push(Arc::new(middleware));
self
}
pub fn jobs(self, jobs: crate::jobs::Jobs) -> Self {
self.state(jobs)
}
pub fn state<T: Clone + Send + Sync + 'static>(mut self, value: T) -> Self {
self.state.insert(value);
self
}
pub fn max_body_size(mut self, bytes: usize) -> Self {
self.max_body_size = bytes;
self
}
pub fn build(self) -> Service {
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)),
}),
}
}
pub async fn serve(self, addr: impl ToSocketAddrs) -> Result<()> {
self.build().serve(addr).await
}
}
#[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>,
telemetry: std::sync::Mutex<Vec<Telemetry>>,
}
impl Service {
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
}
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());
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());
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()
}),
};
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"));
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())
}
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()
}
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;
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())
}
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}"),
}
}
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(())
}
}
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()));
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() }),
}
}
}
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>"
}
}