glacier-web 0.4.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! JSON APIs: `json!`, validation errors as Rails renders them, JSON error
//! responses from `Pipeline::api()`, and `params.require`.

use glacier::db::migration::Migration;
use glacier::db::{self, Repo};
use glacier::middleware::Pipeline;
use glacier::prelude::*;
use glacier::testing::TestClient;

#[glacier::model]
pub struct Post {
    #[validate(required)]
    title: String,
    body: Option<String>,
}

pub struct Posts;

#[glacier::controller]
impl Posts {
    async fn show(ctx: Context) -> Result<Response> {
        let post = Post::find(ctx.id()?).await?;
        glacier::json!(post)
    }

    async fn create(ctx: Context) -> Result<Response> {
        let mut post = Post::build(ctx.params().require("post")?);
        if post.save().await? {
            glacier::json!(post, status = 201)
        } else {
            glacier::json!(post.errors_json(), status = "unprocessable_entity")
        }
    }

    /// Only the controller's own key is wrapped: this 400s on a bare body.
    async fn publish(ctx: Context) -> Result<Response> {
        let options = ctx.params().require("options")?;
        glacier::json!(options.get("when"))
    }

    /// `fetch`: the key must be there, but may be empty.
    async fn touch(ctx: Context) -> Result<Response> {
        let post = ctx.params().fetch("post")?;
        glacier::json!(post.get("title"))
    }

    async fn locked(_ctx: Context) -> Response {
        Response::head(StatusCode::PRECONDITION_FAILED)
    }
}

async fn client() -> TestClient {
    let repo = Repo::connect("sqlite::memory:").await.unwrap();
    db::with(&repo, async {
        let migration = Migration::new(
            "m1",
            |s| {
                s.create_table("posts", |t| {
                    t.string("title").not_null();
                    t.text("body");
                    t.timestamps();
                })
            },
            |_| {},
        );
        for statement in migration.up_sql(repo.dialect()) {
            db::sql(&statement).execute().await.unwrap();
        }
    })
    .await;
    TestClient::new(App::new().env(Env::Test).database(repo).routes(|r| {
        r.pipe_through(&Pipeline::api(), |r| {
            r.get("/posts/:id", Posts::show);
            r.post("/posts", Posts::create);
            r.post("/posts/publish", Posts::publish);
            r.post("/posts/touch", Posts::touch);
            r.get("/posts/locked", Posts::locked);
        });
    }))
}

fn json(res: &Response) -> serde_json::Value {
    serde_json::from_str(&res.body_text()).unwrap()
}

#[glacier::test]
async fn creates_and_shows_records_as_json() {
    let c = client().await;
    let res = c
        .post_json(
            "/posts",
            &serde_json::json!({"post": {"title": "Hi", "body": "There"}}),
        )
        .await;
    assert_eq!(res.status(), StatusCode::CREATED, "{}", res.body_text());
    assert_eq!(
        res.header("content-type"),
        Some("application/json; charset=utf-8")
    );
    let created = json(&res);
    assert_eq!(created["title"], "Hi");
    assert!(
        created.get("__record").is_none(),
        "record state stays private"
    );

    let id = created["id"].as_i64().unwrap();
    let shown = json(&c.get(&format!("/posts/{id}")).await);
    assert_eq!(shown["body"], "There");
}

#[glacier::test]
async fn validation_errors_are_422_in_rails_shape() {
    let c = client().await;
    let res = c
        .post_json("/posts", &serde_json::json!({"post": {"title": ""}}))
        .await;
    assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY);
    assert_eq!(json(&res), serde_json::json!({"title": ["can't be blank"]}));
}

#[glacier::test]
async fn errors_are_json_on_the_api_pipeline() {
    let c = client().await;
    let missing = c.get("/posts/999").await;
    assert_eq!(missing.status(), StatusCode::NOT_FOUND);
    assert_eq!(
        json(&missing),
        serde_json::json!({"status": 404, "error": "Not Found"})
    );

    // As Rails' wrap_parameters: a bare JSON body counts as `{"post": …}`.
    let unwrapped = c
        .post_json("/posts", &serde_json::json!({"title": "No wrapper"}))
        .await;
    assert_eq!(
        unwrapped.status(),
        StatusCode::CREATED,
        "{}",
        unwrapped.body_text()
    );
    assert_eq!(json(&unwrapped)["title"], "No wrapper");

    let not_ours = c
        .post_json("/posts/publish", &serde_json::json!({"when": "now"}))
        .await;
    assert_eq!(
        not_ours.status(),
        StatusCode::BAD_REQUEST,
        "only `post` wraps"
    );
    let locked = c.get("/posts/locked").await;
    assert_eq!(locked.status(), StatusCode::PRECONDITION_FAILED);
    assert!(
        locked.body().is_empty(),
        "head stays empty on the API pipeline"
    );
    // Typed as the request asked, as Rails' `head`: the format, else the
    // Accept header, else HTML.
    assert_eq!(locked.header("content-type"), Some("text/html"));
    let typed = c.get("/posts/locked.json").await;
    assert_eq!(typed.header("content-type"), Some("application/json"));
    c.header("accept", "text/csv");
    let typed = c.get("/posts/locked").await;
    assert_eq!(typed.header("content-type"), Some("text/csv"));
    c.header("accept", "*/*");

    let empty = c.post_json("/posts", &serde_json::json!({})).await;
    assert_eq!(empty.status(), StatusCode::BAD_REQUEST);
    assert_eq!(json(&empty)["error"], "Bad Request");

    // `fetch` takes an empty value, and in JSON the wrapper always gives
    // the controller's key, as Rails' `params.fetch(:post)`.
    for body in [
        serde_json::json!({"post": {}}),
        serde_json::json!({"other": 1}),
    ] {
        let res = c.post_json("/posts/touch", &body).await;
        assert_eq!(res.status(), StatusCode::OK, "{body}");
    }
    let res = c
        .post_json("/posts/touch", &serde_json::json!({"title": "T"}))
        .await;
    assert_eq!(json(&res), "T");

    let wrong_method = c.delete("/posts/1").await;
    assert_eq!(wrong_method.status(), StatusCode::METHOD_NOT_ALLOWED);
    assert!(wrong_method.header("allow").is_some(), "headers survive");
}

#[test]
fn lists_read_repeated_fields_json_arrays_and_single_values() {
    let repeated: Params = [("ids[]", "1"), ("ids[]", "2"), ("other", "x")]
        .into_iter()
        .collect();
    assert_eq!(repeated.list("ids"), ["1", "2"]);
    let json: Params = [("ids", "[3, \"4\"]")].into_iter().collect();
    assert_eq!(json.list("ids"), ["3", "4"]);
    let single: Params = [("ids", "5")].into_iter().collect();
    assert_eq!(single.list("ids"), ["5"]);
    assert!(single.list("missing").is_empty());
}

#[tokio::test]
async fn gets_carry_etags_and_answer_not_modified() {
    let c = client().await;
    let created = c
        .post_json("/posts", &serde_json::json!({"post": {"title": "Tagged"}}))
        .await;
    assert!(
        created.header("etag").is_some(),
        "a 201 is tagged too, as Rails"
    );
    let id = json(&created)["id"].as_i64().unwrap();
    let first = c.get(&format!("/posts/{id}")).await;
    let tag = first.header("etag").unwrap().to_owned();
    assert!(tag.starts_with("W/\""), "{tag}");
    assert_eq!(
        first.header("cache-control"),
        Some("max-age=0, private, must-revalidate")
    );

    c.header("if-none-match", &tag);
    let again = c.get(&format!("/posts/{id}")).await;
    assert_eq!(again.status(), StatusCode::NOT_MODIFIED);
    assert!(again.body().is_empty());
    assert_eq!(again.header("etag"), Some(tag.as_str()));
    c.header("if-none-match", "W/\"something-else\"");
    assert_eq!(
        c.get(&format!("/posts/{id}")).await.status(),
        StatusCode::OK
    );
    // Not a success: not to be cached.
    let missing = c.get("/posts/424242").await;
    assert_eq!(missing.header("cache-control"), Some("no-cache"));
}

#[test]
fn require_reads_nested_json_and_form_fields() {
    let json: Params = [("post", r#"{"title":"T","views":3,"draft":null}"#)]
        .into_iter()
        .collect();
    let post = json.require("post").unwrap();
    assert_eq!(
        (post.get("title"), post.get("views"), post.get("draft")),
        (Some("T"), Some("3"), Some(""))
    );
    let form: Params = [("post[title]", "F"), ("other", "x")].into_iter().collect();
    assert_eq!(form.require("post").unwrap().get("title"), Some("F"));
    let empty: Params = [("post", "{}")].into_iter().collect();
    assert!(empty.require("post").is_err(), "require wants a value");
    assert!(empty.fetch("post").unwrap().iter().next().is_none());
    assert!(form.fetch("comment").is_err(), "fetch wants the key");
    let err = form.require("comment").unwrap_err();
    assert!(
        err.to_string()
            .contains("param is missing or the value is empty: comment"),
        "{err}"
    );
}

#[tokio::test]
async fn conditional_gets_answer_not_modified() {
    let updated = chrono::DateTime::parse_from_rfc3339("2026-10-01T10:52:12.5Z")
        .unwrap()
        .to_utc();
    let c = TestClient::new(App::new().env(Env::Test).routes(move |r| {
        r.get("/thing", move |ctx: Context| async move {
            Response::json(&serde_json::json!({"id": 1})).fresh_when(&ctx, updated)
        });
    }));
    let first = c.get("/thing").await;
    assert_eq!(first.status(), StatusCode::OK);
    assert_eq!(
        first.header("last-modified"),
        Some("Thu, 01 Oct 2026 10:52:12 GMT")
    );
    let etag = first.header("etag").unwrap().to_owned();
    assert!(etag.starts_with("W/\""), "{etag}");

    c.header("if-modified-since", "Thu, 01 Oct 2026 10:52:12 GMT");
    let same = c.get("/thing").await;
    assert_eq!(same.status(), StatusCode::NOT_MODIFIED);
    assert!(same.body().is_empty());
    c.header("if-modified-since", "Thu, 01 Oct 2026 10:52:11 GMT");
    assert_eq!(
        c.get("/thing").await.status(),
        StatusCode::OK,
        "changed since"
    );
    c.header("if-none-match", &etag);
    assert_eq!(
        c.get("/thing").await.status(),
        StatusCode::NOT_MODIFIED,
        "the etag wins"
    );
}

#[tokio::test]
async fn answers_cross_origin_requests_as_rack_cors() {
    let c = TestClient::new(
        App::new()
            .env(Env::Test)
            .middleware(
                glacier::middleware::Cors::any_origin()
                    .methods(["GET", "POST", "PUT", "PATCH", "OPTIONS", "DELETE"])
                    .expose(["Authorization", "Content-Disposition"]),
            )
            .routes(|r| {
                r.get("/things", |_ctx: Context| async { "ok" });
            }),
    );
    let preflight = http::Request::builder()
        .method("OPTIONS")
        .uri("/things")
        .header("origin", "https://app.example.com")
        .header("access-control-request-method", "GET")
        .header(
            "access-control-request-headers",
            "Authorization, Content-Type",
        )
        .body(bytes::Bytes::new())
        .unwrap();
    let res = c.request(preflight).await;
    assert_eq!(res.status(), StatusCode::OK);
    assert!(res.body().is_empty());
    assert_eq!(res.header("access-control-allow-origin"), Some("*"));
    assert_eq!(
        res.header("access-control-allow-methods"),
        Some("GET, POST, PUT, PATCH, OPTIONS, DELETE")
    );
    assert_eq!(
        res.header("access-control-allow-headers"),
        Some("Authorization, Content-Type")
    );
    assert_eq!(res.header("access-control-max-age"), Some("7200"));

    c.header("origin", "https://app.example.com");
    let res = c.get("/things").await;
    assert_eq!(
        res.header("access-control-expose-headers"),
        Some("Authorization, Content-Disposition")
    );
    assert_eq!(res.header("vary"), Some("Origin"));
}

#[tokio::test]
async fn require_finds_a_key_sent_only_as_a_file() {
    let app = App::new().routes(|r| {
        r.post("/comments", |ctx: Context| async move {
            let comment = ctx.params().require("comment")?;
            let file = ctx
                .file("comment[note_image]")
                .map(|f| f.filename)
                .unwrap_or_default();
            Ok::<_, Error>(format!("{} {file}", comment.get("note").unwrap_or("none")))
        });
    });
    let client = TestClient::new(app);
    let boundary = "glacierboundary";
    let body = format!(
        "--{boundary}\r\nContent-Disposition: form-data; name=\"comment[note_image]\"; filename=\"shelf.png\"\r\n\
         Content-Type: image/png\r\n\r\nPNG\r\n--{boundary}--\r\n"
    );
    let request = http::Request::post("/comments")
        .header(
            "content-type",
            format!("multipart/form-data; boundary={boundary}"),
        )
        .body(bytes::Bytes::from(body))
        .unwrap();
    let res = client.request(request).await;
    assert_eq!(
        res.body_text(),
        "none shelf.png",
        "as Rails: a file is a param"
    );
}