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

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.

An application that keeps files in S3, or in an S3-compatible server, needs one SDK client for the process and a bucket it can reach. This recipe builds aws-sdk-s3's Client as a singleton, checks the bucket with HeadBucket before the application serves, and wraps the calls in an Objects provider. It was compiled and run against MinIO in a container. It was not run against AWS.

Versions compiled with: aws-sdk-s3 1.159.0, aws-config 1.13.2, ulo 0.1.0-alpha.3.

Cargo.toml
[dependencies]
ulo = "=0.1.0-alpha.3"
ulo-http = "=0.1.0-alpha.3"
aws-config = { version = "1", features = ["behavior-version-latest"] }
aws-sdk-s3 = "1"

The code

src/storage.rs
use std::time::Duration;

use aws_config::BehaviorVersion;
use aws_sdk_s3::Client;
use aws_sdk_s3::config::{Credentials, Region};
use aws_sdk_s3::primitives::ByteStream;
use ulo::{App, AppBuilder, BoxError, Dep, Module, ModuleDef, ModuleIdentity, Secret, controller, handlers, injectable};
use ulo_http::{Bytes, CallError, ErrorKind, Path};

#[derive(Clone, PartialEq, Eq, Hash)]
pub struct StorageOptions {
    pub bucket: String,
    pub region: String,
    /// An S3-compatible server's URL; `None` means AWS.
    pub endpoint: Option<String>,
    /// `None` leaves credentials to the SDK's default provider chain.
    pub keys: Option<(String, Secret<String>)>,
}

/// The bucket's name, a value of its own so a provider can take it as a dependency.
pub struct BucketName(pub String);

async fn connect(options: StorageOptions) -> Result<Client, BoxError> {
    let mut loader = aws_config::defaults(BehaviorVersion::latest()).region(Region::new(options.region));
    if let Some(endpoint) = options.endpoint.as_deref() {
        loader = loader.endpoint_url(endpoint);
    }
    if let Some((id, secret)) = options.keys {
        loader = loader.credentials_provider(Credentials::new(id, secret.expose().clone(), None, None, "static"));
    }
    let shared = loader.load().await;
    let config = aws_sdk_s3::config::Builder::from(&shared).force_path_style(options.endpoint.is_some()).build();
    Ok(Client::from_conf(config))
}

pub struct StorageModule(pub StorageOptions);

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

    fn register(&self, m: &mut ModuleDef<'_>) {
        if let Some((_, secret)) = &self.0.keys {
            m.secret(secret);
        }
        m.value(BucketName(self.0.bucket.clone()));
        let options = self.0.clone();
        m.try_singleton(move || connect(options.clone()))
            .ready(|client: Dep<Client>, bucket: Dep<BucketName>| async move {
                client.head_bucket().bucket(&bucket.0).send().await.map(drop)
            })
            .retries(2)
            .backoff(Duration::from_secs(1));
        m.provide::<Objects>();
        m.export::<Objects>();
    }
}

#[injectable]
pub struct Objects {
    client: Dep<Client>,
    bucket: Dep<BucketName>,
}

impl Objects {
    pub async fn put(&self, key: &str, body: Bytes) -> Result<(), CallError> {
        self.client
            .put_object()
            .bucket(&self.bucket.0)
            .key(key)
            .body(ByteStream::from(body))
            .send()
            .await
            .map_err(|e| CallError::new(ErrorKind::Unavailable, format!("the object store refused the write: {}", e.into_service_error())))?;
        Ok(())
    }

    pub async fn get(&self, key: &str) -> Result<Bytes, CallError> {
        let answer = self.client.get_object().bucket(&self.bucket.0).key(key).send().await.map_err(|e| {
            if e.as_service_error().is_some_and(|s| s.is_no_such_key()) {
                CallError::new(ErrorKind::NotFound, "no such object")
            } else {
                CallError::new(ErrorKind::Unavailable, "the object store did not answer")
            }
        })?;
        let body = answer.body.collect().await.map_err(|_| CallError::new(ErrorKind::Unavailable, "the object body broke off"))?;
        Ok(body.into_bytes())
    }
}

#[controller]
pub struct FilesController {
    objects: Dep<Objects>,
}

#[handlers]
impl FilesController {
    #[ulo_http::put("/files/{key}")]
    async fn upload(&self, Path(key): Path<String>, body: Bytes) -> Result<(), CallError> {
        self.objects.put(&key, body).await
    }

    #[ulo_http::get("/files/{key}")]
    async fn download(&self, Path(key): Path<String>) -> Result<Bytes, CallError> {
        self.objects.get(&key).await
    }
}

pub struct AppModule(pub StorageOptions);

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

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

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

What each seam does

connect loads the SDK's shared configuration with aws_config::defaults(..). With keys: None the credentials come from the SDK's default provider chain, which is what a deployment on AWS wants. With keys set, a static credentials provider is used. endpoint points the SDK at an S3-compatible server and turns on path-style addressing, which the run against MinIO used.

m.try_singleton(..) takes the factory that calls connect. Loading the configuration is async, and an Err fails the start. The Client is bound as it is, and no .on_destroy(..) is written.

.ready(..) calls HeadBucket. A wrong bucket name, a wrong region or refused credentials fail the start with the check's error instead of failing the first upload. .retries(2).backoff(Duration::from_secs(1)) allows three attempts.

Objects maps the SDK's errors to the error model of Error handling: a missing key is a NotFound, which renders as a 404, and any other failure is Unavailable. The service error is checked with is_no_such_key() on the typed error, not by matching text.

What ran

Against MinIO with a bucket created beforehand:

CallAnswer
PUT /files/hello.txt with body hello s3204
GET /files/hello.txt200, body hello s3
GET /files/missing404, detail no such object
PUT /files/big with a 3 MiB body413
connect with a bucket that does not existfails after 3 attempts with the error below
readiness check of `Client` in StorageModule failed after 3 attempts: service error: NotFound

Failure modes

The body limit applies to uploads. The Bytes extractor reads the body under the default limit of 2 MiB, and a larger upload answers 413 before the handler runs. #[meta(MaxBody(..))] raises it for one route. See Limits and Multipart.

A missing bucket is a startup failure. The check treats every HeadBucket error as not ready and retries it, a permissions error included.

Static keys are a Secret. m.secret(secret) registers the key so the container scrubs it from startup errors. StorageOptions derives Hash and Eq through Secret, so two modules with the same keys are one module.

Reference

  • Lifecycle hooks: .ready(..), retries and backoff.
  • A client as a provider: the same shape for a client no store module covers.
  • Limits: the body limit and its override.
  • Providers: #[injectable] and Dep<T>.

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.

A CLI command with clap

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

On this page

The codeWhat each seam doesWhat ranFailure modesReference