glacier-web 0.5.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
Documentation
//! Webhooks end to end: verify, store once, answer, handle in a job,
//! replay, and side effects that happen once.

use std::sync::atomic::{AtomicUsize, Ordering};

use glacier::db::migration::Migration;
use glacier::db::{self, Repo};
use glacier::prelude::*;
use glacier::testing::TestClient;
use glacier::webhooks::{Event, Stripe, Webhooks, sign_hex};

static HANDLED: AtomicUsize = AtomicUsize::new(0);
static EMAILED: AtomicUsize = AtomicUsize::new(0);

fn signed(body: &str) -> String {
    let t = glacier::time::now().timestamp();
    format!(
        "t={t},v1={}",
        sign_hex("whsec_test", format!("{t}.{body}").as_bytes())
    )
}

async fn post(c: &TestClient, body: &str, signature: &str) -> Response {
    let req = http::Request::post("/webhooks/stripe")
        .header("content-type", "application/json")
        .header("stripe-signature", signature)
        .body(bytes::Bytes::from(body.to_owned()))
        .unwrap();
    c.request(req).await
}

async fn rows(repo: &Repo) -> Vec<(String, String, i64)> {
    db::with(repo, async {
        let rows = db::sql("SELECT event_id, status, attempts FROM webhook_events ORDER BY id")
            .fetch_all()
            .await?;
        rows.iter()
            .map(|r| {
                Ok((
                    r.get("event_id")?,
                    r.get("status")?,
                    r.get::<i64>("attempts")?,
                ))
            })
            .collect::<glacier::Result<Vec<_>>>()
    })
    .await
    .unwrap()
}

#[tokio::test]
async fn stripe_events_are_stored_once_and_handled_in_jobs() {
    let repo = Repo::connect("sqlite::memory:").await.unwrap();
    db::with(&repo, async {
        let migration = Migration::new(
            "m1",
            |s| {
                glacier::jobs::create_table(s);
                glacier::jobs::upgrade_table(s);
                glacier::webhooks::create_table(s);
            },
            |_| {},
        );
        for statement in migration.up_sql(repo.dialect()) {
            db::sql(&statement).execute().await.unwrap();
        }
    })
    .await;
    let webhooks = Webhooks::new().provider(
        Stripe::new(&["whsec_old", "whsec_test"])
            .on("charge.succeeded", |event: Event| async move {
                HANDLED.fetch_add(1, Ordering::SeqCst);
                event
                    .once("receipt", async {
                        EMAILED.fetch_add(1, Ordering::SeqCst);
                        Ok(())
                    })
                    .await?;
                Ok(())
            })
            .on("charge.failed", |_event: Event| async {
                Err(Error::internal("card declined handling broke"))
            }),
    );
    let c = TestClient::new(
        App::new()
            .env(glacier::Env::Test)
            .database(repo.clone())
            .webhooks(webhooks)
            .routes(|r| {
                r.post("/webhooks/:provider", glacier::webhooks::receive);
            }),
    );
    let jobs = Jobs::new();
    let perform = || db::with(&repo, jobs.perform_due());

    // A bad signature is refused, and nothing is kept.
    let body = r#"{"id":"evt_1","type":"charge.succeeded","data":{"object":{"amount":500}}}"#;
    let res = post(&c, body, "t=1,v1=00").await;
    assert_eq!(res.status(), StatusCode::BAD_REQUEST);
    assert!(rows(&repo).await.is_empty());

    // A good one is stored and answered at once; a worker handles it.
    let res = post(&c, body, &signed(body)).await;
    assert_eq!(
        (res.status(), res.body_text().as_str()),
        (StatusCode::OK, "ok")
    );
    assert_eq!(
        rows(&repo).await,
        [("evt_1".to_owned(), "received".to_owned(), 0)]
    );
    assert_eq!(perform().await.unwrap(), 1);
    assert_eq!(
        rows(&repo).await,
        [("evt_1".to_owned(), "processed".to_owned(), 1)]
    );
    assert_eq!(
        (
            HANDLED.load(Ordering::SeqCst),
            EMAILED.load(Ordering::SeqCst)
        ),
        (1, 1)
    );

    // Stripe sends it again: still one row, and nothing queued.
    assert_eq!(post(&c, body, &signed(body)).await.status(), StatusCode::OK);
    assert_eq!(rows(&repo).await.len(), 1);
    assert_eq!(perform().await.unwrap(), 0);

    // Replayed: handled again, but the receipt isn't sent twice.
    let id = db::with(&repo, db::sql("SELECT id FROM webhook_events").fetch_all())
        .await
        .unwrap()[0]
        .get::<i64>("id")
        .unwrap();
    assert!(db::with(&repo, Webhooks::replay(id)).await.unwrap());
    assert_eq!(perform().await.unwrap(), 1);
    assert_eq!(
        (
            HANDLED.load(Ordering::SeqCst),
            EMAILED.load(Ordering::SeqCst)
        ),
        (2, 1)
    );

    // An event nothing handles isn't kept.
    let other = r#"{"id":"evt_2","type":"customer.created"}"#;
    let res = post(&c, other, &signed(other)).await;
    assert_eq!(res.body_text(), "ignored");
    assert_eq!(rows(&repo).await.len(), 1);

    // A failing handler is marked failed, with its error, and retried later.
    let failing = r#"{"id":"evt_3","type":"charge.failed"}"#;
    post(&c, failing, &signed(failing)).await;
    assert_eq!(perform().await.unwrap(), 1);
    let (status, error): (String, String) = db::with(&repo, async {
        let rows =
            db::sql("SELECT status, last_error FROM webhook_events WHERE event_id = 'evt_3'")
                .fetch_all()
                .await?;
        Ok::<_, glacier::Error>((rows[0].get("status")?, rows[0].get("last_error")?))
    })
    .await
    .unwrap();
    assert_eq!(status, "failed");
    assert!(error.contains("card declined handling broke"), "{error}");
    let queued = db::with(
        &repo,
        db::sql("SELECT attempts FROM glacier_jobs WHERE failed_at IS NULL").fetch_all(),
    )
    .await
    .unwrap();
    assert_eq!(queued.len(), 1, "the job will try again");
}