capy-framework 0.10.0

An opinionated full-stack Rust web framework with strong conventions and sensible defaults.
Documentation
//! The application factory supplies the same typed dependencies to HTTP and workers.
#![cfg(all(feature = "testing", feature = "jobs", feature = "mail"))]

use capy_framework::{
    self as capy,
    jobs::{Job, JobContext, JobError, JobResult, Jobs},
    mail::{Mail, Mailbox, Mailer},
    migration::{MigrationTrait, MigratorTrait},
    prelude::*,
    testing::TestApp,
};
use std::sync::{
    atomic::{AtomicUsize, Ordering},
    Arc,
};

#[derive(Clone, Debug)]
struct Counter(Arc<AtomicUsize>);

async fn count(Service(counter): Service<Counter>) -> Json<Value> {
    Json(json!({"count": counter.0.load(Ordering::SeqCst)}))
}

#[derive(Serialize, Deserialize)]
#[serde(crate = "capy::serde")]
struct CountAndMail;

impl Job for CountAndMail {
    const NAME: &'static str = "test.count_and_mail";

    async fn handle(self, ctx: JobContext) -> JobResult {
        let counter = ctx.service::<Counter>()?;
        let mailer = ctx.service::<Mailer>()?;
        counter.0.fetch_add(1, Ordering::SeqCst);
        mailer
            .send_mail(
                "welcome",
                Mail::new("Welcome")
                    .to(Mailbox::parse("reader@example.test")
                        .map_err(|_| JobError::permanent("Invalid test address"))?)
                    .text("Hello"),
            )
            .await
            .map_err(|_| JobError::retry("Mail delivery failed"))?;
        Ok(())
    }
}

struct Migrator;
#[capy::migration::async_trait::async_trait]
impl MigratorTrait for Migrator {
    fn migrations() -> Vec<Box<dyn MigrationTrait>> {
        vec![Box::new(capy::jobs::migration::JobsMigration)]
    }
}

fn application(counter: Counter) -> App<Migrator> {
    App::new()
        .config(AppConfig::default())
        .service(counter)
        .mail()
        .jobs(Jobs::new().register::<CountAndMail>())
        .api_routes(Routes::new().get("/count", count))
        .migrations(Migrator)
}

#[tokio::test]
async fn captured_mail_and_custom_services_reach_the_real_worker() -> Result<()> {
    let first = Counter(Arc::new(AtomicUsize::new(0)));
    let second = Counter(Arc::new(AtomicUsize::new(0)));
    let (one, two) = tokio::try_join!(
        TestApp::builder(application(first.clone()))
            .capture_mail()
            .boot(),
        TestApp::builder(application(second.clone()))
            .capture_mail()
            .boot()
    )?;

    assert!(Arc::ptr_eq(&one.service::<Counter>()?.0, &first.0));
    one.get("/api/count")
        .send()
        .await
        .assert_json(json!({"count": 0}));
    one.jobs().queue().dispatch(CountAndMail).await?;
    assert_eq!(one.jobs().drain(1).await?, 1);
    one.get("/api/count")
        .send()
        .await
        .assert_json(json!({"count": 1}));
    two.get("/api/count")
        .send()
        .await
        .assert_json(json!({"count": 0}));
    one.mail().assert_sent_to("reader@example.test");
    assert!(two.mail().sent().is_empty());

    one.cleanup().await?;
    two.cleanup().await?;
    Ok(())
}

#[test]
fn missing_services_are_actionable_and_debug_is_payload_free() {
    let mut services = Services::new();
    let missing = services.get::<Counter>().unwrap_err().to_string();
    assert!(missing.contains("Counter"));
    assert!(missing.contains("App::service"));
    services.insert(String::from("private-service-secret"));
    assert!(!format!("{services:?}").contains("private-service-secret"));
}