glacier-web 0.1.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! HTTP responses and the `IntoResponse` conversion trait.

use bytes::Bytes;
use http::{Extensions, HeaderMap, HeaderName, HeaderValue, StatusCode, header};
use http_body_util::Full;
use serde::Serialize;

use crate::error::Error;

/// Marks a [`Response::head`] response.
#[derive(Debug, Clone, Copy)]
struct Head;

/// A fully buffered HTTP response.
#[derive(Debug, Clone)]
pub struct Response {
    status: StatusCode,
    headers: HeaderMap,
    body: Bytes,
    extensions: Extensions,
}

impl Default for Response {
    fn default() -> Self {
        Self::new(StatusCode::OK)
    }
}

impl Response {
    /// An empty response with the given status.
    pub fn new(status: StatusCode) -> Self {
        Self {
            status,
            headers: HeaderMap::new(),
            body: Bytes::new(),
            extensions: Extensions::new(),
        }
    }

    pub fn text(body: impl Into<String>) -> Self {
        Self::with_body(body.into(), "text/plain; charset=utf-8")
    }

    pub fn html(body: impl Into<String>) -> Self {
        Self::with_body(body.into(), "text/html; charset=utf-8")
    }

    /// Serializes `value` as JSON. Serialization failures become a 500.
    /// With [`escape_html_entities_in_json`] on, `<`, `>` and `&` are
    /// written `\u003c`, `\u003e` and `\u0026`, as Rails writes them.
    pub fn json<T: Serialize + ?Sized>(value: &T) -> Self {
        match serde_json::to_vec(value) {
            Ok(body) if ESCAPE_HTML.load(std::sync::atomic::Ordering::Relaxed) => {
                Self::with_body(escape_html(&body), "application/json; charset=utf-8")
            }
            Ok(body) => Self::with_body(body, "application/json; charset=utf-8"),
            Err(err) => Error::from(err).into_response(),
        }
    }

    /// A `303 See Other` redirect, the right status after a form submission.
    pub fn redirect(location: &str) -> Self {
        Self::new(StatusCode::SEE_OTHER).with_header(header::LOCATION, location)
    }

    /// A response with only a status and no body, as Rails' `head :ok`.
    /// Error statuses stay empty too: `Pipeline::api` leaves them be.
    pub fn head(status: StatusCode) -> Self {
        let mut response = Self::new(status);
        response.extensions.insert(Head);
        response
    }

    pub fn no_content() -> Self {
        Self::new(StatusCode::NO_CONTENT)
    }

    fn with_body(body: impl Into<Bytes>, content_type: &'static str) -> Self {
        let mut res = Self::new(StatusCode::OK);
        res.body = body.into();
        res.headers
            .insert(header::CONTENT_TYPE, HeaderValue::from_static(content_type));
        res
    }

    /// Replaces the body, leaving headers untouched.
    pub fn with_body_bytes(mut self, body: impl Into<Bytes>) -> Self {
        self.body = body.into();
        self
    }

    pub fn with_status(mut self, status: StatusCode) -> Self {
        self.status = status;
        self
    }

    /// Sets a header, replacing any existing value. Invalid names or values
    /// are dropped with a warning rather than panicking mid-request.
    pub fn with_header<K, V>(mut self, name: K, value: V) -> Self
    where
        K: TryInto<HeaderName>,
        V: TryInto<HeaderValue>,
    {
        match (name.try_into(), value.try_into()) {
            (Ok(name), Ok(value)) => {
                self.headers.insert(name, value);
            }
            _ => tracing::warn!("ignoring invalid response header"),
        }
        self
    }

    pub fn status(&self) -> StatusCode {
        self.status
    }

    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    pub fn headers_mut(&mut self) -> &mut HeaderMap {
        &mut self.headers
    }

    pub fn header(&self, name: impl http::header::AsHeaderName) -> Option<&str> {
        self.headers.get(name).and_then(|v| v.to_str().ok())
    }

    /// Data attached for middleware further up the stack; never sent to
    /// the client.
    pub fn extensions(&self) -> &Extensions {
        &self.extensions
    }

    pub fn extensions_mut(&mut self) -> &mut Extensions {
        &mut self.extensions
    }

    pub fn body(&self) -> &Bytes {
        &self.body
    }

    /// This response for a conditional GET, as Rails' `stale?`/`fresh_when`:
    /// it gets `Last-Modified` and a weak `ETag` of its body, and becomes an
    /// empty `304 Not Modified` when the request's `If-None-Match` matches
    /// the ETag, or (without one) its `If-Modified-Since` isn't older than
    /// `last_modified`.
    ///
    /// ```ignore
    /// Response::json(&action).fresh_when(&ctx, action.updated_at.and_utc())
    /// ```
    pub fn fresh_when(
        mut self,
        ctx: &crate::Context,
        last_modified: chrono::DateTime<chrono::Utc>,
    ) -> Self {
        use sha2::Digest;
        let modified = last_modified
            .format("%a, %d %b %Y %H:%M:%S GMT")
            .to_string();
        let digest = sha2::Sha256::digest(&self.body);
        let etag = format!(
            "W/\"{}\"",
            digest[..16]
                .iter()
                .map(|b| format!("{b:02x}"))
                .collect::<String>()
        );
        let fresh = match ctx.header(header::IF_NONE_MATCH) {
            Some(tags) => tags
                .split(',')
                .any(|tag| tag.trim() == etag || tag.trim() == "*"),
            None => ctx
                .header(header::IF_MODIFIED_SINCE)
                .and_then(crate::time::parse_http_date)
                .is_some_and(|since| since.timestamp() >= last_modified.timestamp()),
        };
        if let Ok(value) = HeaderValue::from_str(&modified) {
            self.headers.insert(header::LAST_MODIFIED, value);
        }
        if let Ok(value) = HeaderValue::from_str(&etag) {
            self.headers.insert(header::ETAG, value);
        }
        if fresh && self.status == StatusCode::OK {
            self.status = StatusCode::NOT_MODIFIED;
            self.body = Bytes::new();
            self.headers.remove(header::CONTENT_TYPE);
        }
        self
    }

    /// Whether this is a [`head`](Self::head) response, meant to be empty.
    pub fn is_head(&self) -> bool {
        self.extensions.get::<Head>().is_some()
    }

    /// The body decoded as UTF-8 (lossily). Mostly useful in tests.
    pub fn body_text(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }

    /// The body parsed as JSON (`null` if it isn't). Mostly useful in
    /// tests: `res.body_json()["id"]`.
    pub fn body_json(&self) -> serde_json::Value {
        serde_json::from_slice(&self.body).unwrap_or_default()
    }

    pub(crate) fn into_http(self) -> http::Response<Full<Bytes>> {
        let mut res = http::Response::new(Full::new(self.body));
        *res.status_mut() = self.status;
        *res.headers_mut() = self.headers;
        res
    }
}

/// Anything a handler can return.
pub trait IntoResponse {
    fn into_response(self) -> Response;
}

static ESCAPE_HTML: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);

/// Writes `<`, `>`, `&`, U+2028 and U+2029 in JSON responses as `\u` escapes,
/// as Rails does by default (`escape_html_entities_in_json`), so JSON put
/// into a page can't close a `<script>`. Call it once at startup.
pub fn escape_html_entities_in_json(on: bool) {
    ESCAPE_HTML.store(on, std::sync::atomic::Ordering::Relaxed);
}

/// The escaping itself. These characters only appear inside JSON strings,
/// so replacing them anywhere is safe.
fn escape_html(json: &[u8]) -> Vec<u8> {
    let text = String::from_utf8_lossy(json);
    let mut out = String::with_capacity(text.len());
    for c in text.chars() {
        match c {
            '<' => out.push_str("\\u003c"),
            '>' => out.push_str("\\u003e"),
            '&' => out.push_str("\\u0026"),
            '\u{2028}' => out.push_str("\\u2028"),
            '\u{2029}' => out.push_str("\\u2029"),
            c => out.push(c),
        }
    }
    out.into_bytes()
}

#[cfg(test)]
mod escape_tests {
    #[test]
    fn escapes_as_rails_does() {
        let json = br#"{"url":"/a?b=1&c=<x>"}"#;
        assert_eq!(
            String::from_utf8(super::escape_html(json)).unwrap(),
            r#"{"url":"/a?b=1\u0026c=\u003cx\u003e"}"#
        );
    }
}

impl IntoResponse for Response {
    fn into_response(self) -> Response {
        self
    }
}

impl IntoResponse for &'static str {
    fn into_response(self) -> Response {
        Response::text(self)
    }
}

impl IntoResponse for String {
    fn into_response(self) -> Response {
        Response::text(self)
    }
}

impl IntoResponse for StatusCode {
    fn into_response(self) -> Response {
        Response::new(self)
    }
}

impl<R: IntoResponse> IntoResponse for (StatusCode, R) {
    fn into_response(self) -> Response {
        self.1.into_response().with_status(self.0)
    }
}

impl<R: IntoResponse, E: IntoResponse> IntoResponse for Result<R, E> {
    fn into_response(self) -> Response {
        match self {
            Ok(r) => r.into_response(),
            Err(e) => e.into_response(),
        }
    }
}

/// An HTML response body.
#[derive(Debug, Clone)]
pub struct Html<T>(pub T);

impl<T: Into<String>> IntoResponse for Html<T> {
    fn into_response(self) -> Response {
        Response::html(self.0)
    }
}

/// A JSON response body.
#[derive(Debug, Clone)]
pub struct Json<T>(pub T);

impl<T: Serialize> IntoResponse for Json<T> {
    fn into_response(self) -> Response {
        Response::json(&self.0)
    }
}

/// A response status from a number (`201`), a [`StatusCode`] or a
/// snake_case name (`"created"`, `"unprocessable_entity"`), for
/// `json!(…, status = …)` and `.glacier`'s `status: :created`.
pub trait IntoStatus {
    fn into_status(self) -> StatusCode;
}

impl IntoStatus for StatusCode {
    fn into_status(self) -> StatusCode {
        self
    }
}

impl IntoStatus for u16 {
    #[track_caller]
    fn into_status(self) -> StatusCode {
        StatusCode::from_u16(self).unwrap_or_else(|_| panic!("{self} isn't an HTTP status"))
    }
}

impl IntoStatus for i32 {
    #[track_caller]
    fn into_status(self) -> StatusCode {
        u16::try_from(self)
            .ok()
            .and_then(|code| StatusCode::from_u16(code).ok())
            .unwrap_or_else(|| panic!("{self} isn't an HTTP status"))
    }
}

impl IntoStatus for &str {
    /// # Panics
    ///
    /// On a name no status has, so a typo fails loudly.
    #[track_caller]
    fn into_status(self) -> StatusCode {
        status_named(self).unwrap_or_else(|| panic!("no HTTP status is called `:{self}`"))
    }
}

/// The snake_case name of a status: `see_other`, `unprocessable_entity`.
pub fn status_name(status: StatusCode) -> String {
    let reason = status.canonical_reason().unwrap_or(status.as_str());
    reason
        .to_ascii_lowercase()
        .replace(['-', '\''], "")
        .split(|c: char| !c.is_ascii_alphanumeric())
        .filter(|word| !word.is_empty())
        .collect::<Vec<_>>()
        .join("_")
}

/// The status with this snake_case name, if any.
pub fn status_named(name: &str) -> Option<StatusCode> {
    (100..600)
        .filter_map(|code| StatusCode::from_u16(code).ok())
        .find(|status| status_name(*status) == name)
}