ulo
ulo
Documentation

Start here

Coming from NestJSNestJS topics, mapped

The model

Protocols

Integrations

RecipesServe static filesCompress responsesSecurity headers and CSRFSessions with tower-sessionsCookies with tower-cookiesRequest IDsAccess logError reporting with SentryLocalised responses with FluentA client as a providerA MongoDB ODM over the injected clientExplicit transactions with SQLxA mailer over lettreObject storage over the AWS SDKA CLI command with clapMocks with mockallFeature flags with OpenFeatureAuthorization with CedarMoving from axum or actix-web

Operating

Reference

Recipes

A mailer over lettre

An SMTP transport built at startup with a bounded connection test, behind a Mailer trait that a test replaces with a fake.

Sending mail needs a transport configured once, a sender address, and a way to fake both in tests. This recipe builds lettre's async SMTP transport as a singleton, checks the server answers before the application starts serving, and hides it behind a Mailer trait. It was compiled and run against Mailpit, a local SMTP catcher, in a container.

Versions compiled with: lettre 0.11.23, ulo 0.1.0-alpha.3.

Cargo.toml
[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-http = "=0.1.0-alpha.3"
lettre = { version = "0.11", default-features = false, features = ["builder", "smtp-transport", "tokio1-rustls", "ring", "webpki-roots", "hostname"] }
serde = { version = "1", features = ["derive"] }

The code

src/mail.rs
use std::future::Future;
use std::pin::Pin;
use std::time::Duration;

use lettre::message::Mailbox;
use lettre::transport::smtp::authentication::Credentials;
use lettre::{AsyncSmtpTransport, AsyncTransport, Message, Tokio1Executor};
use serde::{Deserialize, Serialize};
use ulo::{App, AppBuilder, BoxError, Dep, Module, ModuleDef, ModuleIdentity, Secret, controller, handlers, injectable};
use ulo_http::{CallError, ErrorKind, Json};

pub type Smtp = AsyncSmtpTransport<Tokio1Executor>;

#[derive(Clone, PartialEq, Eq, Hash)]
pub struct MailOptions {
    pub host: String,
    pub port: u16,
    /// Plain SMTP with no TLS, for a local catcher. Production uses STARTTLS.
    pub plaintext: bool,
    pub login: Option<(String, Secret<String>)>,
    pub from: String,
}

/// The sender address, a value of its own so a provider can take it as a dependency.
pub struct MailFrom(pub Mailbox);

#[derive(Debug)]
pub struct MailError(pub BoxError);

impl std::fmt::Display for MailError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "mail was not sent: {}", self.0)
    }
}

impl std::error::Error for MailError {}

pub struct Outgoing {
    pub to: Mailbox,
    pub subject: String,
    pub body: String,
}

/// What the rest of the application depends on. A test replaces it; production binds `SmtpMailer`.
pub trait Mailer: Send + Sync {
    fn send(&self, mail: Outgoing) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + '_>>;
}

#[injectable]
pub struct SmtpMailer {
    transport: Dep<Smtp>,
    from: Dep<MailFrom>,
}

impl Mailer for SmtpMailer {
    fn send(&self, mail: Outgoing) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + '_>> {
        Box::pin(async move {
            let message = Message::builder()
                .from(self.from.0.clone())
                .to(mail.to)
                .subject(mail.subject)
                .body(mail.body)
                .map_err(|e| MailError(Box::new(e)))?;
            self.transport.send(message).await.map_err(|e| MailError(Box::new(e)))?;
            Ok(())
        })
    }
}

fn build(options: &MailOptions) -> Result<Smtp, BoxError> {
    let builder = if options.plaintext {
        Smtp::builder_dangerous(options.host.as_str())
    } else {
        Smtp::starttls_relay(&options.host)?
    };
    let builder = builder.port(options.port).timeout(Some(Duration::from_secs(10)));
    let builder = match &options.login {
        Some((user, password)) => builder.credentials(Credentials::new(user.clone(), password.expose().clone())),
        None => builder,
    };
    Ok(builder.build())
}

pub struct MailModule(pub MailOptions);

impl Module for MailModule {
    fn identity(&self) -> ModuleIdentity {
        ModuleIdentity::of_type::<Self>()
    }

    fn register(&self, m: &mut ModuleDef<'_>) {
        if let Some((_, password)) = &self.0.login {
            m.secret(password);
        }
        let options = self.0.clone();
        m.try_singleton(move || {
            let built = build(&options);
            async move { built }
        })
        .ready(|transport: Dep<Smtp>| async move {
            match transport.test_connection().await {
                Ok(true) => Ok(()),
                Ok(false) => Err("the server did not accept the connection test".into()),
                Err(e) => Err(BoxError::from(e)),
            }
        })
        .retries(3)
        .backoff(Duration::from_secs(2));

        m.try_value(self.0.from.parse::<Mailbox>().map(MailFrom));
        m.provide::<SmtpMailer>().also_as::<dyn Mailer>(|a| a);
        m.export::<dyn Mailer>();
    }
}

#[derive(Deserialize)]
pub struct Signup {
    pub email: String,
}

#[derive(Serialize)]
pub struct Accepted {
    pub mailed: String,
}

#[controller]
pub struct SignupController {
    mailer: Dep<dyn Mailer>,
}

#[handlers]
impl SignupController {
    #[ulo_http::post("/signup")]
    async fn signup(&self, Json(body): Json<Signup>) -> Result<Json<Accepted>, CallError> {
        let to: Mailbox = body.email.parse().map_err(|_| CallError::new(ErrorKind::BadRequest, "not an email address"))?;
        self.mailer
            .send(Outgoing { to, subject: "Welcome".into(), body: "Your account is ready.".into() })
            .await
            .map_err(|e| CallError::new(ErrorKind::Unavailable, e.to_string()))?;
        Ok(Json(Accepted { mailed: body.email }))
    }
}

pub struct AppModule(pub MailOptions);

impl Module for AppModule {
    fn identity(&self) -> ModuleIdentity {
        ModuleIdentity::of_type::<Self>()
    }

    fn register(&self, m: &mut ModuleDef<'_>) {
        m.import(MailModule(self.0.clone()));
        m.controller::<SignupController>();
    }
}

pub fn builder(options: MailOptions) -> AppBuilder {
    App::builder(AppModule(options))
}

What each seam does

m.try_singleton(..) builds the transport during connect. The factory returns a Result, so a bad host name or option fails the start. Construction succeeded against a closed port in the run below, so the connection test is where a wrong host or port shows.

.ready(..) runs test_connection() after construction and before anything that depends on the transport. .retries(3).backoff(Duration::from_secs(2)) allows four attempts two seconds apart. Ok(false) from test_connection is turned into an error. See Lifecycle hooks.

m.secret(password) registers the password with the container's redaction, which scrubs it from any hook or constructor error before the error is stored.

MailFrom is a value of its own, built with m.try_value(..) from the parsed address. A malformed from fails wire(), before connect runs.

SmtpMailer takes the transport and the sender, and .also_as::<dyn Mailer>(|a| a) binds it under the trait too. m.export::<dyn Mailer>() makes the trait the module's public surface: SignupController takes Dep<dyn Mailer> and knows nothing about SMTP.

Tokio1Executor needs a tokio runtime, and the examples start the app with Tokio::current(). The plaintext option is for a local catcher. Production takes starttls_relay. This recipe compiles the relay's TLS path and does not exercise it, because Mailpit in the test accepts plain SMTP.

What ran

RunResult
POST /signup with {"email":"ada@example.org"} against Mailpit200; Mailpit's API listed one message, from shop@example.com, to ada@example.org, subject Welcome
POST /signup with {"email":"not an address"}400, detail not an email address; nothing sent
connect with nothing listening on the portfails after 6.0 s with error A below
from of nopewire() fails with error B below, recorded by try_value
faked(..) from the test code abovePOST /signup answered 200 and the recorder held ada@example.org: Welcome

Error A:

readiness check of `AsyncSmtpTransport<Tokio1Executor>` in MailModule failed after 4 attempts: Connection error: Connection refused (os error 61)

Error B:

the value for `MailFrom` in MailModule failed to build: Invalid input

Testing

src/mail_fake.rs
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, Mutex};

use ulo::{Module, ModuleDef, ModuleIdentity, TestApp};
use ulo_runtime_tokio::Tokio;

use crate::mailer::{AppModule, MailError, MailModule, MailOptions, Mailer, Outgoing};

#[derive(Default)]
pub struct Recorder(pub Mutex<Vec<String>>);

impl Mailer for Arc<Recorder> {
    fn send(&self, mail: Outgoing) -> Pin<Box<dyn Future<Output = Result<(), MailError>> + Send + '_>> {
        self.0.lock().unwrap().push(format!("{}: {}", mail.to, mail.subject));
        Box::pin(async { Ok(()) })
    }
}

pub struct FakeMailModule(pub Arc<Recorder>);

impl Module for FakeMailModule {
    fn identity(&self) -> ModuleIdentity {
        ModuleIdentity::of_type::<Self>()
    }

    fn register(&self, m: &mut ModuleDef<'_>) {
        m.value(self.0.clone()).also_as::<dyn Mailer>(|a| a);
        m.export::<dyn Mailer>();
    }
}

pub async fn faked(options: MailOptions) -> (ulo::App<ulo::Connected>, Arc<Recorder>) {
    let recorder = Arc::new(Recorder::default());
    let app = TestApp::of(AppModule(options.clone()))
        .runtime(Tokio::current())
        .replace_module(MailModule(options), FakeMailModule(recorder.clone()))
        .connect()
        .await
        .unwrap();
    (app, recorder)
}

FakeMailModule binds a recorder as dyn Mailer and exports it. TestApp::replace_module puts it where MailModule was, so the transport and its readiness check are not in the graph. override_value::<dyn Mailer> is not the tool here. It replaces the Mailer binding and leaves the transport in the module, and in a run the transport's readiness check still tried the real host and failed the connect. See TestApp.

Failure modes

The server is down at startup. The start fails with the readiness error above after the retries. Without .ready(..) the application starts with the server down, and the first send fails instead.

A caller's bad address is not a server error. The handler parses the address into a Mailbox before the mailer runs, so the answer is 400. An address handed to the transport unparsed answered 503 with the detail mail was not sent: Invalid input.

No pooling feature. The lettre feature list above has no pool, so each send opens its own connection. lettre has a pool feature for connection reuse, which this recipe does not compile.

Reference

  • Lifecycle hooks: .ready(..), retries and backoff.
  • Providers: #[injectable], Dep<T> and failing constructors.
  • TestApp: replace_module and override_value.
  • Traits and qualifiers: binding a type under a trait.
  • Health checks: a check that reports without blocking the start.

Explicit transactions with SQLx

A unit of work that begins a transaction, passes it as &mut Transaction to repositories, and commits once or rolls back on drop.

Object storage over the AWS SDK

An S3 client built from options, checked against its bucket at startup, and served through upload and download routes.

On this page

The codeWhat each seam doesWhat ranTestingFailure modesReference