capy-framework 0.10.0

An opinionated full-stack Rust web framework with strong conventions and sensible defaults.
Documentation
//! Compile and run the exact welcome example in docs/guide.md.
#![cfg(all(feature = "auth", feature = "jobs", feature = "mail"))]
use capy_framework as capy;

// guide:begin
use capy::{
    auth::{MemoryResetDelivery, UserRegistered},
    jobs::{Job, JobContext, JobError, JobResult, Jobs},
    mail::{Mail, Mailbox, Mailer},
    prelude::*,
    sea_orm::{ConnectionTrait, Statement},
};

// Your application migration creates welcome_recipients(user_id BIGINT PRIMARY KEY,
// email TEXT NOT NULL). It is application data, not a private auth model.
async fn save_recipient(db: &impl ConnectionTrait, id: i64, email: &str) -> Result<()> {
    db.execute(Statement::from_sql_and_values(
        db.get_database_backend(),
        "INSERT INTO welcome_recipients (user_id, email) VALUES ($1, $2)",
        [id.into(), email.into()],
    ))
    .await?;
    Ok(())
}

#[derive(Serialize, Deserialize)]
#[serde(crate = "capy::serde")]
struct SendWelcome {
    user_id: i64,
}
impl SendWelcome {
    async fn deliver(self, ctx: JobContext) -> JobResult {
        let mail = ctx.service::<Mailer>()?;
        let recipient = ctx
            .db
            .query_one(Statement::from_sql_and_values(
                ctx.db.get_database_backend(),
                "SELECT email FROM welcome_recipients WHERE user_id=$1",
                [self.user_id.into()],
            ))
            .await?
            .ok_or_else(|| JobError::permanent("Recipient removed"))?;
        let email: String = recipient.try_get("", "email")?;
        mail.send_mail(
            "welcome",
            Mail::new("Welcome")
                .to(Mailbox::parse(&email).map_err(|_| JobError::permanent("Invalid recipient"))?)
                .text("Your account has been created."),
        )
        .await
        .map_err(|_| JobError::retry("Welcome delivery failed"))?;
        Ok(())
    }
}
impl Job for SendWelcome {
    const NAME: &'static str = "app.welcome";
    async fn handle(self, ctx: JobContext) -> JobResult {
        self.deliver(ctx).await
    }
}
fn application(mail: Mailer) -> App {
    App::new()
        // Development example. Production installs an application ResetDelivery.
        .auth(MemoryResetDelivery::default())
        .service(mail)
        .mail()
        .jobs(Jobs::new().register::<SendWelcome>())
        .on::<UserRegistered>(|event, ctx| {
            Box::pin(async move {
                save_recipient(ctx.transaction, event.user.id, &event.user.email).await?;
                ctx.jobs()
                    .dispatch(SendWelcome {
                        user_id: event.user.id,
                    })
                    .await?;
                if event.user.email.ends_with("@blocked.example") {
                    return Err(EventRejection::Forbidden {
                        code: "registration_not_allowed",
                        message: "Registration is not allowed for this domain.",
                    }
                    .into());
                }
                Ok(())
            })
        })
}
// guide:end

#[tokio::test]
async fn welcome_is_enqueued_before_commit_delivered_after_commit_and_rejection_rolls_back(
) -> Result<()> {
    use capy::migration::{MigrationTrait, SchemaManager};
    use capy_testing::{TestApp, TestQueue};
    use std::sync::Arc;
    let mut config = AppConfig::default();
    config.database.url = "sqlite::memory:".into();
    config.database.max_connections = 1;
    config.database.min_connections = 1;
    let db = capy::db::connect(&config.database).await?;
    let manager = SchemaManager::new(&db);
    capy::auth::migration::IdentityMigration
        .up(&manager)
        .await?;
    capy::jobs::migration::JobsMigration.up(&manager).await?;
    db.execute(Statement::from_string(
        db.get_database_backend(),
        "CREATE TABLE welcome_recipients (user_id BIGINT PRIMARY KEY, email TEXT NOT NULL)",
    ))
    .await?;
    let ctx = AppContext {
        db,
        config: Arc::new(config.clone()),
    };
    let (mail, inbox) = Mailer::capture(&config)?;
    let mut services = Services::new();
    services.insert(mail.clone());
    let queue =
        TestQueue::new(ctx.clone(), Jobs::new().register::<SendWelcome>())?.with_services(services);
    let app = TestApp::new(application(mail).into_router(ctx.clone()));
    for (email, expected) in [
        ("a@blocked.example", axum::http::StatusCode::FORBIDDEN),
        ("a@example.test", axum::http::StatusCode::CREATED),
    ] {
        let guest = app
            .get("/api/auth/csrf")
            .header("x-capy-csrf".parse().unwrap(), "1".parse().unwrap())
            .send()
            .await;
        let response = tokio::time::timeout(
            std::time::Duration::from_secs(10),
            app.post("/api/auth/register")
                .cookie(guest.cookie("session").unwrap())
                .header(
                    "x-csrf-token".parse().unwrap(),
                    guest.json::<Value>()["csrf_token"]
                        .as_str()
                        .unwrap()
                        .parse()
                        .unwrap(),
                )
                .json(
                    json!({"name":"Guide User", "email":email, "password":"a long safe password"}),
                )
                .send(),
        )
        .await
        .expect("single-connection guide must not deadlock");
        response.assert_status(expected);
        assert!(inbox.take().is_empty(), "listeners cannot deliver mail");
        if expected == axum::http::StatusCode::FORBIDDEN {
            assert_eq!(ctx.jobs().count::<SendWelcome>().await?, 0);
            let row = ctx
                .db
                .query_one(Statement::from_string(
                    ctx.db.get_database_backend(),
                    "SELECT COUNT(*) AS n FROM welcome_recipients",
                ))
                .await?
                .unwrap();
            assert_eq!(row.try_get::<i64>("", "n")?, 0);
        } else {
            assert_eq!(ctx.jobs().count::<SendWelcome>().await?, 1);
            assert!(queue.run_next_job().await?);
            let messages = inbox.take();
            assert_eq!(messages.len(), 1);
            assert!(messages[0].has_subject("Welcome"));
        }
    }
    Ok(())
}