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 client as a provider

The lifecycle a module writes for a client no store module covers, what the store modules add on top, and a hand-built SOAP client as the worked example.

The store modules cover five databases. Everything else a service talks to (Stripe, an AWS service, a legacy SOAP endpoint) is a client the application builds. It still needs the same four things: construction that can fail the start, a bounded wait for the peer, a place to close, and no secret in an error. A plain module writes these on the binding it contributes. For an SDK client with the same shape, see Object storage.

Versions compiled with: reqwest 0.13.5, quick-xml 0.42.0, ulo 0.1.0-alpha.3.

The lifecycle you write

A module that needs hooks implements Module and calls them on the ModuleDef, since #[module] has no spelling for them. See Lifecycle hooks.

CallWhat it does
m.try_singleton(f)Builds the client once during connect. A factory returning Err fails the start.
.ready(check)Runs after construction and before anything that depends on the client. Takes injected parameters like the factory does.
.retries(n)Attempts after the first. Zero unless written.
.backoff(d)The wait between attempts. Zero unless written, and a nonzero wait needs a Timer.
.attempt_timeout(d)Bounds one attempt. A timed-out attempt is retried like one that returned Err.
.timeout(d)Bounds the whole check.
.on_destroy(hook)Runs after the drain, in reverse connect order.
.on_init, .before_shutdown, .on_shutdownThe other hooks on the same handle.

A check that writes no bound takes the app's construct_timeout as its attempt bound when a Timer exists, so a ping to a host that drops packets reaches its retries.

What a store module adds

A store module doesA hand-built client writes
Marks failures retrying cannot mend (bad credentials, a refused certificate) as ulo::Permanent, and the retry loop stops at the first attempt.The same wrapper, Permanent::new(e), on the errors of its check that are final.
Wraps the connect in one bound, connect_within, with a constant retries and backoff..retries(..), .backoff(..) and .timeout(..) on the binding.
Contributes a health check named after the store, so readiness reflects the database after the start. See Health checks.A Check of its own. A .ready(..) runs once, at start.
Takes a lock around migrations so replicas do not run them twice. See Migrations.Nothing: the lock is specific to a database schema.
Registers the URL and its password as secrets, so no error or report prints them.m.secret(&secret) for each Secret the module holds.
Fails connect when the runtime is not tokio.Nothing. The client's own runtime requirement is the client's to state.

The code

A SOAP service is a POST of an XML envelope. The client below builds the envelope with quick-xml's Writer and parses the reply with its Reader. It takes a session at start with a Login call and ends it with Logout. No WSDL is read: each operation is written by hand.

src/soap.rs
use std::sync::Mutex;
use std::time::Duration;

use quick_xml::Reader;
use quick_xml::Writer;
use quick_xml::escape::resolve_predefined_entity;
use quick_xml::events::{BytesText, Event};
use ulo::{App, AppBuilder, BoxError, Dep, Module, ModuleDef, ModuleIdentity, Permanent, Secret, controller, handlers};
use ulo_http::{CallError, ErrorKind, Path};

const ENVELOPE: &str = "http://schemas.xmlsoap.org/soap/envelope/";

#[derive(Clone, PartialEq, Eq, Hash)]
pub struct SoapOptions {
    pub endpoint: String,
    pub namespace: String,
    pub user: String,
    pub password: Secret<String>,
}

#[derive(Debug)]
pub enum SoapError {
    Transport(reqwest::Error),
    Xml(String),
    /// The service answered with a `soap:Fault`.
    Fault(String),
}

impl std::fmt::Display for SoapError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SoapError::Transport(e) => write!(f, "the SOAP call did not complete: {e}"),
            SoapError::Xml(e) => write!(f, "the SOAP reply is not what was expected: {e}"),
            SoapError::Fault(e) => write!(f, "the service refused the call: {e}"),
        }
    }
}

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

pub struct SoapClient {
    http: reqwest::Client,
    options: SoapOptions,
    session: Mutex<Option<String>>,
}

/// One operation as an XML envelope. `quick-xml` escapes the text of every argument.
fn envelope(namespace: &str, session: Option<&str>, operation: &str, args: &[(&str, &str)]) -> Result<String, SoapError> {
    let xml = |e: std::io::Error| SoapError::Xml(e.to_string());
    let mut w = Writer::new(Vec::new());
    w.create_element("soap:Envelope")
        .with_attribute(("xmlns:soap", ENVELOPE))
        .write_inner_content(|w| {
            if let Some(token) = session {
                w.create_element("soap:Header").write_inner_content(|w| {
                    w.create_element("Session").write_text_content(BytesText::new(token))?;
                    Ok(())
                })?;
            }
            w.create_element("soap:Body").write_inner_content(|w| {
                w.create_element(operation).with_attribute(("xmlns", namespace)).write_inner_content(|w| {
                    for (name, value) in args {
                        w.create_element(*name).write_text_content(BytesText::new(value))?;
                    }
                    Ok(())
                })?;
                Ok(())
            })?;
            Ok(())
        })
        .map_err(xml)?;
    String::from_utf8(w.into_inner()).map_err(|e| SoapError::Xml(e.to_string()))
}

/// The text of the first element named `wanted`, or the `faultstring` of a fault. Names are
/// compared without their prefix, so the service's choice of prefix does not matter.
fn text_of(reply: &str, wanted: &str) -> Result<String, SoapError> {
    let xml = |e: &dyn std::fmt::Display| SoapError::Xml(e.to_string());
    let mut reader = Reader::from_str(reply);
    let (mut capture, mut fault, mut out) = (None::<bool>, None::<String>, String::new());
    loop {
        match reader.read_event().map_err(|e| xml(&e))? {
            Event::Start(e) if e.local_name().as_ref() == wanted => capture = Some(false),
            Event::Start(e) if e.local_name().as_ref() == "faultstring" => capture = Some(true),
            Event::Text(t) if capture.is_some() => out.push_str(&t.xml10_content()),
            Event::CData(t) if capture.is_some() => out.push_str(&t.xml10_content()),
            Event::GeneralRef(r) if capture.is_some() => {
                let name: &str = &r;
                match (r.resolve_char_ref().map_err(|e| xml(&e))?, resolve_predefined_entity(name)) {
                    (Some(c), _) => out.push(c),
                    (None, Some(s)) => out.push_str(s),
                    (None, None) => return Err(SoapError::Xml(format!("unknown entity &{name};"))),
                }
            }
            Event::End(_) => match capture.take() {
                Some(true) => fault = Some(std::mem::take(&mut out)),
                Some(false) => return Ok(out),
                None => {}
            },
            Event::Eof => break,
            _ => {}
        }
    }
    Err(fault.map_or_else(|| SoapError::Xml(format!("no <{wanted}> in the reply")), SoapError::Fault))
}

impl SoapClient {
    fn new(options: SoapOptions) -> Result<Self, BoxError> {
        let http = reqwest::Client::builder().timeout(Duration::from_secs(10)).build()?;
        Ok(SoapClient { http, options, session: Mutex::new(None) })
    }

    async fn call(&self, operation: &str, args: &[(&str, &str)], result: &str) -> Result<String, SoapError> {
        let session = self.session.lock().unwrap().clone();
        let body = envelope(&self.options.namespace, session.as_deref(), operation, args)?;
        let reply = self
            .http
            .post(&self.options.endpoint)
            .header("content-type", "text/xml; charset=utf-8")
            .header("soapaction", format!("\"{}/{operation}\"", self.options.namespace))
            .body(body)
            .send()
            .await
            .map_err(SoapError::Transport)?
            .text()
            .await
            .map_err(SoapError::Transport)?;
        text_of(&reply, result)
    }

    async fn login(&self) -> Result<(), SoapError> {
        let token = self.call("Login", &[("user", &self.options.user), ("password", self.options.password.expose())], "Token").await?;
        *self.session.lock().unwrap() = Some(token);
        Ok(())
    }

    async fn logout(&self) {
        // A failed logout leaves the session to expire on the service's side.
        let _ = self.call("Logout", &[], "Done").await;
        *self.session.lock().unwrap() = None;
    }

    pub async fn number_to_words(&self, n: u64) -> Result<String, SoapError> {
        self.call("NumberToWords", &[("ubiNum", &n.to_string())], "NumberToWordsResult").await
    }
}

pub struct SoapModule(pub SoapOptions);

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

    fn register(&self, m: &mut ModuleDef<'_>) {
        m.secret(&self.0.password);
        let options = self.0.clone();
        m.try_singleton(move || {
            let built = SoapClient::new(options.clone());
            async move { built }
        })
        .ready(|client: Dep<SoapClient>| async move {
            client.login().await.map_err(|e| match e {
                // Refused credentials: another attempt gets the same answer.
                SoapError::Fault(_) => BoxError::from(Permanent::new(e)),
                other => BoxError::from(other),
            })
        })
        .retries(2)
        .backoff(Duration::from_secs(1))
        .on_destroy(|client: Dep<SoapClient>| async move { client.logout().await });
        m.export::<SoapClient>();
    }
}

#[controller]
pub struct WordsController {
    soap: Dep<SoapClient>,
}

#[handlers]
impl WordsController {
    #[ulo_http::get("/words/{n}")]
    async fn words(&self, Path(n): Path<u64>) -> Result<String, CallError> {
        self.soap.number_to_words(n).await.map_err(|e| match e {
            SoapError::Fault(_) => CallError::new(ErrorKind::BadRequest, e.to_string()),
            other => CallError::new(ErrorKind::Unavailable, other.to_string()),
        })
    }
}

pub struct AppModule(pub SoapOptions);

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

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

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

What each seam does

SoapClient::new builds the reqwest::Client and returns a Result, so a bad client configuration fails the start. The password is a Secret, and m.secret(..) registers it for scrubbing.

.ready(..) is login. The session token goes into the client behind a Mutex, because the check receives a shared Dep<SoapClient>. Every later call reads the token and sends it in a SOAP header. A soap:Fault on login means the credentials were refused, and Permanent::new(e) marks it so the check stops at the first attempt. A transport error is not marked and is retried.

.on_destroy(..) is logout. It runs after the drain, so a call in flight when shutdown began has finished. A failed logout is ignored, and the service expires the session.

envelope writes each argument through BytesText::new, which escapes it. The password p&ss<w went out as p&amp;ss&lt;w.

text_of compares element names without their prefix, and returns the faultstring of a fault when the wanted element is absent. In quick-xml 0.42 an entity reference arrives as its own Event::GeneralRef, and the parser resolves it; a parser that read only Event::Text would drop the &amp;.

What ran

Against a mock SOAP server written for the test, a TCP listener that answers by the soapaction header. No real SOAP service was called.

RunResult
connectOne Login request, <user>ann</user><password>p&amp;ss&lt;w</password> in the body
GET /words/13200, thirteen & <more> A, parsed from thirteen &amp; <![CDATA[<more>]]> &#65; in NumberToWordsResult; the request carried <Session>tok-1</Session> in the header
GET /words/99, answered with a soap:Fault400, detail the service refused the call: number too large
ShutdownOne Logout request, with the session header
connect with a login the service refusesFails after 1 attempt, message A below; ulo::is_permanent answered true
connect with nothing listening, .retries(2).backoff(1s)Fails after 2.0 s and 3 attempts, message B below; the endpoint had been given as http://ann:hunter22@127.0.0.1:1/ and the message shows it without the userinfo

Message A:

readiness check of `SoapClient` in SoapModule failed after 1 attempt: the service refused the call: bad credentials

Message B:

readiness check of `SoapClient` in SoapModule failed after 3 attempts: the SOAP call did not complete: error sending request for url (http://127.0.0.1:1/)

Failure modes

Hooks need a singleton. .ready(..) and the hook methods exist on singleton handles only. On an execution-scoped or transient handle they do not compile.

A check that reads the network blocks the start. Three attempts a second apart against a dead host cost two seconds here. A client whose peer may be down at start drops .ready(..), and its first call reports the failure.

One check per binding. A second .ready(..) on one binding is a wiring error naming both calls.

Stripe and similar SDKs. A client such as async-stripe's takes the same shape: a constructor in try_singleton, a cheap authenticated call in .ready(..), and Permanent around a rejected key. This site has no compiled Stripe example, and the SDK's calls are not shown here.

Reference

  • Lifecycle hooks: hooks, readiness checks and the secrets rule.
  • Providers: how a failing constructor reports.
  • Connecting: the store modules' retry policy and permanent failures.
  • Health checks: a Check that reports after the start.
  • Shutdown: where .on_destroy(..) runs.
  • Object storage: the same lifecycle on an AWS SDK client.

Localised responses with Fluent

Negotiate Accept-Language in an extractor, translate with fluent, and localise the problem document in a global ErrorHandler.

A MongoDB ODM over the injected client

Models with oximod that read and write through the mongodb::Client the MongoDB module already built, with no second connection.

On this page

The lifecycle you writeWhat a store module addsThe codeWhat each seam doesWhat ranFailure modesReference