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 CLI command with clap

Run a one-shot command with the application's providers and no server: clap parses, App::execute runs.

A migration, a report or an admin task needs the application's providers and none of its sockets. clap parses the command line. App::execute opens one execution per command, and the command is resolved from the container in that execution like any other provider.

This recipe builds on examples/12-standalone and compiled against clap 4.6.8 with ulo 0.1.0-alpha.3. The binary and the tests were run.

[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-runtime-tokio = "=0.1.0-alpha.3"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
clap = { version = "4.6", features = ["derive"] }

The code

use clap::{Parser, Subcommand};
use ulo::{App, AppBuilder, Closed, Connected, Dep, ExecOptions, Ext, LookupError, injectable, module};

#[derive(Parser)]
#[command(name = "ledger")]
pub struct Cli {
    #[command(subcommand)]
    pub command: Command,
}

#[derive(Subcommand)]
pub enum Command {
    /// Prints the row count for a tenant.
    Report { tenant: String },
}

pub struct Tenant(pub String);

#[injectable]
pub struct Ledger;

impl Ledger {
    fn rows(&self, tenant: &str) -> usize {
        tenant.len()
    }
}

#[injectable(execution)]
pub struct ReportCommand {
    tenant: Ext<Tenant>,
    ledger: Dep<Ledger>,
}

impl ReportCommand {
    pub fn run(&self) -> String {
        format!("{}: {} rows", self.tenant.0, self.ledger.rows(&self.tenant.0))
    }
}

#[module(providers = [Ledger, ReportCommand])]
pub struct AppModule;

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

/// Runs one parsed command in its own execution and returns what it prints.
pub async fn dispatch(app: &App<Connected>, cli: Cli) -> Result<Result<String, LookupError>, Closed> {
    match cli.command {
        Command::Report { tenant } => {
            app.execute(ExecOptions::new(), async |exec| {
                exec.extensions().insert(Tenant(tenant));
                Ok(exec.get::<ReportCommand>().await?.run())
            })
            .await
        }
    }
}

The binary parses first, builds the application second:

use clap::Parser;
use r3::cli::{Cli, builder, dispatch};
use ulo::Signal;
use ulo_runtime_tokio::Tokio;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let cli = Cli::parse();
    let app = builder().runtime(Tokio::current()).wire()?.connect().await?;
    println!("{}", dispatch(&app, cli).await??);
    app.close(Signal::new("done")).await?;
    Ok(())
}

Running it:

$ ledger report acme
acme: 4 rows
$ ledger report
error: the following required arguments were not provided:
  <TENANT>

Usage: ledger report <TENANT>

For more information, try '--help'.
$ echo $?
2

What each seam does

  • Cli::parse() runs before builder(). A malformed command line prints clap's message and exits with status 2 without wiring the application, so a typo never starts a database connection.
  • connect() performs the startup a server performs: provider construction and init hooks. The commands run after it.
  • dispatch matches the subcommand and opens one execution for it with ExecOptions::new(). Each command is its own execution, so an #[injectable(execution)] provider such as ReportCommand is built fresh for it.
  • The parsed arguments reach the command through the execution's extensions: exec.extensions().insert(Tenant(..)) before exec.get::<ReportCommand>(). ReportCommand declares Ext<Tenant> and reads it like a handler reads a value a guard wrote.
  • execute returns Result<R, Closed> and the closure returns its own Result, so dispatch returns a nested one and main writes ??.
  • app.close(..) runs the shutdown sequence, with no sockets to close. Destroy and shutdown hooks run here.

A test

Cli::try_parse_from takes the argument list a shell would have produced, so the whole path runs in a test without a process:

use clap::Parser;
use r3::cli::{Cli, builder, dispatch};
use ulo::Signal;
use ulo_runtime_tokio::Tokio;

#[tokio::test]
async fn report_prints_the_row_count() {
    let app = builder().runtime(Tokio::current()).wire().unwrap().connect().await.unwrap();
    let cli = Cli::try_parse_from(["ledger", "report", "acme"]).unwrap();
    assert_eq!(dispatch(&app, cli).await.unwrap().unwrap(), "acme: 4 rows");
    app.close(Signal::new("done")).await.unwrap();
}

#[test]
fn a_missing_argument_is_refused_before_any_app_exists() {
    let refused = Cli::try_parse_from(["ledger", "report"]).err().unwrap();
    assert_eq!(refused.exit_code(), 2);
}

Failure modes

  • A command that exec.get::<T>() cannot resolve returns a LookupError in the inner Result. Observed messages: "no binding for Unbound is visible from this module" for a type nothing binds, and "the extension Tenant was not written in this execution" for a command whose Ext<Tenant> the caller did not insert. main above returns the error, and the process exits with status 1. Map it to a message and a code of your own when a script reads the result.
  • Wiring errors and a failing init hook come out of wire() and connect(), before any command runs.

Reference

  • Standalone executions: execute, per-execution data, deadlines and close.
  • Scopes: what #[injectable(execution)] builds and when.
  • Application phases: wire, connect and close.
  • Testing: TestApp, for a command whose dependencies are replaced.

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.

Mocks with mockall

Register a mockall mock in place of a trait binding with TestApp::override_value and have its expectations checked when the app closes.

On this page

The codeWhat each seam doesA testFailure modesReference