dust

Media library

Introduction

The media library stores files for your models: images, documents, or anything else. It copies a file to one of your disks, records it in the media table, and can generate resized or cropped versions. A model takes part by implementing HasMedia, which is also where it declares the collections the file may join.

The library is an optional feature. A new application enables it and ships the media table migration.

Enabling the library

The dust new skeleton enables the feature:

toml
[dependencies]dust-framework = { path = ".", features = ["database-sqlite", "medialib"] }

On an existing application, add medialib to the feature list and run dust migrate. The migration creates the media table.

Attaching media

Implement HasMedia on a model and declare its collections:

rust
use dust::medialib::{HasMedia, MediaCollections};impl HasMedia for Post {    fn register_media_collections(collections: &mut MediaCollections) {        collections.add("images").single_file().accepts(["image/*"]);        collections.add("documents");    }}

Then attach a file from a path, from bytes, or from a URL:

rust
let media = post.add_media("storage/app/photo.jpg").to_media_collection("images").await?;let media = post.add_media_bytes(bytes, "photo.jpg").to_media_collection("images").await?;let media = post.add_media_url("https://example.com/photo.jpg").to_media_collection("images").await?;

A path or bytes attachment reads the MIME type from the extension. A URL attachment reads it from Content-Type, takes the file name from Content-Disposition or the URL's last segment, and rejects anything but http and https. A URL may download at most 10 MB unless you raise the limit:

rust
let media = post.add_media_url(url)    .max_bytes(50 * 1024 * 1024)    .to_media_collection("documents")    .await?;

Set a display name that differs from the file's name with named:

rust
let media = post.add_media(path).named("Cover photo").to_media_collection("images").await?;

Collections

A collection groups files and carries their rules:

  • disk("s3") stores the collection on another disk.
  • single_file() keeps one file; attaching another deletes the previous one after the new one is stored.
  • accepts(["image/*", "application/pdf"]) rejects other MIME types; with no list, the collection accepts every type.
  • conversions(...) declares the sizes to generate.

Conversions

A conversion applies manipulations to the original image and stores the result beside it, under conversions/<name>/. The original is never changed.

rust
collections.add("images").conversions(|conversions| {    conversions.add("thumb").crop(200, 200);    conversions.add("preview").fit(800, 600);    conversions.add("large").width(1600).quality(90);});

The built-in manipulations are crop, fit, width, height, and rotate. crop fills the box and scales as needed; fit keeps the whole image inside the box. A conversion keeps the original format by default: PNG stays PNG, WebP stays WebP, everything else becomes JPEG. Choose another format with .format(Format::Webp).

Method Effect
crop(width, height) Scales to fill the box, then crops the overflow
fit(width, height) Scales the whole image to sit inside the box
width(pixels), height(pixels) Resizes one side and keeps the aspect ratio
rotate(degrees) Rotates the image
quality(0..=100) Sets the encoder quality for lossy formats
format(Format) Chooses the output format
manipulate(plugin) Applies a custom Manipulation

Add a plugin by implementing Manipulation. The image crate is available at dust::medialib::image:

rust
use dust::medialib::image::DynamicImage;use dust::medialib::{Manipulation, Result};#[derive(Debug)]struct Flip;impl Manipulation for Flip {    fn apply(&self, image: &mut DynamicImage) -> Result<()> {        let flipped = image.fliph();        *image = flipped;        Ok(())    }}conversions.add("mirror").manipulate(Flip);

Conversions are generated when the file is attached. Only image MIME types are converted; SVG files keep the original only.

Read a conversion's URL with url_with_conversion; when the conversion wasn't generated, it returns the original's URL:

rust
let thumb = media.url_with_conversion("thumb").await?;

Configuration

The media library reads config/medialib.toml, which a new application creates:

toml
# The disk new media is stored on when neither the collection nor the attachment names one.# Leave it commented to use `public`, then the application's default disk.disk = "public"# The largest file a URL may download, in bytes. The default is 10 MiB.max_download_size = 10485760

A missing file, or a key the file leaves out, keeps the default. The disk is chosen in this order:

  1. .on_disk(...) on the attachment;
  2. disk(...) on the collection;
  3. disk in config/medialib.toml;
  4. the public disk, or the application's default disk when public isn't configured.

max_download_size applies to URLs; .max_bytes(...) on one attachment overrides it. The values are available in code through dust::medialib::Settings::load(), which returns the same defaults when the file is missing.

Disks

Every file lives on one disk. A collection picks one with disk("s3"), an attachment may override it with .on_disk("s3"), and the default is the public disk, or the application's default disk when public isn't configured.

The disk's name is stored with the row, so url, path, and full_path always resolve the disk that holds the file:

rust
media.url().await?;                  // the disk's URLmedia.full_url().await?;             // absolute, using APP_URL when the disk returns a relative URLmedia.path();                        // media/post/42/<uuid>/photo.jpgmedia.full_path().await?;            // the local path, or an error on S3

Reading media

On a model:

rust
let images = post.get_media("images").await?;let first = post.get_first_media("images").await?;let url = post.get_first_media_url("images").await?;

Across models, use MediaQuery. It offers the same filters as the console command:

rust
use dust::medialib::MediaQuery;let images = MediaQuery::new()    .model("post")    .collection("images")    .disk("public")    .mime("image/*")    .name("cover")    .limit(20)    .get()    .await?;

Media exposes uuid, name, file_name, mime_type, size, disk_name, model_type, model_id, collection_name, and the URL and path methods above.

Moving and deleting

rust
media.move_to_disk("s3").await?;media.delete().await?;post.clear_media_collection("images").await?;

move_to_disk copies the original and its conversions, updates the row, and deletes the copies on the old disk only after the update succeeds. delete removes the files on the row's disk and then the row; a file that is already missing is skipped.

Failure modes

Symptom Cause What to do
add_media rejects the MIME type The collection lists accepts(..) and the file does not match Check the file's real type; the extension alone is not enough
A URL attachment fails The URL is not http/https, the download exceeds the limit, or the server returns an error Raise .max_bytes(..) or store the file on a disk yourself
A conversion is missing The file is not an image, or it is an SVG Only raster images are converted; SVG keeps the original
Attaching a second file to a single_file collection deletes the first That is the collection's rule Remove single_file() when a collection should hold many files
full_path fails on S3 Object stores have no local path Use url() or read the file through storage
A move fails halfway The copy or the row update failed The old copy is left in place; retry the move

Conversions are generated before to_media_collection returns, so attaching a large original inside a request adds its processing time to that request. For big uploads, attach the file from a queued job so the HTTP response is not tied to the image work.

Console commands

The feature registers four commands. A command that needs a model's collections reaches them through the registry, so register each model once when the application starts:

rust
dust::medialib::register::<Post>();

Attach a file:

shell
dust media:add storage/app/photo.jpg --model=post --id=42 --collection=imagesdust media:add https://example.com/photo.jpg --model=post --id=42 --collection=images --disk=s3

--name sets the display name and --max-bytes limits a download.

List media with filters:

shell
dust media:list --model=post --collection=images --mime='image/*' --limit=20dust media:list --disk=public --oldest --json

Delete or move one file:

shell
dust media:delete <uuid>dust media:move <uuid> --disk=s3

The media table

The migration creates media with these columns:

Column Holds
id the row's key
model_type, model_id the owning model's morph name and key
uuid the folder name on the disk
collection_name the collection
name the display name
file_name the name on the disk
mime_type the file's MIME type
disk the disk that holds the file
size the size in bytes
order_column the position in the collection
conversions JSON: each generated conversion's path
custom_properties JSON for application data
generated_conversions JSON: which conversions were generated
created_at, updated_at timestamps

The table has an index on model_type and model_id, so a model's files are cheap to read.