Files
Many applications store files: a station’s photo, a PDF attached to a contract, a spreadsheet an export made. In rind this is three pieces:
- a column, of type
File, which holds the file’s key (its name in the storage); - an input field, of type
Upload, which reads a file a client sends; - a storage, the
storageplugin, which says where the files are: a folder on the disk, or an S3 bucket.
Coming from Django: the column is a
FileField, the storage isDEFAULT_FILE_STORAGE(orSTORAGES["default"]) withdjango-storagesfor S3, andRIND_MEDIA_URLisMEDIA_URL. rind stores the key as Django does, so a database Django wrote is read as it is.
Setting it up
Turn on the Cargo feature storage, or storage-s3 for S3:
# Cargo.toml of the application
rind = { version = "…", features = ["storage-s3"] }
Give the plugin to the application, in app():
#![allow(unused)]
fn main() {
// sample/src/lib.rs
.with(
rind::storage::Storage::from_env()
.expect("RIND_STORAGE")
// (the railway also makes resized copies of its images: see Images)
.sizes(rind::images::Sizes::new()),
)
}
Storage::from_env() reads these environment variables:
| Variable | What it says |
|---|---|
RIND_STORAGE | where the files are: file:///srv/media (a folder), or s3://bucket/prefix. ./media when unset |
RIND_MEDIA_URL | the public address the files are served at, such as https://files.example.org/media/ |
RIND_STORAGE_ACCEL | an nginx internal location for downloads: see Letting nginx send the file |
AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION | the S3 credentials, for an s3:// storage |
AWS_ENDPOINT, AWS_ALLOW_HTTP | for a server that speaks S3 but is not Amazon’s (MinIO, RustFS…) |
With nothing set, the files go to ./media and the application serves
them at /media/<key>, which is what you want in development.
A file column
A model’s file is a column of type rind::db::types::File:
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
pub struct Station {
// …
/// A photo of the station: its key in the storage.
#[column(max_length = 500)]
pub photo: Option<rind::db::types::File>,
}
}
In the database it is a varchar that holds the file’s key, such as
2c/03a1…/Gare_de_Lyon.png: this is what Django’s FileField holds. An
empty key means “no file”, as Django writes it.
In an answer, the serializer sends a file as an object, or null when
there is none:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/serializers.rs
/// `{url, name, size}`, or null.
pub photo: Option<Option<rind::db::types::File>>,
}
GET /stations/1?fields=id,photo
{"id": 1, "photo": {"url": "/media/2c/03a1…/Gare_de_Lyon.png", "name": "Gare_de_Lyon.png", "size": 1024}}
The URL and the size come from the storage. The size is asked of the
storage once, then remembered, since a key’s content never changes. In
a list, the sizes the storage does not know yet are asked for together,
then the page is written. Without a storage plugin, url and size are
null.
Receiving a file
An input field of type Upload reads a file sent by a client:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/serializers.rs
pub struct StationIn {
// …
/// Sent in a form, or in JSON as `{name, type, content}` (base64);
/// null removes it.
pub photo: Option<Option<rind::api::files::Upload>>,
}
}
The double Option follows the usual rule of inputs: the outer one is
“was the field sent?”, the inner one is “is it null?”. Sending null
removes the file from the row.
A client can send the file in two ways.
As a form (multipart/form-data), as a browser does. The file is a
part, and the other fields are text parts:
PATCH /stations/2
Content-Type: multipart/form-data; boundary=…
platforms=7, opened=(empty), photo=plan.pdf (application/pdf)
{"id": 2, "platforms": 7, "opened": null, "photo": {"url": "/media/…/plan.pdf", "name": "plan.pdf", "size": 8}, …}
In a form every value is text, so rind reads a text as JSON for a field
that is not a string: 7 becomes a number, true a boolean. An empty
text is null for a field that can be null. A text that is not a valid
value is an error on its field, as in JSON. Both web frameworks (actix-web
and axum) read forms with the same code.
As JSON, with the content in base64:
{"photo": {"name": "plan.pdf", "type": "application/pdf", "content": "JVBERi0xLjQ="}}
type is optional. A content that is not base64 is a 400.
Where the file is stored
The file’s key is the SHA-1 of its content, then its name:
<sha1[..2]>/<sha1[2..]>/<name>. This is Django’s layout without its
folder. The name is cleaned: its path is dropped, and characters that a
URL or a path would read wrongly become _ (../Gare de Lyon.png
becomes Gare_de_Lyon.png). The same content sent twice is stored once.
To store a field’s files in a folder, as Django’s upload_to does, give
the field a folder:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/images.rs
#[input(folder = "images")]
pub file: Option<rind::api::files::Upload>,
}
The key is then images/<sha1[..2]>/<sha1[2..]>/<name>. The folder is
applied when the input is read, before the file is stored: a hook would
come too late to change it.
When the file is stored
The pipeline stores the file once the input is valid, before the write
that names it. If that write then fails, the file stays in the storage.
It is in no one’s way (its key is unique), and storage-orphans lists
such files (see Files no row names).
A request body is read up to RIND_BODY_LIMIT bytes (32 MiB by
default), files included. A file sent to an application without a
storage plugin is a 500.
Where the files are served from
How a client gets a file depends on the storage, and on
RIND_MEDIA_URL:
- With
RIND_MEDIA_URL, a file’s URL is that address then its key. Something else serves the files: nginx, a CDN, a public bucket. - A folder, without
RIND_MEDIA_URL: the application serves the files itself at/media/<key>. Every file served there is public, as Django’sMEDIA_URLis, and is sent with a cache of a year (its key never changes content). - An S3 bucket, without
RIND_MEDIA_URL: a file’s URL is a signed address that expires after an hour (Storage::expirychanges it). A private bucket stays private.
Coming from Django: a private S3 bucket with signed URLs is
django-storages’AWS_QUERYSTRING_AUTH = True.
You can set all of this in code instead of the environment:
#![allow(unused)]
fn main() {
rind::storage::Storage::local("/srv/media")? // a folder
.base_url("https://files.example.org/media/") // the public address
// or
rind::storage::Storage::s3("bucket", "prefix")? // a bucket (feature storage-s3)
.serve("/media") // served by the application
}
The storage goes through the object_store crate: Google Cloud Storage
and Azure would be one more feature of that crate.
/ready checks that the storage answers (Health).
A file the application makes
An action can make a file (a workbook, a printable PDF) and keep it. The
plugin is also a service, which stores it under the same kind of key as
an upload, and gives back a File to keep in a row of your own:
#![allow(unused)]
fn main() {
let storage = ctx.service::<rind::storage::Storage>().unwrap();
let file = storage.store(Some("exports"), "distances.xlsx", bytes).await?;
// file.0 is "exports/<sha1[..2]>/<sha1[2..]>/distances.xlsx"
}
Later, a route that has decided the request may have the file (a link with a code, a user’s own file) answers it as a download:
#![allow(unused)]
fn main() {
storage.download(&file.0, "distances.xlsx", true).await // an Answer
}
The answer has the file’s type (from its name) and a
Content-Disposition: attachment when the last argument is true (the
browser saves the file), inline otherwise (the browser shows it). A key
that is not stored is a 404.
Letting nginx send the file
By default the bytes of the file are the answer’s body: the application
reads the file and sends it. Behind nginx, you can let nginx do it.
Call .accel_redirect("protected") on the storage (or set
RIND_STORAGE_ACCEL=protected). The answer then has no body, and a
header X-Accel-Redirect: /protected/<key>. nginx sends the file from an
internal location:
location /protected/ { internal; alias /srv/media/; }
The application checks who may have the file, and nginx sends it.
Using the storage from code
The Storage service also has put(key, bytes), get(key) (None
when there is no such file), delete(key) and keys(prefix).
Files no row names
cargo run -p sample -- storage-orphans --column network_station.photo --column network_image.file
storage-orphans lists the stored files that no row of these columns
names: files of writes that failed, or of rows that were deleted. It
only lists them; it deletes nothing. Name every column that holds files,
or the files of the others will be listed too. Resized copies of images
are left out.
Images
Reading an image’s width and height when it is uploaded, galleries and logos, and resized copies are in Images.
Not yet
The OpenAPI document does not say that an input also takes a form.
Reference
Storage
| Method | What it does |
|---|---|
Storage::from_env() | from RIND_STORAGE, RIND_MEDIA_URL, RIND_STORAGE_ACCEL |
Storage::local(folder) | files in a folder, created if needed |
Storage::s3(bucket, prefix) | files in a bucket, with the AWS_* variables (feature storage-s3) |
.base_url(url) | the public address the keys are below |
.serve(path) | the application serves the files at path/<key>; and gives them that address when there is no base_url |
.expiry(duration) | how long a signed address is valid (an hour) |
.accel_redirect(path) | downloads are handed to nginx |
.sizes(Sizes) | resized copies of the images (Images) |
store(folder, name, bytes) | stores a file the application made; gives its File |
download(key, filename, attachment) | answers a stored file as a download |
put, get, delete, keys | the files, by their keys |
Tested against a real application
Against the 5,907 documents of a real Django application, read as File
columns from the folder Django stored them in, the size rind found was
Django’s for 5,903. The other 4 files were not in the folder.