Introduction
rind (Rind Is Not Django) is a framework for writing REST APIs on PostgreSQL, in Rust. It is written for people who know Django and Django REST framework, and who want to find the same ideas in Rust: models, a query layer, migrations, serializers, filters, permissions, viewsets.
Here is a complete endpoint, a list of trains that anyone signed in can read, that the staff can change, searchable and sortable:
#![allow(unused)]
fn main() {
#[derive(Resource)]
#[resource(model = Train, path = "trains", out = TrainOut, filters = TrainFilters, input = TrainIn, delete)]
#[rule(staff)]
#[rule(authenticated, actions(list, retrieve))]
#[search(Train::name(), unaccent)]
#[ordering(by(id, number, name), default("number"))]
pub struct TrainResource;
}
If you know DRF, you can probably read it already: a ModelViewSet with
its serializer, its filterset, its permissions, its search_fields and
its ordering_fields.
Not a port
rind is not Django translated into Rust. It keeps Django’s ideas, and changes two things about them.
It decides at compile time what Django decides at run time. A field that does not exist, a relation followed the wrong way, a rule that names an action the resource does not have: these are errors of the compiler, not exceptions in production.
It does nothing behind your back.
- Nothing is filtered silently. A model whose table holds rows that most code must not read has no default query at all, so every use says which rows it reads.
- Nothing runs because a row was saved, unless the model says so.
There are no signals. What every write of a model does is listed on the
model (
#[model(behaviours(Tracking))]); anything else is a function, called by name. - A filter through a “many” relation never repeats a row. It is
written as an
EXISTS, not a join, so there is no.distinct()to remember. - A list reads only the columns its fields need, not the whole row, and nested objects are loaded once per page, never once per row.
- Pages never overlap. Every ordering ends with the primary key.
How to read this book
- New to rind? Follow the tutorial. In six parts, it builds a small library API from an empty folder to a tested application, and introduces every important idea on the way.
- Looking for the rind way of something you know in Django? rind for Django developers maps the Django and DRF names to rind’s, with links to the chapters.
- Working on a subject? The topic guides explain one subject each, from the common case to the rare one, and end with a reference section. They are grouped as in the table of contents:
| Part | Chapters |
|---|---|
| Starting | the rind tool, the command line, starting from an existing database, porting a Django application, the sample application, organising an application in crates |
| The data | models, queries, geography, migrations, primary and replica databases |
| The API | resources, serializers, inputs, filters, parameters, authentication, signing in, permissions, actions, OpenAPI, exports |
| Beyond the API | plugins: logging, CORS, health, metrics, cache, usage log, mail, jobs, files, images, behaviours |
The words with a precise meaning (domain, resource, mode, scope…) are defined in the glossary.
The API documentation of the crates (rustdoc) is beside this book when it is read on the project’s site.
Where it stands
rind is young. It was grown against a real Django application of some size (several hundred models), whose answers it was compared with, request by request, and it is tested on PostgreSQL. It has not been released yet: the names in this book can still change.
It runs on axum and on actix-web. The core knows neither: each has its adapter, behind a Cargo feature of the same name, and your code is the same with both.
The crates
You depend on rind; it re-exports the others.
| Crate | What it is |
|---|---|
rind | what an application depends on: it re-exports the crates below, and holds the plugins, each behind a Cargo feature |
rind-query | the query layer, without any database driver |
rind-db | PostgreSQL: running queries, migrations, replicas, reading a database’s schema |
rind-api | resources, serializers, permissions, the two web adapters, the hooks plugins add |
rind-macros | the derives: Model, Resource, Serializer, Input, FilterSet… |
rind-cli | the rind tool: new projects, domains, models, resources, a project written from a database |
rind-auth | signing in: tokens, passwords, password reset, sign-in codes. A separate dependency, not re-exported by rind (Signing in) |
Most examples in the topic guides come from the sample application of the repository, the railway: you can read it whole, run it and change it. The tutorial builds its own, smaller application.
rind for Django developers
This page is a map. On the left, a Django or Django REST framework name
you know; on the right, where the same idea lives in rind, and the
chapter that explains it. Read it when you think “how do I write
get_queryset here?”.
rind keeps most of Django’s ideas, but moves many decisions from run time to compile time, and makes explicit what Django does implicitly. The last section lists the main differences of spirit.
The project
| Django | rind | Chapter |
|---|---|---|
django-admin startproject | rind new | Starting a project |
manage.py startapp | rind add domain | Starting a project |
| an app | a domain: one crate per layer (<domain>-models, <domain>-api…) | Organising an application |
INSTALLED_APPS, ROOT_URLCONF | app(): .models(..), .api(..), .with(..) | The command line |
settings.py | environment variables (DATABASE_URL, BIND, …) and Rust code in app() | The command line |
manage.py | rind (the tool), and the application’s binary | The command line |
| a management command | Cli::command("name", "about", function) | The command line |
runserver | rind serve | The command line |
inspectdb | rind inspect | Starting from a database |
| middleware | a plugin’s hook (Around) | Plugins |
a reusable app (django-cors-headers, …) | a plugin, .with(..), behind a Cargo feature | Plugins |
Models
| Django | rind | Chapter |
|---|---|---|
class Book(models.Model) | #[derive(Model)] struct Book | Models |
Meta.db_table | #[model(table = "…")] (always given) | Models |
CharField(max_length=200) | String with #[column(max_length = 200)] | Models |
null=True | Option<T> | Models |
default=… | #[column(default = "SQL")], or a default in the input | Models, Inputs |
ForeignKey(Author, on_delete=…) | author_id: i64 with #[fk(Author, on_delete = …)] | Models |
related_name / book_set | reverse = books on the key, or #[reverse(..)] on the target: never implicit | Models |
ManyToManyField | #[m2m(name = …, through = "…", from = "…", to = "…")] | Models |
Meta.indexes, unique_together, constraints | #[index(..)], #[unique(..)], #[check(..)] | Models |
| an abstract model, a mixin | a field group (#[with_fields(..)]) or a behaviour | Behaviours |
a custom manager, objects.published() | a scope: impl Book { fn published() -> Query<Book> } | Models, Queries |
| a default manager that filters | #[model(scoped)]: no default query at all | Models |
signals (post_save, …) | none: a hook of the resource, a behaviour, or a function called by name | Inputs, Behaviours |
Queries
| Django | rind | Chapter |
|---|---|---|
Book.objects.filter(year__gt=1970) | Query::<Book>::new().filter(Book::year().gt(1970)) | Queries |
"author__name" | Book::author().name(): a typed path | Queries |
Q(a) | Q(b), ~Q(a) | a | b, !a on conditions | Queries |
F("price") | the path itself, Book::price() | Queries |
.annotate(n=Count("books")) | Author::books().count() in a serializer’s #[annotated], or in a query | Queries, Serializers |
select_related, prefetch_related | not needed: nested fields are loaded per page, in one query each | Serializers |
.distinct() after a filter through a many relation | not needed: such a filter is an EXISTS | Queries |
select_for_update() | a lock on the query | Queries |
transaction.atomic() | db.begin(); every write of a resource is already a transaction | Queries, Inputs |
makemigrations / migrate / showmigrations | rind make / rind migrate / rind status | Migrations |
makemigrations --check | rind check (and the test rind new writes) | Migrations |
DATABASES, routers, .using() | Db, replicas, ctx.database(name) | Databases |
The API
| DRF | rind | Chapter |
|---|---|---|
ModelViewSet | #[derive(Resource)] | Resources |
a router, urls.py | Api::new("domain").resource::<R>() | Resources |
ModelSerializer (reading) | #[derive(Serializer)], the output | Serializers |
ModelSerializer (writing), validate_<field>, validate | #[derive(Input)], the input | Inputs |
read_only=True / write_only=True | a field only in the output / only in the input | Serializers |
source="author_id" | #[field(name = "author")] author_id | Serializers |
| a nested serializer | #[nested(key = …)], #[nested(many, by = …)] | Serializers |
SerializerMethodField | #[computed(loader = …)], called once per page | Serializers |
dynamic fields (?fields=) | built in: fields, omit, include | Serializers |
perform_create, perform_update, save() | a hook: impl Writes for R | Inputs |
django-filter’s FilterSet | #[derive(FilterSet)] | Filters |
search_fields | #[search(path, mode)] | Filters |
ordering_fields, Meta.ordering | #[ordering(by(..), default(..))] | Filters |
PageNumberPagination | built in; {parameters, nav, results} | Filters |
@action(detail=True) | #[action(POST)] taking the object | Actions |
@action(detail=False) | #[action(GET)] without the object | Actions |
| query parameters read by hand | typed parameters, #[derive(Parameters)] | Parameters |
| authentication classes | an Authenticate implementation, or rind-auth | Authentication |
djangorestframework-simplejwt | rind-auth: POST /token, /token/refresh | Signing in |
request.user | ctx.user, an Identity | Authentication |
permission_classes | #[rule(..)] | Permissions |
get_queryset filtering on the user | a mode: #[mode(.., query = …)] | Permissions |
has_object_permission | the mode’s query: an object outside it is a 404 | Permissions |
drf-spectacular | built in: rind openapi | OpenAPI |
| renderers (CSV, xlsx) | ?format=csv, ?format=xlsx | Exports |
APIClient in tests | app.router(..) called with tower’s oneshot | Tutorial, part 6 |
Around the API
| Django | rind | Chapter |
|---|---|---|
django.core.mail, anymail | the mail plugin | |
| Celery, django-q | the jobs plugin | Jobs |
FileField, django-storages | File columns and the storage plugin | Files |
ImageField, easy-thumbnails | the images plugin | Images |
the cache framework, cache_page | the cache plugin, with ETags | Cache |
LOGGING | tracing, RUST_LOG, RIND_LOG=json | Logging |
| django-cors-headers | the CORS settings | CORS |
| django-prometheus | the metrics plugin | Metrics |
What is not there
Some things a Django developer expects do not exist, on purpose or not yet:
- No admin. rind serves APIs only.
- No templates, no forms, no sessions. The front end is a separate client.
- No
createsuperuser. Write a command of your own: the tutorial shows one. - No migrating backwards, no squashing. Migrations go forward; a mistake is fixed by a new migration.
Differences of spirit
- Errors at compile time. A misspelt field, a relation followed the wrong way, a rule naming an action that does not exist: the compiler refuses them, where Django would fail at run time, or silently do nothing.
- Nothing implicit. No reverse relation is guessed, no manager filters behind your back, no signal runs code from far away. What a write does is in its hook, or in the behaviours listed on the model.
- No N+1 by construction. Nested objects and computed values are loaded for a whole page at a time. A list reads only the columns of the fields it sends.
- Pages that never overlap. Every ordering ends with the primary key.
- SQL you can read. Migrations are plain SQL files, and queries are built from typed paths that turn into predictable SQL.
Tutorial: a library API
This tutorial builds a small, complete REST API with rind, one step at a time. If you have followed Django’s “Writing your first Django app” tutorial, the path will feel familiar: create a project, describe the data, serve it over HTTP, open it to users, add some behaviour of your own, and test it.
The application is a library:
- the library has authors and books;
- anyone can read the catalogue, but only librarians can change it;
- signed-in members can borrow a book and give it back;
- members see their own loans, librarians see every loan.
Every command and every answer shown in these pages was really run.
The parts
- Creating a project:
rind new, what it writes, and the firstrind serve. - Models and migrations: authors and books, a foreign
key, and the SQL that
rind makewrites. - A first resource: the
/booksendpoint, its serializer and its input; creating, reading, changing and deleting books withcurl. - Lists: filters, search, ordering, pages: what a client can ask of a list.
- Users and permissions: signing in with
rind-auth, a second domain for the loans, rules, and permission modes. - Actions and tests: a
give_backaction, and a test that runs the whole story over HTTP.
Each part takes between fifteen and thirty minutes.
What you need
- Rust, recent enough for the 2024 edition (
rustup update). - Docker, to run PostgreSQL. Any PostgreSQL server will do if you already have one.
curl, to talk to the API. Any HTTP client works.- A checkout of rind. rind is not published on crates.io yet, so the
rindtool is installed from the repository, and new projects depend on that checkout by its path.
You should be able to read Rust. You do not need to know how macros work:
rind uses derives (#[derive(Model)], #[derive(Resource)]) to write
most of the code for you, and you will only write attributes on structs.
Where to go after
The tutorial shows the common path. Each topic has a chapter of its own that goes into detail: Models, Queries, Resources, Serializers, Inputs, Filters, Permissions, and the others in the table of contents. rind for Django developers maps the Django names you know to the rind ones.
Part 1: Creating a project
In Django, you start with django-admin startproject and then
manage.py startapp. In rind, one command does both: rind new.
Installing the rind tool
From a checkout of the rind repository:
cargo install --path crates/rind-cli # or: make install-cli
This installs two programs, rind and cargo-rind, so rind … and
cargo rind … do the same thing. Check that it works:
rind --help
Creating the project
rind new library --domain catalog
library is the name of the project. --domain catalog creates a first
domain called catalog.
A domain is the rind word for a part of your application that holds
related models and endpoints: what Django calls an app. Our library
will have two domains: catalog (authors and books) and, later,
lending (who borrowed what).
The tool prints what it writes:
project library
wrote library/Cargo.toml
wrote library/docker-compose.yml
wrote library/.env.example
wrote library/.env
wrote library/.gitignore
wrote library/README.md
wrote library/app/Cargo.toml
wrote library/app/src/lib.rs
wrote library/app/src/main.rs
wrote library/app/tests/schema.rs
domain catalog
wrote library/crates/catalog/catalog-models/Cargo.toml
wrote library/crates/catalog/catalog-models/src/lib.rs
wrote library/crates/catalog/catalog-models/migrations/embedded.rs
…
wrote library/crates/catalog/catalog-api/Cargo.toml
wrote library/crates/catalog/catalog-api/src/lib.rs
…
What is in it
library/
Cargo.toml the Cargo workspace
docker-compose.yml a PostgreSQL server for development
.env DATABASE_URL, BIND, RIND_TEST_DATABASE_URL
app/
src/lib.rs app(): the application, described once
src/main.rs the command line (like manage.py)
tests/schema.rs a test that runs `rind check`
crates/
catalog/
catalog-models/ the models of the domain, and its migrations
catalog-api/ the resources (endpoints) of the domain
A few things are different from a Django project.
A domain is several crates. Each domain is split into layers, one
Rust crate per layer: catalog-models holds the models,
catalog-api the HTTP endpoints. Rust compiles a crate as a whole, so
small crates mean that a change recompiles only a small part of the
project. It also keeps the models free of any HTTP code. You can read the
full reasons in Organising an application; for now,
remember that models go in -models, endpoints in -api.
The application is a value. Open app/src/lib.rs:
#![allow(unused)]
fn main() {
pub fn app() -> rind::Application {
rind::Application::new("Library", env!("CARGO_PKG_VERSION"))
.models(catalog_models::migrations())
.api(catalog_api::api())
}
}
This function is the equivalent of Django’s INSTALLED_APPS and
ROOT_URLCONF together. Every domain gives its models (.models(..))
and its endpoints (.api(..)). Everything rind does — creating tables,
serving routes, writing the OpenAPI document — starts from this value.
The rind tool adds a line here each time you add a domain.
main.rs is one line. Open app/src/main.rs:
fn main() -> std::process::ExitCode {
rind::cli::main(app::app())
}
The commands of your application (migrate, serve, …) are rind’s,
like the commands of manage.py are Django’s. You will add a command of
your own in part 5.
Starting the database
The project comes with a docker-compose.yml for PostgreSQL, and its
.env points to it:
cd library
docker compose up -d
# .env
DATABASE_URL=postgres://library:library@127.0.0.1:5432/library
BIND=127.0.0.1:8080
RIND_TEST_DATABASE_URL=postgres://library:library@127.0.0.1:5432/library
If you already run a PostgreSQL server on port 5432, change the port in
both files, or point DATABASE_URL to a database of your own server.
The rind tool reads .env and passes it to your application as
environment variables. (Plain cargo run and cargo test do not read
it: remember this when you get to the tests.)
The first run
rind check
rind migrate
rind serve
rind checkcompiles the application and checks that the models and the migrations agree. The first time, compiling takes a few minutes.rind migrateapplies the migrations. There are none yet, but it creates the table where rind records what it has applied.rind servestarts the server:
Library (axum) listening on http://127.0.0.1:8080
The server is built on axum by default. rind new --web actix
builds it on actix-web instead; your own code is the same with both.
There is nothing to see yet: the application has no endpoint. Stop the
server with Ctrl-C, and let’s describe some data.
Coming from Django: there is no
settings.py. The configuration that changes between machines (the database, the address to listen on, secrets) comes from environment variables. Everything else is Rust code, inapp(), checked by the compiler.
Next: Part 2: Models and migrations.
Part 2: Models and migrations
A model describes a table, as in Django. In rind, a model is a Rust
struct with #[derive(Model)]: one field per column.
Adding two models
The rind tool writes the struct for you:
rind add model catalog Author name:String
rind add model catalog Book title:String year:i32
edited crates/catalog/catalog-models/src/lib.rs (struct Author)
edited crates/catalog/catalog-models/src/lib.rs
No migration is written: `rind make` writes it, once Author is what it should be.
add model takes the domain, the name of the model, and its fields as
name:RustType. It adds the struct to the domain’s models crate, and a
line to the list of the domain’s tables. It does not write a
migration yet: you will first finish the model by hand.
Open crates/catalog/catalog-models/src/lib.rs. Each struct comes with a
block of comments that reminds you of the syntax; delete it once you
have read it. (--bare leaves it out.)
Finishing the models
Here is the file as we want it:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-models/src/lib.rs
use rind::prelude::*;
/// Someone who writes books.
#[derive(Debug, Clone, Model)]
#[model(table = "catalog_author")]
#[reverse(name = books, model = Book, fk = "author_id")]
pub struct Author {
pub id: i64,
#[column(max_length = 100)]
pub name: String,
}
/// A book of the library.
#[derive(Debug, Clone, Model)]
#[model(table = "catalog_book")]
pub struct Book {
pub id: i64,
#[column(max_length = 200)]
pub title: String,
pub year: i32,
#[fk(Author, on_delete = restrict)]
pub author_id: i64,
}
/// The tables of this domain.
pub fn schema() -> Vec<rind::schema::Table> {
vec![
rind::schema::Table::of::<Author>(),
rind::schema::Table::of::<Book>(),
]
}
/// The migrations of this domain: its tables, change after change.
pub fn migrations() -> rind::migrations::Domain {
rind::migrations::domain!("catalog", schema())
}
}
Let’s read it piece by piece.
The table name is explicit. #[model(table = "catalog_book")]
names the table. The tool chose <domain>_<model>, the same convention
as Django’s <app>_<model>.
The key is id. A field id: i64 is the primary key, and the
database gives its value (a bigint identity column). This is Django’s
BigAutoField.
The SQL type comes from the Rust type. String is text, or
character varying(n) with max_length = n; i32 is integer; i64
is bigint. A column is NOT NULL unless its type is an Option:
Option<String> is Django’s null=True. The Models
chapter lists every type.
A foreign key is a field and an attribute. The column is the field
author_id. The attribute #[fk(Author, on_delete = restrict)] says
which model it points to, and what happens to a book when its author is
deleted: restrict refuses the deletion, like Django’s
on_delete=PROTECT. (cascade and set_null exist too.)
The relation gets its name from the field: author_id gives a relation
called author. You will use it in queries as Book::author().
The way back is declared too. In Django, a ForeignKey silently
gives the other model a book_set (or the related_name). In rind,
nothing is guessed: #[reverse(name = books, model = Book, fk = "author_id")] on Author says “an author has books: the rows of
Book whose author_id is this author”. You will use it in part 3 to
count each author’s books.
Coming from Django: each model has typed paths to its columns and relations:
Book::title(),Book::author(),Book::author().name(). They replace the strings of Django’s querysets ("author__name"). A typo is a compile error, not aFieldErrorat run time.
Writing the migration
rind make
catalog 0001_initial
create catalog_author
create catalog_book
key catalog_book.author_id
This is manage.py makemigrations. rind compares the models with the
state recorded by the previous migrations, and writes what changed. The
migration is plain SQL, in
crates/catalog/catalog-models/migrations/0001_initial.sql:
-- rind migration: catalog 0001_initial
-- create catalog_author
CREATE TABLE "catalog_author" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"name" character varying(100) NOT NULL
);
-- create catalog_book
CREATE TABLE "catalog_book" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"title" character varying(200) NOT NULL,
"year" integer NOT NULL,
"author_id" bigint NOT NULL
);
-- key catalog_book.author_id
ALTER TABLE "catalog_book" ADD CONSTRAINT "catalog_book_author_id_fkey" FOREIGN KEY ("author_id") REFERENCES "catalog_author" ("id") ON DELETE RESTRICT;
CREATE INDEX "catalog_book_author_id_idx" ON "catalog_book" ("author_id");
You can read it, review it in a pull request, and change it by hand if
you need to. Beside it, 0001_initial.state.json records what the
models looked like, so that the next rind make knows what changed; and
embedded.rs lists the files so that they are compiled into the
application. You commit all three.
Notice that the foreign key got an index without asking, as in Django.
Applying it
rind migrate
applied catalog 0001_initial
rind status shows what the database has applied (showmigrations):
[x] catalog 0001_initial
Changing a model
Change a model, run rind make again, and you get a second migration
with only the difference. If you rename a field, rind make cannot tell
a rename from a deletion plus an addition, so it asks you (or you say it
with --rename book.old_name=new_name).
rind check fails when a model has changed without a migration. It runs
in cargo test too, through the test that rind new wrote in
app/tests/schema.rs, so a forgotten migration does not reach
production.
What we have
Two tables, created by a migration you can read. There is still no endpoint: that is the next part.
Next: Part 3: A first resource.
Part 3: A first resource
A resource is a model served over HTTP: what Django REST framework
calls a ModelViewSet. It gives a list, a detail, and the writes.
Generating it
rind add resource catalog Book --rule anyone
rind add resource catalog Author --rule anyone
wrote crates/catalog/catalog-api/src/books/mod.rs
wrote crates/catalog/catalog-api/src/books/serializers.rs
wrote crates/catalog/catalog-api/src/books/filters.rs
wrote crates/catalog/catalog-api/src/books/views.rs
edited crates/catalog/catalog-api/src/lib.rs
…
--rule anyone opens the resource to everyone, signed in or not. By
default the tool writes a resource for the staff only: an endpoint that a
generator opens by default is an endpoint that gets deployed open by
mistake. We open both resources now to try them, and we will close them
properly in part 5.
Each resource is a folder with the files a DRF developer expects:
| File | Holds | In DRF |
|---|---|---|
serializers.rs | what a book looks like in an answer, and what can be written | serializers.py |
filters.rs | the query parameters that filter the list | a django-filter FilterSet |
views.rs | the resource: its model, its path, its rules | views.py |
The tool also added the resource to the domain’s api(), in
crates/catalog/catalog-api/src/lib.rs:
#![allow(unused)]
fn main() {
pub fn api() -> rind::api::Api {
rind::api::Api::new("catalog")
.resource::<books::BookResource>()
.resource::<authors::AuthorResource>()
}
}
That is the whole of the routing: there is no urls.py and no router to
register.
The resource
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/books/views.rs
#[derive(Resource)]
#[resource(
model = Book,
path = "books",
out = BookOut,
filters = BookFilters,
input = BookIn,
delete
)]
#[rule(anyone)]
pub struct BookResource;
}
The struct is empty: everything is in the attributes. model is the
model, path the URL, out the serializer of the answers, input what
can be written, filters the filterset, and delete allows deletions.
#[rule(anyone)] says who may use it.
rind routes lists what it serves:
catalog
/authors GET POST
/authors/{id} DELETE GET PATCH PUT
/books GET POST
/books/{id} DELETE GET PATCH PUT
Two structs: what goes out, what comes in
The generated serializers.rs has two structs. DRF uses one
ModelSerializer for both directions, with read_only and write_only
flags; rind uses two, because what a client reads and what it may write
are rarely the same.
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/books/serializers.rs
/// A book as the API shows it.
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Book)]
pub struct BookOut {
#[field(mandatory)]
pub id: Option<i64>,
pub title: Option<String>,
pub year: Option<i32>,
pub author_id: Option<i64>,
}
/// What can be written on a book.
#[derive(Debug, Input)]
#[input(model = Book)]
pub struct BookIn {
pub title: Option<String>,
pub year: Option<i32>,
pub author_id: Option<i64>,
}
}
Every field of the output is an Option. A client can ask for some
fields only (you will see how below). A field it did not ask for is not
read from the database, and stays None. mandatory means the field is
always sent.
Every field of the input is an Option too, for another reason: a
PATCH sends only some fields. The input knows from the model which
fields are required on a creation.
Let’s improve the generated code a little. DRF sends a foreign key under
the name of the relation ("author": 1), not of the column; and the
input should check that the author exists:
#![allow(unused)]
fn main() {
use catalog_models::{Author, Book};
use rind::{Input, Serializer};
use crate::authors::AuthorOut;
/// A book as the API shows it.
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Book)]
pub struct BookOut {
#[field(mandatory)]
pub id: Option<i64>,
pub title: Option<String>,
pub year: Option<i32>,
/// The author's id, under the relation's name.
#[field(name = "author")]
pub author_id: Option<i64>,
/// The whole author, when the client asks for it.
#[nested(key = author_id, on_request)]
pub author_details: Option<AuthorOut>,
}
/// What can be written on a book.
#[derive(Debug, Input)]
#[input(model = Book)]
pub struct BookIn {
#[input(max_length = 200)]
pub title: Option<String>,
pub year: Option<i32>,
#[input(name = "author", fk = Author)]
pub author_id: Option<i64>,
}
}
#[field(name = "author")]sends the field asauthor.#[nested(key = author_id, on_request)]is a nested serializer, like a nestedAuthorSerializerin DRF.on_requestmeans it is sent only when the client asks for it.#[input(name = "author", fk = Author)]reads the field asauthor, and checks that the author exists, with a clear error on the field.#[input(max_length = 200)]checks the length before the database does.
And for the authors, an output with a count of their books:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/authors/serializers.rs
use catalog_models::Author;
use rind::{Input, Serializer};
/// An author as the API shows it.
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Author)]
pub struct AuthorOut {
#[field(mandatory)]
pub id: Option<i64>,
pub name: Option<String>,
/// How many books the library has by this author.
#[annotated(expr = Author::books().count(), on_request)]
pub books_count: Option<i64>,
}
/// What can be written on an author.
#[derive(Debug, Input)]
#[input(model = Author)]
pub struct AuthorIn {
#[input(max_length = 100)]
pub name: Option<String>,
}
}
#[annotated(expr = …)] is DRF’s field backed by a queryset
.annotate(...). Author::books() is the reverse relation declared in
part 2, and .count() counts it, in the same SQL query as the list.
Run rind serve, and let’s use the API.
Creating
curl -X POST -H 'Content-Type: application/json' \
-d '{"name": "Frank Herbert"}' localhost:8080/authors
curl -X POST -H 'Content-Type: application/json' \
-d '{"name": "Ursula K. Le Guin"}' localhost:8080/authors
{"id":1,"name":"Frank Herbert"}
{"id":2,"name":"Ursula K. Le Guin"}
curl -X POST -H 'Content-Type: application/json' \
-d '{"title": "Dune", "year": 1965, "author": 1}' localhost:8080/books
{"id":1,"title":"Dune","year":1965,"author":1}
Add two more books the same way: The Dispossessed (1974) and A Wizard of Earthsea (1968), both by author 2.
A creation answers 201 Created, with the object as a read would show
it.
Validation errors
An author that does not exist:
curl -X POST -H 'Content-Type: application/json' \
-d '{"title": "Children of Dune", "year": 1976, "author": 9}' localhost:8080/books
{"author":["Invalid pk \"9\" - object does not exist."]}
Several problems at once:
curl -X POST -H 'Content-Type: application/json' \
-d '{"title": "", "year": "soon"}' localhost:8080/books
{"author":["This field is required."],"title":["This field may not be blank."],"year":["Invalid value."]}
The answer is a 400 Bad Request, with a list of messages per field: the
same shape, and mostly the same messages, as DRF. A client written for a
DRF API reads them as it always has.
Reading
curl localhost:8080/books
{
"parameters": {"page": "page", "pagesize": "page_size"},
"nav": {"size": 100, "page": 1, "next": null, "prev": null, "count": 3, "pages": 1},
"results": [
{"id": 3, "title": "A Wizard of Earthsea", "year": 1968, "author": 2},
{"id": 1, "title": "Dune", "year": 1965, "author": 1},
{"id": 2, "title": "The Dispossessed", "year": 1974, "author": 2}
]
}
(The answers in this tutorial are shown indented; the server sends them on one line.)
A list is always paginated. nav says where you are: the page size, the
page number, the next and previous pages, the number of objects and of
pages. results holds the objects. We will come back to it in part 4.
One object:
curl localhost:8080/books/1
{"id":1,"title":"Dune","year":1965,"author":1}
curl localhost:8080/books/99
{"detail":"Not found."}
Choosing the fields
The client chooses the fields with three query parameters: fields
(only these), omit (all but these) and include (the default ones,
plus these):
curl 'localhost:8080/books?fields=title,author_details'
{
"parameters": {…}, "nav": {…},
"results": [
{"id": 3, "title": "A Wizard of Earthsea", "author_details": {"id": 2, "name": "Ursula K. Le Guin"}},
{"id": 1, "title": "Dune", "author_details": {"id": 1, "name": "Frank Herbert"}},
{"id": 2, "title": "The Dispossessed", "author_details": {"id": 2, "name": "Ursula K. Le Guin"}}
]
}
id is there because it is mandatory. The authors are read for the
whole page in one query, whatever the number of books: there is no
N+1 problem to think of, and no select_related to remember.
curl 'localhost:8080/authors?include=books_count'
{
"parameters": {…}, "nav": {…},
"results": [
{"id": 1, "name": "Frank Herbert", "books_count": 1},
{"id": 2, "name": "Ursula K. Le Guin", "books_count": 2}
]
}
A name that is not a field is an error, not silently ignored:
curl 'localhost:8080/books?fields=price'
{"detail":"Unknown field(s): price."}
Changing and deleting
curl -X PATCH -H 'Content-Type: application/json' \
-d '{"year": 1966}' localhost:8080/books/1
{"id":1,"title":"Dune","year":1966,"author":1}
PATCH changes the fields it sends; PUT expects them all. DELETE /books/{id} answers 204 No Content. Deleting an author who still has
books is refused, because the foreign key says on_delete = restrict.
Coming from Django: where are
get_queryset,perform_createandget_serializer_class? They exist, under other names: the rows a user may see are a permission mode (part 5), and code that runs during a write is a hook (part 5 too). The Resources chapter has the full map.
Next: Part 4: Lists.
Part 4: Lists: filters, search, ordering, pages
A list endpoint is rarely read whole. Clients filter it, search it, sort
it and read it page by page. In DRF you would add django-filter, a
SearchFilter, an OrderingFilter and a pagination class. In rind the
four are part of the resource.
Filters
The generated filters.rs holds an empty filterset: a struct whose
fields are query parameters. Let’s fill it:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/books/filters.rs
use catalog_models::Book;
use rind::FilterSet;
/// What the list of books can be filtered by.
#[derive(Debug, Default, FilterSet)]
#[filterset(model = Book)]
pub struct BookFilters {
/// `?author=2`: the books of one author.
#[filter(path = Book::author_id())]
pub author: Option<i64>,
/// `?published_after=1970`
#[filter(path = Book::year(), lookup = gt)]
pub published_after: Option<i32>,
/// `?published_before=1970`
#[filter(path = Book::year(), lookup = lt)]
pub published_before: Option<i32>,
}
}
Each field is one parameter. Its name is the name of the parameter, its
type says how the value is read, path is the column it filters on, and
lookup the comparison: eq by default, and gt, lt, ge, le,
ne, icontains… (the Filters chapter lists them). It
is django-filter’s NumberFilter(field_name="year", lookup_expr="gt").
The doc comments (///) are not only for you: they go into the OpenAPI
description of the parameter.
curl 'localhost:8080/books?include=author_details&author=2'
{
"parameters": {…},
"nav": {"size": 100, "page": 1, "next": null, "prev": null, "count": 2, "pages": 1},
"results": [
{"id": 3, "title": "A Wizard of Earthsea", "year": 1968, "author": 2,
"author_details": {"id": 2, "name": "Ursula K. Le Guin"}},
{"id": 2, "title": "The Dispossessed", "year": 1974, "author": 2,
"author_details": {"id": 2, "name": "Ursula K. Le Guin"}}
]
}
A value of the wrong type is a 400 that names the parameter:
curl 'localhost:8080/books?author=abc'
{"author":["Enter a number."]}
As with django-filter, an empty value and an unknown parameter are ignored.
Search
?search= looks for words in some fields: DRF’s search_fields. The
resource says which fields, and how:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/books/views.rs
#[derive(Resource)]
#[resource(model = Book, path = "books", /* … as before … */)]
#[rule(anyone)]
#[search(Book::title(), unaccent)]
#[search(Book::author().name(), unaccent)]
#[ordering(by(id, title, year), default("title"))]
pub struct BookResource;
}
Book::author().name() follows the foreign key: a book is found by the
name of its author, as "author__name" does in Django. unaccent
ignores case and accents, so guin finds “Le Guin” and eric would find
“Éric”.
unaccent uses a PostgreSQL extension of the same name. The domain
declares that it needs it, in its models crate:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-models/src/lib.rs
pub fn migrations() -> rind::migrations::Domain {
rind::migrations::domain!("catalog", schema()).extension("unaccent")
}
}
and a migration creates it:
rind make --name unaccent
rind migrate
catalog 0002_unaccent
extension unaccent
-- crates/catalog/catalog-models/migrations/0002_unaccent.sql
CREATE EXTENSION IF NOT EXISTS "unaccent";
Watch out: if you forget the extension, the code compiles and
rind checkpasses, but every search answers500and the server’s log saysfunction unaccent(character varying) does not exist.
curl 'localhost:8080/books?search=guin&fields=title'
{
"parameters": {…}, "nav": {…},
"results": [
{"id": 3, "title": "A Wizard of Earthsea"},
{"id": 2, "title": "The Dispossessed"}
]
}
Several words must all match (?search=le guin), and a quoted phrase is
one word, as in DRF.
Ordering
#[ordering(by(id, title, year), default("title"))] lists the names a
client may sort by, and the default order. It replaces both DRF’s
ordering_fields and Django’s Meta.ordering:
curl 'localhost:8080/books?published_after=1966&ordering=-year&fields=title,year'
{
"parameters": {…}, "nav": {…},
"results": [
{"id": 2, "title": "The Dispossessed", "year": 1974},
{"id": 3, "title": "A Wizard of Earthsea", "year": 1968}
]
}
-year sorts in descending order. A name that is not allowed is ignored,
and the default order applies.
rind always adds the primary key at the end of an ordering. Two books of the same year are then always in the same order, so a page never shows a book twice, and never skips one.
Pages
Every list is paginated. The default page has 100 objects; the client
chooses with page and page_size:
curl 'localhost:8080/books?page_size=2&page=2&fields=title'
{
"parameters": {"page": "page", "pagesize": "page_size"},
"nav": {"size": 2, "page": 2, "next": null, "prev": 1, "count": 3, "pages": 2},
"results": [{"id": 2, "title": "The Dispossessed"}]
}
nav.countis the number of objects after the filters and the search;nav.pagesthe number of pages.nav.nextandnav.prevare page numbers (not URLs, as in DRF), ornull.parameterstells the client the names of the two parameters.?page=lastis the last page. A page that does not exist answers the first page, not an error.
Coming from Django: the envelope is not DRF’s
{count, next, previous, results}. If you port an API whose clients expect another shape, see Answering as Django did.
Everything together
The parameters combine freely:
GET /books?search=dune&published_after=1960&ordering=-year&page_size=20&fields=title,author_details
rind runs this as one query for the page and one for the count, plus one for the nested authors: never one query per book.
Next: Part 5: Users and permissions.
Part 5: Users and permissions
So far everyone can do everything. In this part we will:
- let users sign in, with the
rind-authcrate; - close the catalogue: everyone reads, only the staff writes;
- add the loans, in a second domain, where each member sees only their own.
How rind sees users
rind itself does not know your users. It asks one question per request:
who is this? The answer is an Identity: an id, the flags
is_staff and is_superuser, and the user’s groups. Everything else —
the rules, the modes — reads this identity.
Something must answer the question. You can write it yourself (the
Authentication chapter shows how), or use
rind-auth, which does what Django’s auth app and
djangorestframework-simplejwt do: a user model, password hashing,
POST /token to sign in, JSON Web Tokens, password reset.
Adding rind-auth
rind-auth is a crate of its own, beside rind. While rind is not
published, add it by path, next to rind, in the workspace’s
Cargo.toml:
# Cargo.toml
[workspace.dependencies]
rind = { path = "/path/to/rind/crates/rind" }
rind-auth = { path = "/path/to/rind/crates/rind-auth" }
and in app/Cargo.toml:
[dependencies]
rind-auth.workspace = true
Then, in app():
#![allow(unused)]
fn main() {
// app/src/lib.rs
pub fn app() -> rind::Application {
rind::Application::new("Library", env!("CARGO_PKG_VERSION"))
.models(rind_auth::models::migrations())
.models(catalog_models::migrations())
.models(lending_models::migrations())
.api(catalog_api::api())
.api(lending_api::api())
.with(
rind_auth::Auth::<rind_auth::models::User>::from_env()
.expect("RIND_JWT_SECRET")
.groups(rind_auth::models::groups()),
)
}
}
(lending does not exist yet: we create it below. Add those two lines
when you get there.)
.models(rind_auth::models::migrations())adds the crate’s own user and group tables,auth_userandauth_group, as Django’sdjango.contrib.authdoes. An application can use its own user model instead: see Signing in..with(..)installs a plugin: something that adds routes, checks or behaviour to the application. This one adds the sign-in routes, and answers “who is this?” for every request.from_env()reads the secret that signs the tokens fromRIND_JWT_SECRET. Add it to.env:
RIND_JWT_SECRET=change-me-to-a-long-random-string
Creating users
rind has no createsuperuser command yet, so we write a command of our
own: the equivalent of a Django management command. Commands are added
in main.rs:
// app/src/main.rs
use rind::prelude::*;
use rind_auth::models::User;
fn main() -> std::process::ExitCode {
rind::cli::Cli::new(app::app())
.command(
"create-user",
"creates a user: create-user NAME PASSWORD [--staff]",
create_user,
)
.main()
}
async fn create_user(_app: &rind::Application, args: &[String]) -> rind::cli::Result {
let [name, password, flags @ ..] = args else {
return Err("usage: create-user NAME PASSWORD [--staff]".into());
};
let staff = flags.iter().any(|flag| flag == "--staff");
let db = rind::db::Db::connect(&std::env::var("DATABASE_URL")?)?;
let user = db
.insert(
&Insert::<User>::new()
.value(User::username(), name.clone())
.value(User::is_staff(), staff),
)
.await?;
rind_auth::set_password::<User>(&db, user.id, password, rind_auth::password::ITERATIONS).await?;
println!("created user {} (id {})", user.username, user.id);
Ok(())
}
Insert::<User>::new().value(..) builds an INSERT with typed paths,
and db.insert(..) runs it and returns the new row. set_password
stores the password hashed the way Django hashes it.
rind migrate
rind create-user alice wonderland1
rind create-user bob builder123 --staff
applied auth 0001_initial
…
created user alice (id 1)
created user bob (id 2)
Alice is a member; Bob is a librarian (is_staff).
Signing in
POST /token takes a user name and a password, and answers two tokens:
curl -X POST -H 'Content-Type: application/json' \
-d '{"username": "alice", "password": "wonderland1"}' localhost:8080/token
{"access":"eyJ0eXAiOiJKV1Qi…","refresh":"eyJ0eXAiOiJKV1Qi…"}
The client sends the access token with each request, in the
Authorization header. It is valid for five minutes; POST /token/refresh with the refresh token gives a new one. This is
simplejwt’s protocol, so existing clients work as they are.
To keep the commands short, put the tokens in shell variables:
ALICE=$(curl -s -X POST -H 'Content-Type: application/json' \
-d '{"username": "alice", "password": "wonderland1"}' localhost:8080/token | jq -r .access)
BOB=$(curl -s -X POST -H 'Content-Type: application/json' \
-d '{"username": "bob", "password": "builder123"}' localhost:8080/token | jq -r .access)
A wrong password:
{"detail":"No active account found with the given credentials"}
Rules: who may do what
Now close the catalogue. In both books/views.rs and authors/views.rs,
replace #[rule(anyone)] with:
#![allow(unused)]
fn main() {
#[rule(staff)]
#[rule(anyone, actions(list, retrieve))]
}
A rule says who it is for, and which actions it allows (all of them
when it lists none). The rules are read in order, and the first one that
accepts the request decides. Here: the staff may do everything; anyone
else may only list and retrieve. This is DRF’s
IsAdminUser-or-ReadOnly, without writing a permission class.
curl -X POST -H 'Content-Type: application/json' \
-d '{"title": "Children of Dune", "year": 1976, "author": 1}' localhost:8080/books
{"detail":"Authentication credentials were not provided or are invalid."}
The answer is 401: nobody signed in, and signing in might help. With
Alice’s token, it is 403, because signing in did not help:
curl -X POST -H "Authorization: Bearer $ALICE" -H 'Content-Type: application/json' \
-d '{"title": "Children of Dune", "year": 1976, "author": 1}' localhost:8080/books
{"detail":"You do not have permission to perform this action."}
And with Bob’s, the book is created:
{"id":4,"title":"Children of Dune","year":1976,"author":1}
An action name that does not exist in a rule (a typo such as
actions(lsit)) is a compile error, not a rule that silently allows
nothing.
A second domain: the loans
Loans are another subject than the catalogue, so they get a domain of their own:
rind add domain lending
rind add model lending Loan 'borrowed_on:NaiveDate' 'returned_on:Option<NaiveDate>'
The loans point to the books and to the users, so lending-models
depends on catalog-models and on rind-auth. It also uses dates, from
the chrono crate. Add to crates/lending/lending-models/Cargo.toml:
rind-auth.workspace = true
chrono.workspace = true
catalog-models = { path = "../../catalog/catalog-models" }
and chrono to the workspace’s dependencies, in the root Cargo.toml
(rind also re-exports it as rind::db::chrono, which saves the
dependency; the generated code of rind add resource uses chrono
directly, so we add it):
chrono = { version = "0.4", default-features = false, features = ["std", "clock", "serde"] }
The model:
#![allow(unused)]
fn main() {
// crates/lending/lending-models/src/lib.rs
use catalog_models::Book;
use chrono::NaiveDate;
use rind::prelude::*;
use rind_auth::models::User;
/// A book lent to a member of the library.
#[derive(Debug, Clone, Model)]
#[model(table = "lending_loan")]
pub struct Loan {
pub id: i64,
#[fk(Book, on_delete = cascade, reverse = loans)]
pub book_id: i64,
#[fk(User, on_delete = cascade, reverse = loans)]
pub borrower_id: i64,
#[column(default = "CURRENT_DATE")]
pub borrowed_on: NaiveDate,
/// Empty while the book is still out.
pub returned_on: Option<NaiveDate>,
}
impl Loan {
/// The loans of one user.
pub fn of(user: &rind::api::Identity) -> Query<Loan> {
Query::new().filter(Loan::borrower_id().eq(user.id))
}
}
}
Two new things:
default = "CURRENT_DATE"is a default given by the database, written in SQL.Loan::of(user)is a scope: a plain function that returns a query. It is where a Django developer would write a custom manager method,Loan.objects.of(user). You can test it without HTTP, and use it anywhere.
Domains are ordered: a domain may point to the domains before it, never
after. lending comes after catalog and auth in app(), which is
where the tool put it. Then:
rind make
rind migrate
lending 0001_initial
create lending_loan
key lending_loan.book_id
key lending_loan.borrower_id
The loans resource
rind add resource lending Loan --rule authenticated
Add catalog-models = { path = "../../catalog/catalog-models" } to the
dependencies of crates/lending/lending-api/Cargo.toml, then write the
serializer and the input:
#![allow(unused)]
fn main() {
// crates/lending/lending-api/src/loans/serializers.rs
use catalog_models::Book;
use chrono::NaiveDate;
use lending_models::Loan;
use rind::{Input, Serializer};
/// A loan as the API shows it.
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Loan)]
pub struct LoanOut {
#[field(mandatory)]
pub id: Option<i64>,
#[field(name = "book")]
pub book_id: Option<i64>,
#[field(name = "borrower")]
pub borrower_id: Option<i64>,
pub borrowed_on: Option<NaiveDate>,
pub returned_on: Option<Option<NaiveDate>>,
}
/// What a member writes to borrow a book: only the book. The borrower is
/// who is signed in, and the date is today.
#[derive(Debug, Input)]
#[input(model = Loan)]
pub struct LoanIn {
#[input(name = "book", fk = Book)]
pub book_id: Option<i64>,
}
}
returned_on is an Option<Option<…>>: the outer Option is “was the
field asked for”, the inner one is the SQL NULL.
The input has only book. A member does not choose the borrower: it is
whoever is signed in. That is set by the resource, below.
Modes: which rows each user sees
Alice must see her loans, not Bob’s. In DRF you would write
get_queryset() and filter on request.user. In rind, a rule can give a
mode: a value that decides which rows the request works on, and which
fields it hides.
#![allow(unused)]
fn main() {
// crates/lending/lending-api/src/loans/views.rs
use lending_models::Loan;
use rind::api::resource::{self, Writes};
use rind::api::{ApiError, Ctx, QueryParams};
use rind::prelude::*;
use rind::{Resource, actions};
use super::filters::LoanFilters;
use super::serializers::{LoanIn, LoanOut};
/// What a user sees of the loans.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoanMode {
/// The librarians: every loan.
All,
/// A member: their own loans.
Own,
}
/// Members borrow books and give them back; librarians see every loan.
#[derive(Resource)]
#[resource(
model = Loan,
path = "loans",
out = LoanOut,
filters = LoanFilters,
input = LoanIn,
mode = LoanMode,
hooks,
actions
)]
#[rule(staff, mode = LoanMode::All)]
#[rule(authenticated, actions(list, retrieve, create, give_back), mode = LoanMode::Own)]
#[mode(LoanMode::All, query = Query::new())]
#[mode(LoanMode::Own, query = Loan::of(user), hide(borrower))]
#[ordering(by(id, borrowed_on), default("-borrowed_on"))]
pub struct LoanResource;
}
Read the rules and the modes together:
- the staff may do everything, in mode
All: every loan; - a signed-in user may list, retrieve, create and
give_back(an action we write in part 6), in modeOwn: the rows ofLoan::of(user), and the fieldborroweris hidden, since it is always themselves.
There is no delete in #[resource], so nobody deletes a loan.
Everything happens inside the mode’s rows: the list, the count, the
filters, and each object. A loan that is not yours does not exist for
you: GET /loans/3 answers 404, not 403, so that nobody learns which
ids exist.
A hook: completing a write
hooks in #[resource] says that the resource implements Writes: code
that runs inside the write’s transaction. It is where Django’s
perform_create, or an overridden save(), goes. Ours checks that the
book is on the shelf, and sets the borrower:
#![allow(unused)]
fn main() {
impl Writes for LoanResource {
/// A book can only be borrowed when it is on the shelf. A new loan is
/// the signed-in user's.
async fn creating(
ctx: &Ctx,
input: &LoanIn,
insert: Insert<Loan>,
) -> Result<Insert<Loan>, ApiError> {
let user = ctx.user.as_ref().ok_or(ApiError::Unauthorized)?;
let out = Query::<Loan>::new()
.filter(Loan::book_id().eq(input.book_id.unwrap_or_default()))
.filter(Loan::returned_on().is_null());
if ctx.db.count(&out).await? > 0 {
return Err(ApiError::Validation(
[("book".to_owned(), vec!["This book is already lent.".to_owned()])].into(),
));
}
Ok(insert.value(Loan::borrower_id(), user.id))
}
}
}
ctxis the context of the request:ctx.useris the identity,ctx.dbthe database (here, the write’s transaction).creatingreceives the input, already validated, and theINSERTthat rind is about to run. It returns that insert, possibly completed.ApiError::Validationanswers a 400 with messages per field, like a DRFValidationError({"book": [...]}).
The give_back action is named in a rule, so the code does not compile
until it exists. Add an empty block for now, and fill it in part 6:
#![allow(unused)]
fn main() {
#[actions]
impl LoanResource {}
}
Coming from Django: there are no signals. Code that must run when a loan is created is in the hook, where you can see it, or in a function the hook calls.
Trying it
curl -X POST -H "Authorization: Bearer $ALICE" -H 'Content-Type: application/json' \
-d '{"book": 1}' localhost:8080/loans
{"id":1,"book":1,"borrowed_on":"2026-11-27","returned_on":null}
borrower is not there: the mode hides it. Alice borrows book 3 too.
Then Bob tries to borrow book 1:
curl -X POST -H "Authorization: Bearer $BOB" -H 'Content-Type: application/json' \
-d '{"book": 1}' localhost:8080/loans
{"book":["This book is already lent."]}
Bob borrows book 2 instead. Now compare the lists. Alice’s:
curl -H "Authorization: Bearer $ALICE" localhost:8080/loans
{
"parameters": {…},
"nav": {"size": 100, "page": 1, "next": null, "prev": null, "count": 2, "pages": 1},
"results": [
{"id": 1, "book": 1, "borrowed_on": "2026-11-27", "returned_on": null},
{"id": 2, "book": 3, "borrowed_on": "2026-11-27", "returned_on": null}
]
}
Bob’s, as a librarian, has every loan, with their borrowers:
{
"parameters": {…},
"nav": {"size": 100, "page": 1, "next": null, "prev": null, "count": 3, "pages": 1},
"results": [
{"id": 1, "book": 1, "borrower": 1, "borrowed_on": "2026-11-27", "returned_on": null},
{"id": 2, "book": 3, "borrower": 1, "borrowed_on": "2026-11-27", "returned_on": null},
{"id": 3, "book": 2, "borrower": 2, "borrowed_on": "2026-11-27", "returned_on": null}
]
}
And Bob’s loan, seen by Alice:
curl -H "Authorization: Bearer $ALICE" localhost:8080/loans/3
{"detail":"Not found."}
Next: Part 6: Actions and tests.
Part 6: Actions and tests
An action: giving a book back
Not everything is a create, an update or a delete. Giving a book back is
an operation of its own, on one loan: POST /loans/{id}/give_back. In
DRF it is a method decorated with @action(detail=True, methods=["post"]). In rind it is a method in an #[actions] block:
#![allow(unused)]
fn main() {
// crates/lending/lending-api/src/loans/views.rs
#[actions]
impl LoanResource {
/// Gives the book back: the loan is closed today.
#[action(POST)]
pub async fn give_back(ctx: &Ctx, mode: LoanMode, loan: Loan) -> Result<LoanOut, ApiError> {
if loan.returned_on.is_some() {
return Err(ApiError::BadRequest("This book was already given back.".into()));
}
let today = chrono::Utc::now().date_naive();
ctx.db
.execute(
&Update::<Loan>::new()
.set(Loan::returned_on(), Some(today))
.filter(Loan::id().eq(loan.id)),
)
.await?;
let loan = Loan { returned_on: Some(today), ..loan };
resource::serialize_one::<LoanResource>(ctx, mode, loan, &QueryParams::default()).await
}
}
}
The action asks for what it needs by the types of its parameters:
ctx: &Ctx, the request’s context;mode: LoanMode, the mode the rule gave;loan: Loan, the object of the URL. rind reads it inside the mode: when Alice asks for Bob’s loan, the action does not even run, and the answer is a 404.
It can also take query parameters (#[query] name: T) and a JSON body
(#[body] body: T); see Actions.
Its answer is anything that serializes. Here we answer the loan as a
read would, with serialize_one, so that the mode hides the borrower as
usual.
The action is allowed by its name in the rules. give_back is in the
members’ rule; the staff’s rule lists no actions, so it allows all of
them.
curl -X POST -H "Authorization: Bearer $ALICE" localhost:8080/loans/1/give_back
{"book":1,"borrowed_on":"2026-11-27","id":1,"returned_on":"2026-11-27"}
curl -X POST -H "Authorization: Bearer $ALICE" localhost:8080/loans/1/give_back
{"detail":"This book was already given back."}
And a member cannot change a loan, since no rule gives them update or
partial_update:
curl -X PATCH -H "Authorization: Bearer $ALICE" -H 'Content-Type: application/json' \
-d '{"book": 2}' localhost:8080/loans/2
{"detail":"You do not have permission to perform this action."}
rind routes now shows the action:
lending
/loans GET POST
/loans/{id} GET PATCH PUT
/loans/{id}/give_back POST
Where should the work go? Our action is short, so its work is in the action itself. In a larger application, the work goes in a function of an
opscrate of the domain (lending-ops), which knows nothing of HTTP, and the action only calls it. The function can then be tested alone, and called from a command or a job. See Organising an application.
Testing
rind new wrote a first test, app/tests/schema.rs, which runs rind check inside cargo test. Let’s add one that tells the story of this
tutorial over HTTP.
rind gives each test a PostgreSQL schema of its own, created and
migrated by rind::testing::fresh_schema. The tests can run in
parallel, and each starts from empty tables.
To send requests, we build the application’s router and call it
directly, without a network, with tower’s oneshot. Add the test
dependencies to app/Cargo.toml:
[dev-dependencies]
axum = "0.8"
http-body-util = "0.1"
serde_json.workspace = true
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tower = { version = "0.5", features = ["util"] }
And the test:
#![allow(unused)]
fn main() {
// app/tests/api.rs
use axum::body::Body;
use axum::http::Request;
use http_body_util::BodyExt;
use rind::prelude::*;
use serde_json::{Value, json};
use tower::ServiceExt;
/// Sends one request to the application, and reads its JSON answer.
async fn call(db: &Db, method: &str, uri: &str, token: Option<&str>, body: Value) -> (u16, Value) {
let app = app::app();
let mut request = Request::builder()
.method(method)
.uri(uri)
.header("Content-Type", "application/json");
if let Some(token) = token {
request = request.header("Authorization", format!("Bearer {token}"));
}
let response = app
.router(app.state(db.clone()))
.oneshot(request.body(Body::from(body.to_string())).unwrap())
.await
.unwrap();
let status = response.status().as_u16();
let bytes = response.into_body().collect().await.unwrap().to_bytes();
(status, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
}
#[tokio::test]
async fn a_member_borrows_a_book_and_gives_it_back() {
let Some(db) = rind::testing::fresh_schema(&app::app(), "test_loans").await else {
return;
};
// An author, a book and a member, written straight into the database.
db.batch_execute(
"INSERT INTO catalog_author (id, name) VALUES (1, 'Frank Herbert');
INSERT INTO catalog_book (id, title, year, author_id) VALUES (1, 'Dune', 1965, 1);
INSERT INTO auth_user (id, username) VALUES (1, 'alice');",
)
.await
.unwrap();
rind_auth::set_password::<rind_auth::models::User>(&db, 1, "wonderland1", 1000)
.await
.unwrap();
// Anonymous users cannot see the loans.
let (status, _) = call(&db, "GET", "/loans", None, Value::Null).await;
assert_eq!(status, 401);
// Alice signs in, borrows the book, then gives it back.
let (status, tokens) = call(&db, "POST", "/token", None,
json!({"username": "alice", "password": "wonderland1"})).await;
assert_eq!(status, 200);
let token = tokens["access"].as_str().unwrap();
let (status, loan) = call(&db, "POST", "/loans", Some(token), json!({"book": 1})).await;
assert_eq!(status, 201, "{loan}");
assert_eq!(loan["returned_on"], Value::Null);
let uri = format!("/loans/{}/give_back", loan["id"]);
let (status, loan) = call(&db, "POST", &uri, Some(token), Value::Null).await;
assert_eq!(status, 200, "{loan}");
assert!(loan["returned_on"].is_string());
}
}
A few remarks:
fresh_schemaanswersNonewhenRIND_TEST_DATABASE_URLis not set, and the test returns early: it is skipped, and passes.- The password is hashed with 1,000 iterations instead of more than a million: the test does not need a strong hash, and it is much faster.
callis the small helper that DRF gives you asAPIClient. Write it once in your project, in atests/common/mod.rs, and reuse it.
cargo test does not read .env, and our app() needs
RIND_JWT_SECRET. Export the file’s variables first:
set -a; . ./.env; set +a
cargo test -p app
running 1 test
.
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out
Watch out: without
RIND_TEST_DATABASE_URL, the tests that need a database are skipped and pass. Your continuous integration must set it.
What you have built
In six parts, you have:
- a project of two domains, cut into crates;
- three models, and their migrations as plain SQL;
- three resources, with serializers, inputs, nested objects and counts;
- filters, a search without accents, an ordering and pages;
- users who sign in with tokens, rules, and a permission mode;
- a hook that checks a write, an action, and a test over HTTP.
Where to go next
- The topic guides take each subject in depth: every column type, every query, every option of a serializer.
- The railway, the sample application of the repository, uses nearly every feature of rind. Its code is the best reference after this book.
- rind for Django developers maps Django’s names to rind’s, when you look for “the rind way” of something you know.
- Plugins add health checks, metrics, a cache, mail, background jobs, files and images.
Starting a project
In Django, django-admin startproject writes a project and
manage.py startapp adds an app to it. rind has one tool for both jobs:
the rind command. It writes a new project that builds, passes its
checks and serves an (empty) API. Then it grows the project one piece at
a time: a domain, a model, a resource.
This chapter describes the project commands of the tool: rind new,
rind add and rind doctor. For a guided first project, follow the
tutorial. To start from a database that already
exists (as Django’s inspectdb does), read Starting from a
database.
Installing the tool
You install the tool once, from a checkout of rind:
cargo install --path crates/rind-cli # or: make install-cli
This installs two programs: rind, and cargo-rind. The second one lets
you type cargo rind … instead of rind …; both do the same thing.
Creating a project
rind new library --domain catalog
This creates the folder library/. The name of the folder is the name of
the project. --domain catalog also creates a first domain, called
catalog. A domain is a part of the application about one subject, a bit
like a Django app; it is made of several crates, one per layer.
Organising an application explains why. You can repeat
--domain to create several domains at once, or leave it out and add
them later.
The tool writes these files:
library/
Cargo.toml the workspace
docker-compose.yml a PostgreSQL for development
.env, .env.example DATABASE_URL, BIND, the test database
.gitignore
README.md
app/
Cargo.toml
src/lib.rs app(): the application, described once
src/main.rs one line: rind's commands
tests/schema.rs one test: what `rind check` checks, in `cargo test`
crates/
catalog/
catalog-models/ the models: schema(), migrations(), migrations/embedded.rs
catalog-api/ the resources: api()
The workspace’s Cargo.toml lists its members with a glob,
["app", "crates/*/*-*"], so a new crate needs no edit there. It also
says where rind is (see Where the project finds rind).
The application crate, app/, is the equivalent of Django’s
settings.py and urls.py together. Its src/lib.rs has one function,
app(), that puts the domains together:
#![allow(unused)]
fn main() {
// app/src/lib.rs
pub fn app() -> rind::Application {
rind::Application::new("Library", env!("CARGO_PKG_VERSION"))
.models(catalog_models::migrations())
.api(catalog_api::api())
}
}
Its src/main.rs is one line. It hands the application to rind’s command
line, which gives you make, migrate, serve and the other commands
(see The command line):
// app/src/main.rs
fn main() -> std::process::ExitCode {
rind::cli::main(app::app())
}
The title of the application ("Library") comes from the folder’s name.
It is the title of the OpenAPI document; --title sets another one.
Running the new project
The project is ready to run:
cd library
docker compose up -d # starts PostgreSQL
rind check # the models and their migrations agree
rind migrate # creates the tables
rind serve # http://127.0.0.1:8080
docker-compose.yml starts a PostgreSQL 17 on port 5432, with a user, a
password and a database named after the project. Its data is kept in
memory: it is lost when the container stops. If a PostgreSQL already
runs on port 5432 on your machine, change the port in
docker-compose.yml and in .env.
.env holds the settings for development:
DATABASE_URL=postgres://library:library@127.0.0.1:5432/library
BIND=127.0.0.1:8080
RIND_TEST_DATABASE_URL=postgres://library:library@127.0.0.1:5432/library
The rind tool reads this file and gives its variables to the
application when it runs a command. A variable that is already set in your
shell wins over the file. .env is in .gitignore; .env.example is the
copy you commit.
Coming from Django: there is no
settings.py. What Django reads from its settings, rind reads fromapp()(the code) and from environment variables (DATABASE_URL,BIND, and the variables of each plugin).
How the tool finds the project
You can run rind from any folder inside the project. The tool looks for
a Cargo.toml with a [workspace.metadata.rind] table, in the current
folder and then in each folder above it:
[workspace.metadata.rind]
app = "app" # the package of the application
crates = "crates" # where the domains are: crates/<domain>/<domain>-<layer>
app is required. crates is "crates" when it is left out. A project
laid out in another way only has to say so here: rind’s own repository
says app = "sample" and crates = "sample/crates" (see The railway,
a sample application).
Adding a domain
rind add domain loans
This writes the crates of a new domain, loans-models and loans-api,
and adds them to the application: one dependency per crate in
app/Cargo.toml, and one line per crate in app():
#![allow(unused)]
fn main() {
pub fn app() -> rind::Application {
rind::Application::new("Library", env!("CARGO_PKG_VERSION"))
.models(catalog_models::migrations())
.models(loans_models::migrations())
.api(catalog_api::api())
.api(loans_api::api())
}
}
A domain gets the models and api layers by default. --layers chooses
others, among models, shared, ops and api:
rind add domain accounts --layers models,ops
The models layer is always there, even when you do not name it. Only
the models and api crates have a line in app(): the other layers are
used by the crates above them.
A new domain’s .models(…) line goes after the last one. The order of
these lines matters: a domain’s models may point only to the models of
the domains before it (Domains, in an order).
So add the domains in that order.
A domain’s name is made of lowercase letters, digits and -, and starts
with a letter. rind is refused, because its crates would have the names
of rind’s own crates (rind-api).
Adding a layer to a domain
rind add layer catalog shared
This adds a layer that the domain did not have yet. The new crate depends
on the layers of its domain below it (here, catalog-models), and the
layers above it now depend on it (here, catalog-api). The tool edits
those manifests for you. A dependency on another domain’s crate is yours
to add, in the manifest.
Adding a model
rind add model catalog Book title:String year:i32
This adds a struct to catalog-models/src/lib.rs, just before
fn schema(), and adds the struct to the list that schema() returns:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-models/src/lib.rs
/// A book.
#[derive(Debug, Clone, Model)]
#[model(table = "catalog_book")]
pub struct Book {
pub id: i64,
pub title: String,
pub year: i32,
// rind: syntax reminder, delete when done ----------------------------
// #[column(max_length = 100, unique)] pub code: String,
// #[column(default = "'open'", index)] pub status: String,
// #[fk(Other, on_delete = cascade)] pub other_id: i64,
// #[fk(table = "other_table", on_delete = set_null)] a key to a domain above
// pub other_id: Option<i64>,
// on the struct: #[index(on(a, b))] #[unique(on(a, b))] #[check(name = "…", sql = "…")]
// ---------------------------------------------------------------------
}
/// The tables of this domain.
pub fn schema() -> Vec<rind::schema::Table> {
vec![
rind::schema::Table::of::<Book>(),
]
}
}
The table is named <domain>_<model> in snake case, as Django names
<app>_<model>. Every model gets an id: i64 key.
Each field is given as name:RustType, and nothing more. Lengths, keys,
defaults and indexes are written in Rust, in the struct, with the
attributes of Models. The block of comments recalls their
syntax; delete it once you have read it, or pass --bare to leave it out.
When a type names chrono:: (published:chrono::NaiveDate), the tool
also adds chrono to the crate’s dependencies.
add model writes no migration. You first edit the struct until it is
what you want, and then rind make writes the migration, as Django’s
makemigrations does:
rind add model catalog Book title:String year:i32
# edit the struct: lengths, keys, indexes
rind make
rind migrate
Adding a resource
A resource is a model served over HTTP, with its list, its detail and
its writes: what Django REST framework calls a ModelViewSet, with its
serializer and its filter set. See Resources.
rind add resource catalog Book
This writes a folder for the resource in catalog-api/src/books/:
| File | Holds |
|---|---|
serializers.rs | BookOut, what is sent: every column of the model; BookIn, what can be written: every column but id |
filters.rs | BookFilters, an empty filter set |
views.rs | BookResource: the model, its path, its serializers, its filters, and who may use it |
mod.rs | the three modules, and their types re-exported |
Then it adds pub mod books; and .resource::<books::BookResource>() to
catalog-api/src/lib.rs. The resource is served at /books: the name of
the model in snake case, in the plural. --path gives another path.
The tool finds the model in whichever domain’s models crate has it. The
model can be in another domain: the api crate then gets a dependency on
that domain’s models crate, and on the crates that the model’s field
types come from (chrono, for instance). When two domains have a model
of that name, say which one with --models DOMAIN.
Who may use the new resource
The resource that the tool writes is for the staff only:
#![allow(unused)]
fn main() {
// crates/catalog/catalog-api/src/books/views.rs
/// The staff read and write the books.
#[derive(Resource)]
#[resource(
model = Book,
path = "books",
out = BookOut,
filters = BookFilters,
input = BookIn,
delete
)]
#[rule(staff)]
pub struct BookResource;
}
This is on purpose. What a generator leaves open by default is what gets
deployed open, so you have to ask for it: --rule anyone,
--rule authenticated, --rule staff (the default) or
--rule superuser. You can also change the #[rule(..)] line later (see
Permissions).
A new application signs nobody in yet, so nobody is staff, and nobody can reach the resource. The tool warns you:
books/views.rs: #[rule(staff)], and this application signs nobody in.
Nobody can reach /books until it does (the book, "Authentication"),
or until the rule is another: --rule anyone
The warning goes away once app() has an .auth(…) line (see
Authentication).
How the tool edits your files
The tool only adds things. It does not rename and it does not remove: a
rename is a job for your editor, and rind make then asks you whether a
table or a column was renamed.
New files are written from templates compiled into the tool. A file that already exists is never overwritten: the command stops with an error instead.
Manifests (Cargo.toml) are edited with their comments and their order
kept.
Rust files are edited only in the lists that the tool itself wrote:
- the chain of calls in
app()(.models(…),.api(…)); - the
vec![…]thatschema()returns, and the place beforefn schema()where a new model goes; - the chain of calls in
api()(.resource::<…>()), and thepub modlines of the api crate.
A line is inserted; nothing else in the file is reformatted. When a list
is no longer as the tool wrote it (you rewrote it by hand, for instance
with a call on the same line as Application::new(…)), the tool changes nothing in that file. It
prints the line to add, and where, and you add it yourself:
NOT edited app/src/lib.rs: `.models(…)` is not on a line of its own, as the tool writes it.
Add it by hand: `.models(loans_models::migrations())` in the chain of `app()`
Checking how the crates depend on each other
Organising an application gives rules about which crate may
depend on which. The compiler enforces some of them (crates cannot depend
on each other in a circle), but not all. rind doctor checks the others:
rind doctor
loans-api depends on catalog-api: an api crate never depends on another (…); what both need goes in a shared crate
1 problems.
It reads the project with cargo metadata, without building anything,
so it is fast. It reports:
- an api crate that depends on another api crate;
- a crate that depends on a crate of a higher layer: a
modelscrate on ashared,opsorapicrate, asharedcrate on anopscrate, and so on; - a models crate that
app()does not list (its tables would never be migrated), and an api crate thatapp()does not mount; - a models crate without its
migrations/embedded.rs(it does not compile without it); - a
rindtool and a rind library of different versions.
It prints Nothing to report. and succeeds when all is well, and fails
otherwise, so you can run it in CI. When app() is not a chain the tool
can read, it says so and does not check what app() mounts.
Where the project finds rind
While rind is not published on crates.io, a new project depends on rind
by path. By default this is the checkout that the tool was built from:
the tool remembers it. If that checkout has moved, rind new stops and
asks for --rind PATH, the folder of rind’s workspace. --rind-git URL
depends on rind by git instead.
Reference
rind new PATH
| Option | Meaning |
|---|---|
--web axum or --web actix | The web framework. axum by default. |
--domain NAME | A first domain, with its models and api crates. Can be repeated. |
--serve rind or --serve own | Who serves: rind’s serve (the default), or a server of the application’s own, written in app/src/serve.rs (see The command line). |
--rind PATH | The checkout of rind to depend on. By default, the one the tool was built from. |
--rind-git URL | Depend on rind by git instead. |
--title TITLE | The title of the application, in its OpenAPI document. By default, the folder’s name. |
The folder must not exist, or be empty. At the end, the tool prints the next commands to run.
rind add
| Command | Options | Writes | Edits |
|---|---|---|---|
add domain NAME | --layers models,shared,ops,api (default models,api) | the crates of the domain; an empty migrations/embedded.rs | app/Cargo.toml, and one line per models or api crate in app() |
add layer DOMAIN LAYER | the crate, depending on the layers below it | the manifests of the layers above it; app() for a models or api layer | |
add model DOMAIN NAME [field:Type]… | --bare | the struct, with id and the fields given | the vec! of schema(); use rind::prelude::*; if it is missing; chrono in the manifest when a type needs it |
add resource DOMAIN MODEL | --rule anyone|authenticated|staff|superuser (default staff), --path PATH, --models DOMAIN, --bare | the folder of the resource: mod.rs, serializers.rs, filters.rs, views.rs | pub mod and the chain of api(); the api crate’s manifest when the model is another domain’s, or its fields need a crate |
A model’s name is in CamelCase, as a Rust type (Book, RailCar). A
field cannot be called id: the tool writes that one.
rind doctor
Takes no option. Exits with a failure when it finds a problem.
Other commands of the tool
| Command | Does |
|---|---|
rind inspect | Writes models from an existing database (Starting from a database). |
rind help-app | The application’s list of commands (The command line). |
rind --help | The tool’s own list of commands. |
| any other command | Run by the application: rind migrate is cargo run -q -p app -- migrate. |
The command line
A Django project has manage.py: makemigrations, migrate,
runserver, check, and the management commands that apps add. In rind,
the application’s own binary plays that part. Its commands come from
rind, in the library, and you add your own beside them, as Django’s
management commands.
This chapter describes those commands, the Application value they work
on, how to serve it, and how to test it.
The application’s binary
The main of an application is one line. No change of the application
ever has to touch it:
// app/src/main.rs: the whole file
fn main() -> std::process::ExitCode {
rind::cli::main(app::app())
}
rind::cli comes with the cli feature of rind, which is on by default.
You can run the commands in two ways. With cargo, from the workspace:
cargo run -p app -- migrate
Or with the rind tool (Starting a project), from any
folder of the project:
rind make
rind check
rind migrate
rind openapi --out openapi.json
The tool finds the application’s package, runs
cargo run -q -p <app> -- <command>, and gives it the variables of the
project’s .env file (a variable already set in your shell wins). Every
command that the tool does not know itself goes to the application in
this way.
The two lists of commands are separate. rind --help lists the tool’s
own commands (new, add, doctor, inspect). rind help-app lists
the application’s: the same list as cargo run -p app -- help.
Coming from Django:
manage.pyis a script that loads the settings. Here the commands are compiled into your application’s binary, so they always see the same models and resources as the server.
The commands rind gives you
Here are the commands, grouped by what they work on, with their closest Django equivalent. The Reference has the complete list of options.
Migrations
| rind | Django | Does |
|---|---|---|
make | makemigrations | Writes the migrations of what changed in the models. |
check | makemigrations --check | Fails if the models do not hold together, or have changes without a migration. |
status | showmigrations | Lists the migrations the database has applied, and those it has not. |
migrate | migrate | Applies the migrations the database does not have. |
make asks you, as Django does, when a change looks like a rename (“Was
catalog_book.name renamed to catalog_book.title?”). --rename answers
in advance: --rename old_table=new_table, or
--rename table.old_column=new_column. --name gives the new migration a
name.
migrate --fake records the migrations as applied without running them,
as Django’s migrate --fake. migrate --only a,b applies the migrations
of the named domains only. Every domain is still put in order, so a
domain’s migrations still come after those it depends on.
Migrations explains how they are written, stored and applied.
The schema and the database
These commands compare the models with a real database. They are most useful when an application takes over a database that already exists (Starting from a database).
schemaprints the SQL (DDL) that creates the tables of the models, as Django’ssqlmigratedoes for one migration.schema diffprints a draft of the SQL that would make the database match the models. It is a draft to read, not a migration.dbcheckcompares the models with the database: the tables, the columns and their types, and the foreign tables and their keys. With--rules FILE, it also compares each key’son_deletewith the rules of the old Django application (Answering as Django did).constraintslists the constraints and indexes that the models and the database do not have alike.--sqlprints the statements that give the database the models’ names.verifyapplies every migration to a new, empty schema, compares the result with the models, and drops the schema. With--against URL [--schema S], it also compares the result with the database the models were written from.
The API
openapiprints the OpenAPI document;--out FILEwrites it to a file.routeslists the routes, by domain, asshow_urlsof django-extensions does.serveruns the server (Serving), asrunserverdoes.helpprints the list of commands, with those of the plugins and of the application.
Which database a command uses
A command that needs a database reads its address from DATABASE_URL, or
from --database URL when you give it:
rind migrate --database postgres://library:library@127.0.0.1:5432/library
Commands that use no database (make, check, schema, openapi,
routes) refuse --database.
The first versions of the commands took the address bare
(migrate postgres://…). This is still accepted for a while.
What the commands print, and logging
The commands write rind’s events to the standard error, through
tracing. RUST_LOG says what is written (info by default;
RUST_LOG=rind::sql=debug adds every SQL statement and its duration).
RIND_LOG=json writes one JSON object per line, for a log collector. See
Logging.
The application, described once
Every command works on one value: the Application that app() returns.
#![allow(unused)]
fn main() {
// sample/src/lib.rs (shortened)
pub fn app() -> rind::Application {
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
.models(network_models::migrations())
.models(accounts_models::migrations())
// …
.api(network_api::api())
.api(fleet_api::api())
// …
.auth(accounts_ops::TokenAuth)
}
}
Each domain gives its parts. A models crate gives its tables and its
migrations (migrations()), and an api crate gives its resources, each
named once (api()):
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/lib.rs (shortened)
pub fn api() -> rind::api::Api {
rind::api::Api::new("network")
.resource::<stations::StationResource>()
.resource::<lines::LineResource>()
}
}
The application adds how users sign in (.auth(…), see
Authentication) and its plugins (.with(…), see
Plugins).
Everything else follows from this one value. What a Django project lists
in INSTALLED_APPS, urls.py and its settings, rind reads from it:
| What | From the value |
|---|---|
| every table | app.schema() |
| every migration | app.migrations() |
| the OpenAPI document | app.openapi() |
| the state the resources share | app.state(db) |
| the routes | app.router(state) (axum), app.configure(cfg) (actix-web) |
An api crate depends on no web framework, and needs none of rind’s web features. Only the application chooses axum or actix-web, so the same domain crates serve on both.
Routes that are not resources
Not every route is a resource: a health check, a webhook, static files.
Application never stands in the way of these. A domain adds its own
routes beside its resources:
#![allow(unused)]
fn main() {
// a domain's api crate (fragment)
pub fn api() -> rind::api::Api {
rind::api::Api::new("booking")
.resource::<reservations::ReservationResource>()
.axum(|| axum::Router::new().route("/payments/webhook", post(webhook)))
}
}
The function given to .axum(..) returns an axum::Router<AppState>,
so a handler can read the application’s state. For actix-web, .actix(..)
takes a function that adds services to a ServiceConfig. A route that
belongs to no domain goes on the application itself, with the same
.axum(..) and .actix(..).
.axum and .actix exist only with rind’s feature of the same name. So
only the crate that uses them depends on the web framework.
What the application gives is ordinary, so you can combine it with
anything else. app.router(state) is an ordinary axum::Router, and
app.routes() is the same router before it is given its state.
app.configure is an ordinary actix-web configuration. You can merge,
nest and wrap them with layers like any other.
These routes are not in the OpenAPI document by themselves, because rind
does not know what they take and return. .describe(..), on an Api or
on the Application, adds them:
#![allow(unused)]
fn main() {
.describe(|document| document.path("/payments/webhook", "post", json!({…})))
}
The application’s own commands
These are Django’s management commands. You give each one a name, a line of help and an async function:
// app/src/main.rs
fn main() -> std::process::ExitCode {
rind::cli::Cli::new(app::app())
.command("import-stations", "loads stations from a CSV file", import_stations)
.main()
}
async fn import_stations(
app: &rind::Application,
args: &[String],
) -> Result<(), Box<dyn std::error::Error>> {
// …
}
The function is given the application and the arguments that follow the
command’s name, unparsed. It is not given a database: connect with
rind::db::Db::connect(&std::env::var("DATABASE_URL")?) when it needs
one. An error it returns is printed, and the command exits with a
failure.
The command is listed by help, and runs like the others:
rind import-stations stations.csv
When a command of yours has the name of one of rind’s, yours runs.
Plugins add commands too: cache-clear, usage-prune,
storage-orphans, mail-prune, auth-clean, and the jobs-… commands
of Jobs. A plugin’s command is given the application and its
database (--database, or DATABASE_URL).
Serving
serve reads DATABASE_URL and BIND (127.0.0.1:8080 by default; or
--bind ADDR), connects to the database, and serves every route of the
application with its CORS. It serves on the framework the
application is built with, and on actix-web when it is built with both.
rind’s server is enough for a simple application, and for the first weeks of a larger one. When you need more (other middleware, several listeners, a shutdown that waits for the requests in progress), give the command a server of your own. The command, its options and its place in the list stay rind’s:
// app/src/main.rs (fragment)
fn main() -> std::process::ExitCode {
rind::cli::Cli::new(app::app()).serve(serve).main()
}
async fn serve(app: &rind::Application, settings: rind::cli::Serve) -> std::io::Result<()> {
let router = app
.router(app.state(settings.db))
.layer(TraceLayer::new_for_http());
axum::serve(TcpListener::bind(&settings.bind).await?, router)
.with_graceful_shutdown(signal())
.await
}
settings holds the connected database (db), the address to listen on
(bind) and the database’s address as it was given (database_url).
rind new --serve own starts the project with this form, in
app/src/serve.rs. With axum, app.router(..) already has the CORS
layer. With actix-web, CORS is a middleware of the App, so your server
wraps it itself:
#![allow(unused)]
fn main() {
// app/src/serve.rs, as `rind new --web actix --serve own` writes it (fragment)
App::new()
.wrap(app.actix_cors())
.app_data(web::Data::new(state.clone()))
.configure(move |cfg| app.configure(cfg))
}
Going further: the client’s address
rind’s axum server gives each request the client’s address
(into_make_service_with_connect_info::<SocketAddr>()), which hooks such
as the usage log read. A server of your own on axum should do
the same if it uses them.
The tests
The test that rind new writes runs, in cargo test, what rind check
checks:
#![allow(unused)]
fn main() {
// app/tests/schema.rs
#[test]
fn the_application_holds_together() {
rind::testing::check(&app::app());
}
}
It fails when the models do not hold together across domains, when a
change has no migration, or when a folder’s index of migrations is stale.
Its message says to run rind make.
A test that needs PostgreSQL gets a schema of its own, with the application’s migrations applied:
#![allow(unused)]
fn main() {
#[tokio::test]
async fn stations_are_listed() {
let Some(db) = rind::testing::fresh_schema(&app::app(), "stations_listed").await else {
return; // RIND_TEST_DATABASE_URL is not set: the test is skipped
};
// …
}
}
fresh_schema returns None when RIND_TEST_DATABASE_URL is not set,
so the tests that need a database are skipped on a machine without one.
The schema is dropped first if it is already there, so each test starts
from nothing. Give each test its own schema name, as tests run in
parallel.
rind::testing::empty_schema(name) does the same without the
migrations.
Coming from Django: Django creates one test database and wraps each test in a transaction. rind gives each test a PostgreSQL schema of its own instead, so tests can commit and run in parallel.
Reference
Commands
| Command | Does |
|---|---|
make [--name N] [--rename OLD=NEW]… | Writes the migrations of what changed in the models. --rename old_table=new_table or table.old_column=new_column; otherwise asked. |
check | Fails if the models do not hold together across domains, have changes without a migration, or if a folder’s index (embedded.rs) is not what its files are. |
status | What the database has applied, and has not. |
migrate [--fake] [--only a,b] | Applies what the database has not. --fake: only records it. --only: these domains only. |
constraints [--sql] | The constraints and indexes that the models and the database do not have alike. --sql: the statements that rename them. |
verify [--against URL [--schema S]] | Applies every migration to an empty schema, compares the result with the models (and with the database at URL: Starting from a database), drops the schema. --schema is public by default. |
schema | The DDL of the models. |
schema diff | A draft of what would make the database match the models. |
dbcheck [--rules FILE] | Compares the models with the database: tables, columns, types; the foreign tables and their keys; with --rules FILE, each key’s on_delete with the old application’s rules. |
openapi [--out FILE] | The OpenAPI document. |
routes | The routes, by domain. |
serve [--bind ADDR] | The server, on the framework the application is built with. |
help | The list, with the plugins’ commands and the application’s own. |
Every command that uses a database takes --database URL.
Environment variables
| Variable | Read by |
|---|---|
DATABASE_URL | Every command that uses a database. |
BIND | serve: the address to listen on. 127.0.0.1:8080 by default. |
RUST_LOG, RIND_LOG | What is logged, and how (Logging). |
RIND_TEST_DATABASE_URL | rind::testing: the database of the tests. |
rind::cli
| Item | Is |
|---|---|
rind::cli::main(app) | The command line with rind’s commands only. |
Cli::new(app) | A command line, to add to. |
.command(name, about, f) | A command of the application’s own; f is async fn(&Application, &[String]) -> Result<(), Box<dyn Error>>. |
.serve(f) | What serve runs; f is async fn(&Application, rind::cli::Serve) -> std::io::Result<()>. |
.main() | Runs the command of the process’s arguments. |
rind::cli::Serve | What a server is given: db, bind, database_url. |
Application
| Method | Does |
|---|---|
Application::new(title, version) | The application, with its title and version (for OpenAPI and help). |
.models(domain) | A domain’s tables and migrations: <domain>_models::migrations(). |
.api(api) | A domain’s resources: <domain>_api::api(). |
.auth(authenticator) | How users sign in (Authentication). |
.with(plugin) | A plugin. |
.axum(..), .actix(..) | Routes that belong to no domain. |
.describe(..) | Adds paths to the OpenAPI document. |
.schema(), .migrations(), .openapi() | What the commands read. |
.state(db) | The state the resources share. |
.router(state), .routes() | The routes, for axum. |
.configure(cfg), .actix_cors() | The routes and the CORS middleware, for actix-web. |
Starting from a database
You may start a rind project from a database that already exists: one a
Django application created, or any other PostgreSQL database. Django has
inspectdb for this; it prints draft models that you then fix by hand.
rind inspect goes further. It writes:
- a models crate per domain (a group of tables, like a Django app);
- a model per table, which keeps every name the database has (tables, columns, constraints, indexes), so that the models describe the database exactly;
- an API over them: a resource per model, open to superusers by default;
- tests that check the models read and write the real rows.
It works in two steps, with a person in between. The first step writes a plan, a TOML file of decisions. You read it and correct it. The second step applies the plan and writes the project.
rind inspect postgres://…/shop > inspect.toml # 1. the plan
$EDITOR inspect.toml # domains, names, tables left out
rind inspect --apply inspect.toml --new shop # 2. the project
rind inspect reads only the catalogue of the database (the description
of its tables), never a row, so a replica will do. Without an address, it
reads DATABASE_URL, or the project’s .env.
Once the project is written, Migrations explains how rind takes over the database.
The plan
The first step writes what it would do, as TOML. The plan holds decisions, not the schema: when you apply it, the tables are read again from the database. A plan looks like this:
# A domain per prefix of the tables' names.
[domains]
catalog = "catalog"
_legacy = "legacy"
# The extensions the tables need, with the domains whose first migration
# creates them.
[extensions]
postgis = ["locations", "structures"]
pg_trgm = ["catalog"]
# Types, functions and configurations the tables need.
[objects]
"normalize_text(text)" = "catalog"
# Every table modelled, in its domain.
[tables]
catalog_family = "Family"
catalog_family_labels = { model = "FamilyLabels", m2m = "Family.labels" }
users_user = { model = "User", domain = "accounts" }
# Left out, with why.
[skip]
spatial_ref_sys = "a table of an extension"
# The API: a resource per model, for superuser, staff, authenticated or
# anyone; `none` writes no API.
[api]
rule = "superuser"
# The models without a resource, with why.
[api.skip]
factlink_fix_missing = "its key is not an integer (date)"
Here is what each part means, and what you may change.
- A domain is the prefix of a table’s name: what comes before its
first
_(a leading_belongs to the prefix, so_legacy_logis in_legacy). In[domains], you can rename a domain, or give two prefixes the same domain. To move a single table to another domain, adddomain = "…"to its entry in[tables]. - A struct is named after the rest of the table’s name, in CamelCase,
cut on
_. A Django table has no word boundaries (articletariftemplatebecomesArticletariftemplate), so rename the structs here. - A link table becomes a model too. A link table has a key, two foreign
keys and the pair unique: what Django makes for a
ManyToManyField.m2m = "Family.labels"declares the many-to-many relationlabelsthrough it, on the model of its first key. Both ends must be modelled in the same domain. Removem2mto keep only the model. - Every table is in the plan, either modelled or skipped. To leave a
table out, move it to
[skip]: Django’s own tables, or a table that another program owns. A foreign key to a skipped table stays in the model, by the table’s name. - An extension or an SQL object can be skipped too, by its name in
[skip]. A project that ports only part of a database should not create what only the other parts use (vector = "only classify uses it"). - A table rind cannot model is skipped, with the reason. It may have a column of a type rind does not know, a key on several columns, or no primary key. The first step then ends with a failure, so that you see it. rind never reads something as what it is not.
Some tables are left out without asking: rind’s own (rind_migrations,
and the tables of rind’s plugins, named rind_…), the tables of an
extension, and the partitions of a partitioned table.
Updating the plan
The database may change while you port it. This command brings the plan up to date with the database as it is now, and keeps every decision you made:
rind inspect postgres://…/shop --update inspect.toml
The file is edited in place: its comments, blank lines and order stay as you wrote them.
-
What appeared goes to
[skip], marked# new. Its reason says what the tool proposes, so that the next--applywrites nothing nobody asked for (a plan may cover only part of a database). To model a new table, move it to[tables]with the proposal from its reason:[skip] orders_ordernotification = "new: proposed as \"Ordernotification\"" # newA new extension or SQL object is added the same way, with the domains proposed for it. A new table that rind cannot model gets its reason, and the update ends with a failure, as the first step does.
-
What is gone is removed from every section, and listed at the end of the file (
# gone from the database: …). -
An extension or an object named in
[skip]is kept for as long as the database has it.
Updating a plan that is already up to date changes nothing.
Applying the plan
--apply reads the plan and the database again. It writes nothing if they
do not agree, and lists every problem at once:
- a table of the database that is neither in
[tables]nor in[skip]; - a table of the plan that the database no longer has;
- a column of a type rind does not know;
- a name that cannot be a crate’s or a type’s;
- two tables with the same struct name in one domain;
- a table that a model of the project already describes, in another domain than the plan says.
With --new FOLDER, the project is created as rind new makes it, and
the models go into it.
Applying again, in a project
Run without --new, inside a project, --apply writes only what the
project does not have yet. So the plan can grow with the port: you move a
table from [skip] to [tables], then apply again.
- A table that a model of the project already describes
(
#[model(table = "…")]) is kept as it is, whatever you changed in it. - A new domain is written whole, as with
--new. - In a domain that exists, the new models get their files, and the
domain’s
lib.rsis edited, not rewritten: themod,pub useandTable::of::<…>()lines ofschema()are added, and the rest is kept. The same goes for the tests that inspect wrote (read.rs,copy.rs,api.rs): the new tables’ lines are added. - With
[api], resources are written for the new tables only. An API crate that exists gets thepub modand.resource::<…>()lines. A table modelled before keeps the API the application gave it, under its own names. - What cannot be placed (a file that is no longer as inspect wrote it) is
printed as
NOT edited, with the line to add by hand.
Then rind make writes the first migration of the new tables.
What a model looks like
A table becomes a model that says everything the database has: its lengths, its unique constraints and its indexes, each under the name the database gives it.
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "logs_processor")]
#[index(name = "logs_processor_name_3e149381_like", sql = "USING btree (name varchar_pattern_ops)")]
pub struct Processor {
pub id: i64,
#[column(max_length = 255, unique = "logs_processor_name_3e149381_uniq")]
pub name: String,
pub last_id: Option<i64>,
pub description: String,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
}
The _like index is the one Django adds on PostgreSQL beside an indexed
text column. rind has no attribute for it, so it is kept as SQL.
A foreign key to a model of the same domain carries a relation
(#[fk(Family, …)]). It also gives the target a relation back, under the
name Django gives it by default: <model>_set
(Group::usergrouplink_set()), or <model>_<key>_set when the table has
several keys to the same target (Location::distance_location_a_set()).
Rename them to the related_name the Django application used. The
relation back is a trait, written beside the key
(GroupUsergrouplinkSet). The domain’s lib.rs re-exports each model’s
module whole (pub use usergrouplink::*;), so use users_models::*
brings the trait into scope.
A foreign key to another domain is written by its table’s name, and
unfollowed: #[fk(table = "users_user", unfollowed, …)]. The domains of
a database point to each other, but their crates cannot depend on each
other in both directions.
A parent_id key to the table itself makes the model a tree
(tree = "parent_id", which gives descendants and ancestors), as the
models of django-tree-queries and django-mptt are.
A model whose fields all have a default derives Default, so that a
test writes a row with only the values it cares about:
Storage { cvva: "AD1".into(), ..Default::default() }.
Once everything is written, inspect runs cargo fmt --all on the project.
The generated code is formatted as the rest is, and a later cargo fmt
changes nothing. Without rustfmt, inspect says so and leaves the files as
written.
Deletion rules and foreign tables
A key’s on_delete comes from the database (ON DELETE CASCADE). But a
Django database says nothing there: every Django key is NO ACTION, and
the rules live in the Python code. The models then need the rules from
that code. You give them with --rules rules.json, a file the old
application writes itself (for Django, with the script of
the Django chapter). With it:
- A new model’s key whose rule the database does not hold gets the
file’s rule:
#[fk(.., on_delete = cascade, in_code, ..)]. The database key stays as it is, and rind’s deletion applies the rule (Models). Django’sSET_DEFAULTandSET(..), which rind does not have, are written as the database says, with a note. - The models kept from an earlier apply get it too: their
#[fk(..)]lines are rewritten, and a key that is already right is left as it is. So do theexternalkeys (to a table no model describes), because their target may be a foreign table, which a cascade reaches.
Every apply also writes the foreign tables: the tables left out
([skip]) that a deletion of the models’ rows reaches. These are the
skipped tables with a key to a modelled table; then, for those whose key
cascades, the skipped tables that point to them, and so on. They go into a
crate of their own, crates/foreign/foreign-tables, as
Table::foreign(..) values. The crate is rewritten whole by every apply,
and given to the application:
#![allow(unused)]
fn main() {
.foreign_tables(foreign_tables::tables())
}
See Tables no model describes for what rind does with them. A table without a primary key of one integer column cannot be walked: inspect says so, and the database refuses a deletion that reaches it.
Afterwards, rind dbcheck --rules rules.json compares every key of the
models and of the foreign tables with the file. A rule copied by hand, or
changed in the old application since, shows up.
The tests inspect writes
The application gets two tests of the models:
app/tests/read.rsreads rows of every table through its model, whenRIND_INSPECT_SOURCEnames the database.app/tests/copy.rsalso needsRIND_INSPECT_REBUILD: a server where it migrates a schema of its own from nothing. It copies rows of every table into it through the models (Insert), reads them back, and compares them. The keys are not checked while it copies (a table’s rows may come before the rows they point to), which needs a superuser on that server.
The API
Over the models, inspect writes an API crate per domain. Each model gets a
resource at /<domain>/<table without its prefix> (/catalog/family),
with the rule of [api], and five actions: list, retrieve, create,
update and delete.
- Its serializer sends every column.
- Its input writes every column the database does not compute itself (a
generated column, or a key the database gives, are left out). A text may
be blank and keeps its spaces (
allow_blank,keep_spaces), because Django keeps both. A column with a default isoptional: it is left out if the client does not send it. - Its filters are empty.
A model whose primary key is not an integer has no resource, because a
resource finds its objects by an integer id. The plan lists it in
[api.skip] with that reason.
Nothing is guessed beyond that. Which fields a client may write, the filters, the search, the relations sent nested, the rules of each action: you write them yourself, resource by resource.
With any rule other than anyone, nobody can reach the resources until
the application signs its users in (.auth(..) in app(), see
Authentication). The plan cannot know how a
database’s users prove who they are.
app/tests/api.rs tests the whole API (with axum). A request without
credentials must be refused. Then, signed in as a superuser by an
authenticator of its own, the test lists the rows of each resource in the
database, creates each row again through the API’s JSON in a schema
migrated from nothing, changes it, deletes it, and checks it is gone. It
needs RIND_INSPECT_SOURCE and RIND_INSPECT_REBUILD, as copy.rs does.
The round trip
When the project is written, each of these checks says that the project is the database:
| What is checked | Command | Expected |
|---|---|---|
| it builds | cargo build, rind doctor | nothing to report |
| the migrations | rind make, rind check | a first migration per domain |
| the models are the database | rind dbcheck, rind constraints (on it) | 0 differences |
| the migrations are the models, and the database | rind verify --database <empty server> --against <the database> | the same tables, names and definitions |
| the models read the rows | RIND_INSPECT_SOURCE=… cargo test -p app --test read | every table read |
| the models write them back | … RIND_INSPECT_REBUILD=… cargo test -p app --test copy | every row read back the same |
| the API | … cargo test -p app --test api | refused without credentials; every row created, changed, deleted |
verify --against migrates an empty schema from nothing and compares it
with the database the models were written from: every column, key,
uniqueness, condition, index, default, type and function, by name and by
definition. The server it migrates needs the extensions the database has.
On the database of a real Django application (261 tables, used by Django and by two other services), this gave 260 models in 26 domains and 37 migrations, with 0 differences at each step. The rows of every table were read, and 33,882 of them written back the same. The 259 resources created, changed and deleted 1,052 rows.
What is left to do then is the takeover
(Migrations): record the
migrations on the database (rind migrate --fake), then change it
through them.
What is not modelled
Views, triggers, partitioned tables, sequences that are not a key’s, and
schemas other than the one inspected (--schema, public by default).
The plan’s header lists what the schema has of them.
rind’s own tables are left out: rind_migrations, and every table named
rind_…, such as rind_usage of the usage log or rind_mail
of the mail. Their plugins model them. A prefix rind is not a
domain, because its crates would be named like rind’s own.
Reference
Options
rind inspect [URL] [--schema S] # the plan, on standard output
rind inspect [URL] --update PLAN # the plan brought up to date, in place
rind inspect [URL] --apply PLAN [--rules FILE] # the models, in the project
rind inspect [URL] --apply PLAN --new FOLDER [--web axum|actix] [--rind PATH | --rind-git URL] [--title T]
| Option | Means |
|---|---|
URL | the database; by default DATABASE_URL, or the project’s .env |
--schema S | the schema to read (public) |
--update PLAN | rewrites the plan from the database, keeping its decisions |
--apply PLAN | writes the models, the API and the tests the plan says |
--new FOLDER | with --apply: a new project in this folder, as rind new makes it |
--web, --rind, --rind-git, --title | with --new: as for rind new |
--rules FILE | with --apply: the deletion rules the database does not hold |
The plan’s sections
| Section | Entry | Means |
|---|---|---|
[domains] | prefix = "domain" | the domain of the tables with this prefix |
[extensions] | name = ["domain", …] | the domains whose first migration creates the extension |
[objects] | "name(args)" = "domain" | the domain that creates this type, function or configuration |
[tables] | table = "Struct" | the table is modelled as Struct, in its prefix’s domain |
[tables] | table = { model = "…", domain = "…", m2m = "Model.relation" } | the same, in another domain, or as a link table |
[skip] | name = "why" | a table, an extension or an object left out |
[api] | rule = "…" | superuser, staff, authenticated, anyone, or none for no API |
[api.skip] | table = "why" | a modelled table without a resource |
The environment of the tests
| Variable | Used by | Is |
|---|---|---|
RIND_INSPECT_SOURCE | read.rs, copy.rs, api.rs | the database the models were written from |
RIND_INSPECT_REBUILD | copy.rs, api.rs | a server where a schema is migrated from nothing; copy.rs needs a superuser there |
Answering as Django did: porting a Django application
This chapter is for one situation: you are replacing an existing Django application with rind, and its clients (a web front end, a mobile app, other services) must not notice the change. They must get the same JSON as before, and the existing database, with its data, must keep working as Django left it.
By default, rind answers in its own way. For example, it writes a date
and time with its time zone, and it lets the database’s foreign keys
decide what a deletion does. A Django application often does otherwise.
The django feature of rind, the module rind::django, gives you what
Django writes and rind does not do by default:
- local times without a zone, as Django writes them with
USE_TZ = False; - geometries as EWKT text, as a plain DRF serializer writes them;
- deletions that follow Django’s
on_deleterules, which live in Python and not in the database.
Other chapters cover the rest of what makes rind answer like Django; they are listed at the end.
To start a port from the Django database itself, see Starting from a database.
Turning it on
The module is behind a feature of the rind crate:
# Cargo.toml
[dependencies]
rind = { version = "…", features = ["django"] }
Local times
With USE_TZ = False, Django writes a timestamp with time zone column
as the naive local time of its TIME_ZONE setting: the time on a clock
in that zone, with no zone written. It adds the microseconds only when
there are some:
{"created": "2023-01-09T13:52:00", "updated": "2024-03-10T18:37:54.144655"}
rind writes a DateTime<Utc> with its zone. To answer as Django did, you
set the zone once, when the application starts, and convert the field in
the serializer with #[field(with = …)]:
#![allow(unused)]
fn main() {
// once, at start: Django's TIME_ZONE
rind::django::time::set_time_zone(rind::django::chrono_tz::Europe::Paris);
}
#![allow(unused)]
fn main() {
// in a serializer
#[field(with = rind::django::time::local)]
pub created: Option<rind::django::time::LocalDateTime>, // "2023-01-09T13:52:00"
}
local is for a column that is not null. For a nullable column, use
local_opt, and the field becomes an
Option<Option<LocalDateTime>>. Until set_time_zone is called, the
zone is UTC. Only the first call counts.
Reading local times sent by clients
Since Django’s clients receive local times, they also send local times
back. In an input, the type LocalDateTimeIn reads them:
#![allow(unused)]
fn main() {
// in an input, for a nullable column
pub datestart: Option<Option<rind::django::time::LocalDateTimeIn>>,
}
- A time without a zone (
2026-01-02T08:00:00, or without the seconds,2026-01-02T08:00) is read as a local time ofTIME_ZONE. - A time with its zone (
…+01:00,…Z) is read as that exact moment. - In both cases, the column’s
DateTime<Utc>is written. - Anything else is refused with DRF’s message:
Datetime has wrong format. Use one of these formats instead: ….
Coming from Django: here rind differs from Django on purpose. Django with
USE_TZ = Falseloses the zone of a time sent with one: DRF turns it into the naive time of UTC, which the database then reads as a local time (an hour or two early in Paris). rind keeps the moment that was sent.
Geometries
A plain DRF serializer (without rest_framework_gis) writes a GeoDjango
geometry as GEOS’s EWKT text: SRID=4326;POINT (2.35 48). To send the
same text, convert the field with one of the rind::django::ewkt
functions:
#![allow(unused)]
fn main() {
// in a serializer, for a nullable point column
#[field(with = rind::django::ewkt::point_ewkt)]
pub position: Option<Option<String>>, // "SRID=4326;POINT (2.35 48)"
}
point_ewktwrites a point.shape_ewktdoes the same for a column of any shape (a polygon, a line…). A shape rind cannot read is sent asnull.parse_pointreads a point that a client sends, as GeoDjango reads it: WKT (POINT(-1.55 47.21)) or EWKT withSRID=4326, longitude first. Another SRID is refused.
Numbers are written as short as they can be read back, as GEOS does. See Geography for rind’s own way of sending geometries.
Deleting as Django did
In a Django database, the foreign keys do nothing (NO ACTION). The
on_delete rules (CASCADE, SET_NULL, PROTECT…) are in the Python
code: Django’s collector finds the related rows and deletes or updates
them itself.
A port says so on each key, with in_code:
#![allow(unused)]
fn main() {
#[fk(Family, on_delete = cascade, in_code)]
pub family_id: i64,
}
The database key stays as it is, and rind’s deletion does what Django’s collector did (Models).
Some Django applications also write a safe_delete view: the deletion is
only tried, and the answer says what it would remove, unless the request
confirms it (?doit=really). rind has it ready made, because a native
application has the same use for it:
Tried first: safe_delete.
The tables that the port does not model still point to the ones it does, and a deletion must cascade into them too. You give them to rind as foreign tables.
Getting the deletion rules from Django
You do not copy the rules by hand: you ask Django for them. A script, run
in the application’s Django shell, writes rules.json. It only reads.
The file has one key per line: [table, column, target table, target column, rule].
RULES_OUT=rules.json python manage.py shell < on_delete_rules.py
The script is tools/django/on_delete_rules.py in rind’s repository:
# on_delete_rules.py: rind's tools/django/on_delete_rules.py
import collections
import json
import os
from django.apps import apps
rules = []
for model in apps.get_models(include_auto_created=True):
for field in model._meta.concrete_fields:
if not (field.is_relation and (field.many_to_one or field.one_to_one)):
continue
rules.append(
[
model._meta.db_table,
field.column,
field.remote_field.model._meta.db_table,
field.target_field.column,
field.remote_field.on_delete.__name__,
]
)
path = os.environ.get("RULES_OUT", "rules.json")
with open(path, "w") as out:
out.write("[\n" + ",\n".join(json.dumps(rule) for rule in sorted(rules)) + "\n]\n")
print(len(rules), "keys:", dict(collections.Counter(rule[4] for rule in rules)), "->", path)
It covers every concrete foreign key and one-to-one key, including those of the many-to-many link tables. Django’s rules become rind’s:
| Django | rind |
|---|---|
CASCADE | cascade |
SET_NULL | set_null |
PROTECT, RESTRICT | restrict (a 409 answer, where Django raises an error) |
DO_NOTHING | no_action (nothing is done) |
SET_DEFAULT, SET(..) | no equivalent |
Keep rules.json in the port’s repository, and run the script again when
the Django models change. Two commands use it:
rind inspect --apply plan.toml --rules rules.jsonwrites the rules on the models’ keys and on the foreign tables (Starting from a database).rind dbcheck --rules rules.jsonsays which keys of the application have another rule than the file’s.
Coming from Django: the
pre_deleteandpost_deletesignals are not sent for the rows that a deletion removes with it. Where they mattered, the port must do what they did by itself.
The rest
Other parts of rind also answer as Django does, and are explained in their own chapters:
- Case-insensitive lookups and searches are written as Django writes
them on PostgreSQL (
UPPER(…) LIKE UPPER(…)), not withILIKE: Filters. - The ids of a many-to-many field, as DRF’s
PrimaryKeyRelatedField(many=True)sends them:#[m2m_ids(hop = …)], Serializers. - Django’s
on_deleterules, applied by rind rather than by the database’s keys:#[fk(.., in_code)], Models. - The tokens the Django application already gave its users: rind-auth’s
verify_only, Signing in.
The railway, a sample application
rind’s repository has a sample application in sample/: a railway. It
is small, but it is cut and written as a real application is, and most
examples of this book come from it. It is also where rind itself is
tested on PostgreSQL.
The railway has stations in regions, lines, trains made of wagons, drivers, journeys that stop at stations, passengers, goods, and the reservations of both on the journeys. This chapter shows how it was started, how to run it, what it serves, and what its tests cover.
How it was started
Its skeleton is what the rind tool writes (Starting a
project): a workspace, an application crate, and one crate
per domain and layer. These commands write the same skeleton:
rind new railway --web actix --domain network
cd railway
rind add layer network shared # what the other domains show of a station
rind add domain accounts --layers models,ops # users, groups, signing in
rind add domain fleet
rind add domain timetable
rind add domain booking --layers models,ops,api
The domains are added in the order in which they point to each other: a
journey (in timetable) points to stations (in network) and to trains
(in fleet), so timetable comes after both. Organising an
application explains this order.
Then each model is added one at a time, with a resource for each model that is served:
rind add model network Station code:String name:String city:String
rind add resource network Station --rule anyone
rind make
Everything else is written by hand, in the files that those commands
wrote: the lengths, keys and indexes of the models, the fields of the
serializers, the rules, the actions. app() puts the domains together,
and signs users in with the accounts’ token
(.auth(accounts_ops::TokenAuth)).
In this repository the application crate is sample/ (not app/), and
the domains are in sample/crates/. The repository’s workspace says so
to the tool, in its Cargo.toml:
[workspace.metadata.rind]
app = "sample"
crates = "sample/crates"
So rind check, rind migrate and rind serve work from the
repository, as they do in a new project.
Running it
The repository’s docker-compose.yml starts a PostgreSQL with PostGIS
(the stations have positions), on port 54329. It also starts the servers
that some plugins’ tests use: Redis, an S3 server and Mailpit. Their data
is kept in memory.
docker compose up -d
export DATABASE_URL=postgres://rind:rind@127.0.0.1:54329/rind_sample
There is no .env file in the repository, which is why you export
DATABASE_URL yourself.
Create the tables with the application’s migrations, load a few rows, and serve:
rind migrate # or: cargo run -p sample -- migrate
psql $DATABASE_URL -c 'CREATE EXTENSION IF NOT EXISTS unaccent' -f sample/seed.sql
rind serve # on actix-web
The search of the stations and trains ignores accents, with PostgreSQL’s
unaccent extension. The migrations do not create it, so the psql line
does.
The sample is built with actix-web by default. To serve it on axum instead:
cargo run -p sample --no-default-features --features axum -- serve
make sample-seed (migrate, then load seed.sql) and make sample-serve
(or make sample-serve-axum) do the same. The sample’s main.rs is one
line: its commands are rind’s (The command line).
Then try a few requests:
curl 'localhost:8080/stations?search=paris&fields=name,region_path'
curl 'localhost:8080/journeys?day=2030-05-01&include=stops_details'
curl 'localhost:8080/journeys/1/rooms?free_only=true'
curl -H 'Authorization: Bearer alice-token' localhost:8080/reservations
curl -H 'Authorization: Bearer alice-token' -H 'Content-Type: application/json' \
-d '{"journey": 1, "wagon": 2, "passenger": 1, "seat": 2}' localhost:8080/reservations
The seed data has five users. Each one signs in with a token:
| Token | User |
|---|---|
root-token | root, a superuser |
staff-token | sam, of the railway’s staff |
alice-token, bob-token, carol-token | three travellers |
What it serves
Each resource shows some features of rind. The table says who may read and write each one, and what it shows:
| Resource | Who reads | Who writes | Shows |
|---|---|---|---|
/stations | everyone | staff | filters on a tree and on another domain, counts, a deletion that is tried first; a photo (Files); a position, ?near= (Geography); answers kept by the cache; as xlsx with columns of its own (Exports) |
/regions | everyone | staff | an outline in GeoJSON, ?covers=, its area (Geography) |
/lines | everyone | staff | behaviours: tracking, flags, markdown; a logo and a gallery (Images) |
/images | everyone | staff | an image’s size read from its file; resized copies at /media/…--cover_256.webp |
/trains | signed in | staff | nested lists, sums with a condition |
/journeys | everyone | staff | checks between fields, actions with typed parameters and a body; the distance between two stations |
/reservations | their own, or all for staff | signed in | permission modes, a creation checked under a lock; a confirmation by mail; logged with their body by the usage log |
The application is given every plugin of rind, in app()
(sample/src/lib.rs):
- metrics at
/metrics(Metrics), and/statusand/ready(Health); - the cache, in memory, or in Redis when
RIND_CACHE_URLnames one; - the storage of files, in
./mediaor whereRIND_STORAGEsays (a folder, an S3 bucket), with resized copies of the images; - mail, written to the console, or sent where
RIND_MAIL_URLsays (SMTP, Mailgun); - exports of the lists as xlsx and CSV;
- signing in with rind-auth: tokens, passwords, reset codes by mail. The simple tokens of the seed data still work;
- jobs: journeys marked as arrived every minute, and queued
mail, run by
cargo run -p sample -- jobs-work; - the usage log, in the table
rind_usage.
Its tests
sample/tests/ is where rind itself is tested on PostgreSQL:
export RIND_TEST_DATABASE_URL=postgres://rind:rind@127.0.0.1:54329/rind_sample
cargo test --workspace --all-features
make test does the same, and also sets the addresses of Redis, S3 and
Mailpit from docker-compose.yml. Without RIND_TEST_DATABASE_URL, the
tests that need a database are skipped. Each test works in a schema of
its own, built by the application’s migrations (see The
tests).
| File | What it tests |
|---|---|
api_actix.rs, api_axum.rs | the same HTTP cases (common/api_cases.rs) on both frameworks |
db.rs | the query layer: relations (also between crates), trees, aggregates, loaders, unions, locks |
model_writes.rs | an object written by itself: insert, save, update, refresh, delete; the model’s behaviours |
migrations.rs | making and applying migrations as the models change |
schema.rs | the models, the migrations and the database agree; the relations between crates hold |
inspect.rs | the schema the migrations build, read back, is what the models describe |
foreign_tables.rs | tables no model describes: what a deletion does to them, what dbcheck checks |
databases.rs | the primary, a replica, reading after writing |
geography.rs | positions, outlines and distances with PostGIS |
openapi.rs | the OpenAPI document, frozen in a snapshot |
routes.rs | routes that are not resources, in a domain and in the application |
cors.rs | CORS preflights and headers, on both frameworks |
auth.rs | signing in with rind-auth: tokens, refresh, passwords, reset and sign-in codes by mail, limits |
exports.rs | lists as xlsx and CSV |
jobs.rs | jobs: queued in a transaction, scheduled, retried, exclusive, timed out |
mail.rs | a reservation confirmed by mail, in memory, by SMTP (Mailpit, when RIND_TEST_SMTP_URL names it) and by a Mailgun the test plays |
plugins.rs | a plugin of the test’s own (a hook, a route, an observer, a service), then each of rind’s; Redis and S3 when RIND_TEST_REDIS_URL and RIND_TEST_S3_URL name them |
Organising an application
A Django project is cut into apps: catalog, accounts, billing.
Each app has its models.py, its serializers.py, its views.py, and
the apps import each other freely. A rind application is cut too, but
into Rust crates, and crates follow two rules that Python modules do not.
This chapter explains those rules, and how rind organises an application
around them: in domains and layers.
Why an application is several crates
A crate is compiled as a whole. When you change one line in a crate,
Rust compiles that whole crate again, and then every crate that depends
on it. rind’s derives (Model, Serializer, Resource…) write a lot of
code for you, so a crate with a few dozen models and their resources
takes a while to compile. If the whole application were one crate, every
change would mean that wait. Cut into crates, a change compiles only the
crate it is in, and the crates above it.
Crates cannot depend on each other in a circle. If fleet uses
network, then network cannot use fleet. Python allows two modules
to import each other; Cargo does not allow two crates to depend on each
other. So the parts of the application must be put in an order, where
each part uses only the parts before it.
rind’s answer to both rules is to cut the application in two directions:
- by domain: one subject of the application, like a Django app
(
network,accounts,fleet); - by layer: within a domain, one crate for the models, one for the resources, and others when they are needed.
So each crate is one layer of one domain, named <domain>-<layer>:
fleet-models, fleet-api. The sample is cut this way, even though it
is small:
sample/
src/lib.rs the application: puts the domains together
crates/
network/
network-models regions and stations
network-shared what other domains' resources show of a station
network-api the stations resource
accounts/
accounts-models users and groups
accounts-ops signing in
fleet/
fleet-models fleet-api
timetable/
timetable-models timetable-api
booking/
booking-models booking-ops booking-api
The rind tool writes this layout for you: rind add domain and
rind add layer (Starting a project).
Layers
A domain has up to four layers, from the bottom up. A crate may depend on the layers below its own, never on those above:
| Layer | Holds | May depend on |
|---|---|---|
models | the models, their scopes, their migrations | the models of the domains before its own |
shared | serializers and filters that other domains reuse | models |
ops | what the domain does, without HTTP | models, shared, other ops crates |
api | the resources | anything but another api crate |
A domain has only the layers it has something to put in. Most domains
have just models and api.
The models change least, so they are at the bottom. Every other crate depends on them, so a change there recompiles a lot. In practice, models change less often than the API.
An api crate is a leaf. Nothing depends on it except the application crate. It is where most of the code is, and where most changes are made, so a change there recompiles only that crate (and the application, which mostly just links). This is why an api crate must never depend on another api crate: that would make it a link in a chain again.
What two api crates both need goes in a shared crate. The trains
and the journeys both show stations, with the same few fields. That
serializer lives in network-shared, and both api crates use it:
#![allow(unused)]
fn main() {
// sample/crates/network/network-shared/src/lib.rs
/// A station as another object shows it: enough to name it.
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Station)]
pub struct StationBrief {
#[field(mandatory)]
pub id: Option<i64>,
#[field(mandatory)]
pub code: Option<String>,
#[field(mandatory)]
pub name: Option<String>,
pub city: Option<String>,
}
}
What the domain does goes in an ops crate. It holds the code that
is not about HTTP: signing in, booking a seat under a lock, a job. Django
projects often keep this in a services.py. An ops crate can be called
from an api crate, from a command, from a job or from a test.
An api crate may use the models of any domain, before or after its own:
network-api uses timetable-models to count a station’s departures.
Only the models crates are bound by the order of the domains.
Domains, in an order
The domains are put in an order, and a model may point only to the models
of its own domain and of the domains before it. In the sample, the order
is network, accounts, fleet, timetable, booking: a journey (in
timetable) points to stations and to trains, and a reservation (in
booking) points to journeys.
Rust requires this order, as we saw. It is also a good discipline: the order tells you which parts of the application are its foundations.
The same order appears in app(): the models are given domain after
domain, in that order.
A key that points the other way
Real data models do have circles, though. In the sample, a station’s
manager is a user, and a user has a home station. Since accounts comes
after network, the user’s key to a station is an ordinary key. But the
station’s key to a user points up, to a domain that network-models
cannot depend on.
This key is written with the name of its table, rather than with a type:
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
#[fk(table = "accounts_user", on_delete = set_null)]
pub manager_id: Option<i64>,
}
That is enough for the column and its constraint. The relation itself
(Station::manager()) is declared where both models are known: in the
higher crate, accounts-models, which can name Station. It is declared
in both directions at once:
#![allow(unused)]
fn main() {
// sample/crates/accounts/accounts-models/src/lib.rs
#[derive(Model)]
#[model(table = "accounts_user")]
#[reverse(name = managed_stations, model = Station, fk = "manager_id", forward = manager)]
pub struct User { … }
}
name is the relation from the user (User::managed_stations()), and
forward is the relation the station gets (Station::manager()). You
then follow it like any other relation:
Station::manager().username(), User::managed_stations().any(..). The
station’s methods come from a trait of the crate that declared them, so
you bring that trait into scope where you use them:
#![allow(unused)]
fn main() {
use accounts_models::StationManager as _;
}
Coming from Django: this is the Rust form of Django’s lazy reference,
models.ForeignKey("accounts.User", …): a key written by name, to a model that the file cannot import.
A relation back, from a higher domain
The other direction needs nothing special. A key to a model of a lower
domain can give that model a relation back, with reverse:
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-models/src/lib.rs (fragment)
#[fk(Station, on_delete = restrict, reverse = departures)]
pub origin_id: i64,
}
This gives Station::departures(), through a trait of
timetable-models (use timetable_models::StationDepartures as _;).
Django gives the same with related_name="departures".
Keys that no relation follows
A key that no relation follows yet says so with unfollowed:
#[fk(table = "…", unfollowed)]. Models written from a
database have many of these, because their domains point to
each other. A key to a table that no model of the application describes
is external: #[fk(table = "…", external)].
How names are checked
The compiler cannot check a table’s name written in a string. So a test
of the application, which sees every crate at once, checks them: a
#[fk(table = "…")] without its #[reverse(.., forward = …)], a table
that no model has, and so on. The test that rind new writes does it,
with the other checks of rind check:
#![allow(unused)]
fn main() {
// app/tests/schema.rs
#[test]
fn the_application_holds_together() {
rind::testing::check(&app::app());
}
}
You can also run the check on the relations alone:
#![allow(unused)]
fn main() {
#[test]
fn relations_between_domains_are_all_declared() {
assert!(rind::schema::lint(&sample::app().schema()).is_empty());
}
}
The application crate
The application crate names no model and no resource. Each models crate
gives its tables and migrations (migrations()), each api crate gives
its resources (api()), and the application puts them together:
#![allow(unused)]
fn main() {
// sample/src/lib.rs (shortened)
pub fn app() -> rind::Application {
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
.models(network_models::migrations())
.models(accounts_models::migrations())
// …
.api(network_api::api())
.api(fleet_api::api())
// …
.auth(accounts_ops::TokenAuth)
}
}
This is the place of Django’s INSTALLED_APPS and root urls.py. A new
domain is one line here per crate, and rind add domain writes them. The
schema, the migrations, the OpenAPI document and the routes all follow
from this value (The command line).
Checking the rules
The compiler enforces the order of the crates: a circle does not build.
The other rules of this chapter are checked by rind doctor
(Starting a project), without building
anything. It reports an api crate that depends on another, a crate that
depends on a higher layer, and a models or api crate that app() does
not have.
Reference
| Rule | Checked by |
|---|---|
| Crates do not depend on each other in a circle. | the compiler |
| A crate depends only on the layers below its own. | rind doctor |
| An api crate does not depend on another api crate. | rind doctor |
Every models crate and every api crate is in app(). | rind doctor; a models crate that others point to, also rind check |
A key by table name has its relation declared, or says unfollowed or external. | rind check, rind::testing::check, rind::schema::lint |
| Attribute | Where | Means |
|---|---|---|
#[fk(Target, reverse = name)] | on a key | a key to a model this crate can name; Target gets the relation name back |
#[fk(table = "…")] | on a key | a key to a model of a higher domain, by its table |
#[fk(table = "…", unfollowed)] | on a key | the same, with no relation declared yet |
#[fk(table = "…", external)] | on a key | a key to a table no model describes |
#[reverse(name = …, model = …, fk = "…", forward = …)] | on the target model | declares a relation held by a key of model, in both directions |
Models
A model describes one table of the database: its columns, its keys, its
relations to other tables, its indexes and its constraints. It is what a
Django model class is: class Train(models.Model), its fields and its
Meta. In rind, a model is a plain Rust struct with #[derive(Model)].
Everything else is built on the models. Queries are written with their columns, migrations are computed from them, and resources serve them over HTTP.
This chapter is long, so it is cut into sections. This first page shows a complete model and what the derive gives you. The next pages take each part of a model in turn, list every option, and show the SQL each one produces.
| Page | What it covers | In Django |
|---|---|---|
| Fields and column types | which Rust type gives which SQL type, NULL, every type rind knows | the field classes: CharField, IntegerField, JSONField… |
| Column options | lengths, defaults, unique columns, indexed columns, generated columns | max_length, default, unique, db_index |
| Types of your own | storing an enum or any type of yours in a column | custom fields, choices |
| Primary keys | id, another key, keys the application gives | primary_key=True, AutoField |
| Foreign keys | pointing to another model, what a deletion does | ForeignKey, on_delete |
| Reverse and many-to-many relations | walking a key backwards, link tables | related_name, ManyToManyField |
| Trees | rows that have a parent among themselves | django-mptt, django-treebeard |
| Indexes and constraints | indexes on several columns, unique together, checks | Meta.indexes, Meta.constraints |
| Scopes and scoped models | named queries on a model; models with no default query | managers, objects.published() |
| Sharing fields | fields written once, used by several models | abstract models, mixins |
| Writing objects | insert, save, update, delete on an object | obj.save(), obj.delete() |
| Behaviours and hooks | what every write of a model does | auto_now, save() overrides, signals |
| Reference | every attribute and every key, in tables |
A first model
Here is the train of the sample application, the railway:
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
use network_models::Station;
use rind::prelude::*;
/// A train: an engine and the wagons it pulls.
#[derive(Debug, Clone, Model)]
#[model(table = "fleet_train")]
#[reverse(name = wagons, model = Wagon, fk = "train_id")]
pub struct Train {
pub id: i64,
#[column(max_length = 10, unique)]
pub number: String,
#[column(max_length = 100)]
pub name: String,
/// `passenger` or `freight`.
#[column(max_length = 10)]
pub kind: String,
/// `active`, `maintenance` or `retired`.
#[column(max_length = 12, default = "'active'", index)]
pub status: String,
/// The station it is kept at.
#[fk(Station, on_delete = restrict, name = depot, reverse = depot_trains)]
pub depot_id: i64,
}
}
Read it from top to bottom:
use rind::prelude::*;brings the derive and the query types (Query,Insert,Db…) into scope. Every models crate starts with it.#[derive(Debug, Clone, Model)]:Modelis the derive that does the work.DebugandCloneare not required, but you will want them.#[model(table = "fleet_train")]names the table. It is required: rind does not make up a name from the crate and the struct.- Each field is a column, and the field’s Rust type gives the column’s
SQL type: an
i64is abigint, aStringwithmax_length = 10is acharacter varying(10). idis the primary key, because it is calledid.#[column(..)]adds what the type cannot say: a length, a default, a unique constraint, an index.depot_idis a foreign key to the stations. The relation is calleddepot.#[reverse(..)]declares the other side of a foreign key that another model holds: the wagons point to their train, so a train haswagons.- The doc comments (
///) are kept. They describe the fields in the OpenAPI document, as Django’shelp_textdoes.
The table this model describes, as rind schema prints it:
CREATE TABLE "fleet_train" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"number" character varying(10) NOT NULL CONSTRAINT "fleet_train_number_key" UNIQUE,
"name" character varying(100) NOT NULL,
"kind" character varying(10) NOT NULL,
"status" character varying(12) NOT NULL DEFAULT 'active',
"depot_id" bigint NOT NULL
);
CREATE INDEX "fleet_train_status_idx" ON "fleet_train" ("status");
ALTER TABLE "fleet_train" ADD CONSTRAINT "fleet_train_depot_id_fkey" FOREIGN KEY ("depot_id") REFERENCES "network_station" ("id") ON DELETE RESTRICT;
CREATE INDEX "fleet_train_depot_id_idx" ON "fleet_train" ("depot_id");
There is nothing in the table that the struct does not say, and nothing in the struct that the table does not have.
What the derive gives you
With this struct, you can already read trains:
#![allow(unused)]
fn main() {
let active: Vec<Train> = db
.all(&Query::<Train>::new().filter(Train::status().eq("active")))
.await?;
}
The derive gave the struct everything a Django model class has:
- It can be read from a row.
db.all(&query)answers aVec<Train>,db.first(&query)anOption<Train>. - It has a typed path to each column,
Train::number(), and to each relation,Train::depot()andTrain::wagons(). You write queries with them, as you would writeTrain.objects.filter(depot__city="Paris")in Django:Train::depot().city().eq("Paris"). A misspelt name does not compile. - Its schema is known. The migrations compare it with the database and write what changed (Migrations).
- It can write itself:
train.insert(&db),train.save(&db),train.delete(&db)(Writing objects).
The paths are typed. Train::number() is a path to a String, so it can
be compared with a text, and not with a number:
error[E0277]: the trait bound `{integer}: Operand<std::string::String>` is not satisfied
|
| Query::new().filter(Train::number().eq(3))
| -- ^ the trait `Operand<std::string::String>` is not implemented for `{integer}`
Reference lists everything the derive writes.
Coming from Django: there is no automatic
idfield, no automatic table name, and no automatic reverse relation (wagon_set). Everything a model has is written in the struct. This costs a few lines, and it means that what you read is what the database has.
From the struct to the table
A model does not create its table by itself. Three steps, which rind add model prepares for you:
-
The model is listed in the
schema()function of its crate. A model that is not listed has no table, and nothing warns you:#![allow(unused)] fn main() { // sample/crates/fleet/fleet-models/src/lib.rs pub fn schema() -> Vec<rind::schema::Table> { use rind::schema::Table; vec![Table::of::<Train>(), Table::of::<Wagon>(), Table::of::<Driver>()] } pub fn migrations() -> rind::migrations::Domain { rind::migrations::domain!("fleet", schema()) } } -
The domain is in the application:
app()has.models(fleet_models::migrations()). -
A migration is written and applied:
rind make, thenrind migrate(Migrations).
After that, every change to the struct is a new rind make. rind check
fails when the struct and the migrations disagree.
Where models live
A model lives in the models crate of its domain
(crates/fleet/fleet-models): the crate that every other layer of the
domain depends on. Keep this crate free of HTTP: no serializers, no
resources. A model may point to the models of the domains before its
own, never after (Organising an application).
Next: Fields and column types.
Fields and column types
Each field of a model struct is a column of its table. rind reads the field’s Rust type and chooses the SQL type from it. This page lists every type rind knows, with the column it gives, and how its values look in JSON when a resource sends them.
All the SQL on this page was printed by rind schema from a model that
has every type:
#![allow(unused)]
fn main() {
use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
use rind::prelude::*;
#[derive(Debug, Clone, Model)]
#[model(table = "lab_everything")]
pub struct Everything {
pub id: i64,
pub big: i64,
pub int: i32,
pub small: i16,
// … one field per type, shown below
}
}
NULL is Option
A column is NOT NULL unless its field is an Option:
#![allow(unused)]
fn main() {
pub body: String, // "body" text NOT NULL
pub maybe: Option<String>, // "maybe" text
}
This is Django’s null=True. There is no separate blank=True: what a
client may leave empty is decided by the input, not by
the model.
Option works with every type on this page, arrays included:
Option<Vec<i32>> is a nullable integer[].
Numbers
#![allow(unused)]
fn main() {
pub big: i64, // "big" bigint NOT NULL
pub int: i32, // "int" integer NOT NULL
pub small: i16, // "small" smallint NOT NULL
pub double: f64, // "double" double precision NOT NULL
pub single: f32, // "single" real NOT NULL
}
| Rust | PostgreSQL | Django | JSON |
|---|---|---|---|
i64 | bigint | BigIntegerField | 42 |
i32 | integer | IntegerField | 42 |
i16 | smallint | SmallIntegerField | 42 |
f64 | double precision | FloatField | 4.2 |
f32 | real | 4.2 |
There are no unsigned types (u32, u64): PostgreSQL has none. Use the
signed type, and a check constraint if the value
must be positive (Django’s PositiveIntegerField).
In queries, every integer column compares with any integer, and every
float column with any float: Wagon::position().eq(1) works although the
column is an i32. (The path of an integer column is a Path<i64>,
whatever its width.)
For exact decimals (prices), see Decimals below.
Booleans
#![allow(unused)]
fn main() {
pub flag: bool, // "flag" boolean NOT NULL
}
Django’s BooleanField. JSON true or false.
Texts
#![allow(unused)]
fn main() {
pub body: String, // "body" text NOT NULL
#[column(max_length = 50)]
pub short: String, // "short" character varying(50) NOT NULL
}
A String is a text column, of any length: Django’s TextField. With
max_length = n, it is a character varying(n): Django’s CharField.
In PostgreSQL the two are stored the same way and are as fast. The
length is a rule about the data, not an optimisation. Use max_length
when there is a real limit (a code, a name), and text otherwise.
The input does not read the model’s max_length: give it
there too (#[input(max_length = 50)]), so that a client gets a clear
error on the field rather than a database error.
Django’s EmailField, SlugField, URLField are all CharFields with a
validation. In rind the column is a String; the validation goes in the
input.
Dates and times
#![allow(unused)]
fn main() {
use chrono::{DateTime, NaiveDate, NaiveDateTime, Utc};
pub day: NaiveDate, // "day" date NOT NULL
pub moment: DateTime<Utc>, // "moment" timestamp with time zone NOT NULL
pub local: NaiveDateTime, // "local" timestamp without time zone NOT NULL
}
| Rust | PostgreSQL | Django | JSON |
|---|---|---|---|
chrono::NaiveDate | date | DateField | "2026-11-27" |
chrono::DateTime<Utc> | timestamp with time zone | DateTimeField with USE_TZ = True | "2026-11-27T15:48:05Z" |
chrono::NaiveDateTime | timestamp without time zone | DateTimeField with USE_TZ = False | "2026-11-27T15:48:05" |
The types come from the chrono crate. rind
re-exports it, so a models crate can use it without a dependency of its
own:
#![allow(unused)]
fn main() {
use rind::db::chrono::{DateTime, NaiveDate, Utc};
}
or add it to its Cargo.toml, as the sample does, with the serde
feature (the serializers need it):
chrono = { version = "0.4", default-features = false, features = ["std", "clock", "serde"] }
Which one to choose. A moment in time (when a row was created, when a
train leaves) is a DateTime<Utc>: PostgreSQL stores it as an instant,
and there is no doubt about its time zone. Use NaiveDateTime only to
describe an existing database whose columns have no time zone.
Not supported yet: a time of day alone (time, Django’s
TimeField, chrono::NaiveTime) and a duration (interval,
DurationField). rind can neither write them nor compare them. Store a
time as an i32 of minutes or seconds, and a duration as an i64 of
seconds.
JSON
#![allow(unused)]
fn main() {
pub data: serde_json::Value, // "data" jsonb NOT NULL
}
A serde_json::Value is a jsonb column: Django’s JSONField. It holds
any JSON value, and is sent to the client as it is.
rind::prelude has a type called Value too: it is rind’s own value of a
query parameter, not JSON. Write serde_json::Value in full in a model,
and add serde_json to the crate’s dependencies.
Queries can look inside a JSON column: see Queries.
Arrays
#![allow(unused)]
fn main() {
pub tags: Vec<String>, // "tags" text[] NOT NULL
#[column(max_length = 20)]
pub codes: Vec<String>, // "codes" character varying(20)[] NOT NULL
pub numbers: Vec<i64>, // "numbers" bigint[] NOT NULL
pub maybe_list: Option<Vec<i32>>, // "maybe_list" integer[]
}
A Vec<T> is a PostgreSQL array of the SQL type of T: Django’s
ArrayField (from django.contrib.postgres). max_length applies to
each element. Arrays of arrays are not supported.
In JSON an array is a list: ["rail", "night"].
Arrays are useful for short lists that belong to the row (tags, flags, the services of a station) and that you filter with “contains” or “overlaps”. When the elements have attributes of their own, or are shared between rows, use another model and a relation instead.
Bytes
#![allow(unused)]
fn main() {
#[column(sql = "bytea")]
pub raw: Vec<u8>, // "raw" bytea NOT NULL
}
Django’s BinaryField. rind would read a Vec<u8> as an array of small
numbers, so give the type with sql = "bytea". In JSON it is a list of
numbers: [0, 1, 255].
For files (images, documents), do not store the bytes in the table: use
a File column, below.
Types that need their SQL type
For the types below, there is more than one possible SQL type, or the
type comes from an extension. rind cannot guess, so the field says it
with #[column(sql = "…")]:
#![allow(unused)]
fn main() {
#[column(sql = "inet")]
pub address: rind::db::types::Inet, // "address" inet NOT NULL
}
If you forget it, the derive stops:
error: cannot tell the SQL type of this field: give it, #[column(sql = "…")]
|
| pub address: rind::db::types::Inet,
| ^^^^^^^^^^^^^^^^^^^^^
Each of these types reads and writes its PostgreSQL type exactly, in the binary form the server uses, in queries, inputs and updates alike.
| Rust | sql = … | Django | JSON |
|---|---|---|---|
rind::db::types::Decimal (feature decimal) | "numeric(10, 2)" | DecimalField | "1234.56" (a string, so no digit is lost) |
rind::db::types::Inet | "inet" | GenericIPAddressField | "192.168.1.7" |
rind::db::geo::Point | "geography(Point,4326)" or "geometry(Point,4326)" | GeoDjango PointField | {"lng": 2.35, "lat": 48.85} |
rind::db::geo::Polygon, MultiPolygon, Geometry | "geometry(Polygon,4326)"… | PolygonField… | GeoJSON |
rind::db::geo::Shape | any PostGIS type | GeometryField | the EWKB, in hexadecimal |
rind::db::types::Vector | "vector(3)" (pgvector) | pgvector’s VectorField | [0.5, -1.0, 2.0] |
rind::db::types::TsVector | "tsvector" | SearchVectorField | [{"word": "gare", "positions": [1]}] |
rind::db::types::EnumValue | the name of an enumerated type | "ok" (the label) |
Decimals
Decimal needs the Cargo feature decimal of rind:
rind = { workspace = true, features = ["decimal"] }
#![allow(unused)]
fn main() {
#[column(sql = "numeric(10, 2)")]
pub price: rind::db::types::Decimal,
}
numeric(10, 2) is Django’s max_digits=10, decimal_places=2. Never
store money in an f64.
Geography
Point and the shapes need the PostGIS extension, which the domain
declares so that its first migration creates it:
#![allow(unused)]
fn main() {
pub fn migrations() -> rind::migrations::Domain {
rind::migrations::domain!("network", schema()).extension("postgis")
}
}
Geography has the rest: the shapes, distances, and how a client sends a point.
Enumerated types
EnumValue holds a value of a PostgreSQL enumerated type (CREATE TYPE mood AS ENUM ('sad', 'ok', 'happy')), by its label. It is for a database
that already has such types. For a new model, a Rust enum stored as a
text is usually simpler: see Types of your own.
Files
#![allow(unused)]
fn main() {
#[column(max_length = 200)]
pub photo: Option<rind::db::types::File>, // "photo" character varying(200)
}
A File column holds the key of a file in the storage (a folder or an
S3 bucket), as Django’s FileField holds a path. The bytes are in the
storage, not in the table. In JSON it is {"url": …, "name": …, "size": …}, or null. See Files.
Names of columns
The column has the name of the field. A field whose name is a Rust
keyword is written with r#:
#![allow(unused)]
fn main() {
pub r#type: String, // the column "type"
}
Its path is then Model::type_(), with a trailing underscore, since
type() is not a valid function name.
To give a column another name than its field, there is no option: the field has the column’s name. (Models written from a database keep the database’s names.)
Doc comments
A doc comment on a field is kept by the derive. The serializers and
inputs that send or read the field use it as the field’s description in
the OpenAPI document, as Django’s help_text:
#![allow(unused)]
fn main() {
/// `active`, `maintenance` or `retired`.
#[column(max_length = 12, default = "'active'", index)]
pub status: String,
}
What is not supported
| Django | rind |
|---|---|
TimeField, DurationField | not yet: store minutes or seconds in an integer |
UUIDField | not yet: a String with sql = "uuid" can be neither read nor written (error deserializing column). Store UUIDs as text, or write a type of your own |
PositiveIntegerField | a signed integer and a check |
choices= | a String and the input’s choices(..), or an enum of your own |
db_column= | none: the field has the column’s name |
Next: Column options.
Column options
The Rust type of a field gives the SQL type of its column. Everything
else about the column is said with #[column(..)], written above the
field:
#![allow(unused)]
fn main() {
#[column(max_length = 12, default = "'active'", index)]
pub status: String,
}
This page takes each key in turn. There are seven:
| Key | What it does | Django |
|---|---|---|
max_length = n | a text of at most n characters | max_length= |
default = "SQL" | the column’s default, in SQL | default=, db_default= |
unique | a unique constraint on the column | unique=True |
index | an index on the column | db_index=True |
sql = "type" | the SQL type, when rind cannot tell it | a custom field’s db_type() |
generated = "SQL" | a column the database computes | GeneratedField |
read = "SQL" | an expression the column is read through |
A key that does not exist is a compile error that lists the right ones:
error: unknown key: expected `max_length`, `sql`, `default`, `unique`, `index`, `read` or `generated`
|
| #[column(max_lenght = 3)]
| ^^^^^^^^^^
max_length: the length of a text
#![allow(unused)]
fn main() {
#[column(max_length = 50)]
pub short: String, // "short" character varying(50) NOT NULL
#[column(max_length = 20)]
pub codes: Vec<String>, // "codes" character varying(20)[] NOT NULL
}
On a String, it makes a character varying(n) instead of a text. On a
Vec<String>, it applies to each element. On a File,
it is the length of the file’s key.
The database refuses a longer value. The input checks it
earlier, with a clear message, when it has the same key:
#[input(max_length = 50)].
default: the column’s default value
#![allow(unused)]
fn main() {
#[column(default = "'draft'", max_length = 10)]
pub status: String, // "status" character varying(10) NOT NULL DEFAULT 'draft'
#[column(default = "0")]
pub count: i32, // "count" integer NOT NULL DEFAULT 0
#[column(default = "false")]
pub archived: bool, // "archived" boolean NOT NULL DEFAULT false
#[column(default = "now()")]
pub created: DateTime<Utc>, // "created" timestamp with time zone NOT NULL DEFAULT now()
#[column(default = "CURRENT_DATE")]
pub borrowed_on: NaiveDate, // "borrowed_on" date NOT NULL DEFAULT CURRENT_DATE
#[column(default = "'{}'")]
pub labels: Vec<String>, // "labels" text[] NOT NULL DEFAULT '{}'
#[column(default = "'{}'::jsonb")]
pub extra: serde_json::Value, // "extra" jsonb NOT NULL DEFAULT '{}'::jsonb
}
The default is SQL, not Rust. The string is copied as it is after
DEFAULT in the table’s definition. That is why a text default has its
own quotes inside the Rust string: "'draft'" is the SQL text 'draft',
while "draft" would be the name of a column, and the migration would
fail.
| You want | Write |
|---|---|
| a text | default = "'draft'" |
| a number | default = "0", default = "1.5" |
| a boolean | default = "false" |
| the time of the insert | default = "now()" |
| the day of the insert | default = "CURRENT_DATE" |
| an empty array | default = "'{}'" |
| an array with values | default = "'{rail,night}'" |
| an empty JSON object | default = "'{}'::jsonb" |
| a random UUID, as text | default = "gen_random_uuid()::text" |
When the default is used. The database uses it when an INSERT does
not name the column. Three cases:
-
An insert built with
Insertthat does not set the column:#![allow(unused)] fn main() { // no `status` given: the row gets 'draft' let order: Order = db.insert(&Insert::<Order>::new()).await?; } -
A creation through a resource whose client did not send the field (when the input does not give a default of its own).
-
An insert written in SQL.
An object written with order.insert(&db) gives every
column, since a Rust struct has no “missing” field, so the column’s
default is not used there.
Coming from Django: Django’s
default=is a Python value, computed when the object is made, and the database never sees it. rind’sdefaultis the database’s own default, like Django 5’sdb_default=. It works for every insert, whoever writes it: the API, a script,psql. A default that depends on the request (the user who creates the row) belongs to the resource’s hook.
unique: one row per value
#![allow(unused)]
fn main() {
#[column(unique, max_length = 20)]
pub code: String,
// "code" character varying(20) NOT NULL CONSTRAINT "lab_everything_code_key" UNIQUE
#[column(unique = "lab_everything_slug_uniq", max_length = 20)]
pub slug: String,
// "slug" character varying(20) NOT NULL CONSTRAINT "lab_everything_slug_uniq" UNIQUE
}
The constraint is named <table>_<column>_key, PostgreSQL’s own
convention. Give a name (unique = "…") only to describe a database
whose constraint already has another one.
Several NULLs do not break a unique constraint: PostgreSQL counts each
NULL as different. For columns that are unique together, or to count
NULLs as equal, use #[unique(..)]
on the struct.
When a write breaks the constraint, a resource answers 400, not 500.
Declare it on the input too (#[input(model = Train, unique(number))])
and the client gets the message on the field.
index: an index on the column
#![allow(unused)]
fn main() {
#[column(index)]
pub rank: i32,
// CREATE INDEX "lab_everything_rank_idx" ON "lab_everything" ("rank");
#[column(index = "lab_everything_score_idx")]
pub score: i32,
// CREATE INDEX "lab_everything_score_idx" ON "lab_everything" ("score");
}
The index is named <table>_<column>_idx, unless a name is given.
You do not need index on:
- a foreign key: it gets an index by itself (Foreign keys);
- a unique column: the unique constraint is an index already;
- the primary key.
Add one on a column that lists often filter or sort on (a status, a date). For an index on several columns, on an expression, or of another kind than a B-tree, see Indexes and constraints.
sql: the SQL type, said explicitly
#![allow(unused)]
fn main() {
#[column(sql = "inet")]
pub address: rind::db::types::Inet,
#[column(sql = "numeric(10, 2)")]
pub price: rind::db::types::Decimal,
#[column(sql = "geography(Point,4326)")]
pub position: Option<rind::db::geo::Point>,
}
sql replaces the type rind would choose. It is required for the types
listed in Types that need their SQL type
and for your own types. The string is copied as it is
into the table’s definition.
It can also replace a type rind knows, when an existing database has
another one: #[column(sql = "character varying(254)")] pub email: String describes a column whose length is not a rule you want to
repeat in max_length.
generated: a column the database computes
#![allow(unused)]
fn main() {
#[column(generated = "md5(body)")]
pub body_hash: String,
// "body_hash" text GENERATED ALWAYS AS (md5(body)) STORED NOT NULL
}
A generated column is computed by PostgreSQL from the other columns of
its row, at every insert and update: Django’s GeneratedField. The
expression is SQL, and can only use columns of the same row.
rind never writes a generated column: not in an object’s insert or
save, not in an input. It reads it like any other column, filters and
sorts on it. Uses: a hash for a uniqueness, a lower-case copy for a
search, a total of two columns.
read: a column read through an expression
#![allow(unused)]
fn main() {
#[column(sql = "geometry(Point,4326)", read = "ST_AsGeoJSON({})::jsonb")]
pub geom: serde_json::Value,
}
read is SQL that the column is read through: {} stands for the
column. Here the database stores a PostGIS geometry, and rind reads it as
GeoJSON, into a serde_json::Value.
Filters and orderings still see the stored column, not the expression.
And since rind could not write the value back in the stored type, it
never writes a column that has read: it is read-only for rind.
read is mostly for databases you describe but do not control. For
geography, the Point and shape types are usually
better: they read and write.
Combining keys
Keys combine, in any order:
#![allow(unused)]
fn main() {
#[column(max_length = 10, default = "'draft'", index)]
pub status: String,
}
Some combinations make no sense, and the derive does not always stop
them: a default on a generated column, an index on a unique one.
Keep each column to the keys it needs.
Next: Types of your own.
Types of your own
A column can have a type of your application: a Rust enum for a status,
a newtype around a code, a value that the database stores in a way of its
own. This is what Django does with choices (and TextChoices), or with
a custom Field subclass.
This page builds one complete example, an order whose status is an
enum, and explains each piece.
The goal
In Django:
class Order(models.Model):
class Status(models.TextChoices):
DRAFT = "draft"
SENT = "sent"
PAID = "paid"
status = models.CharField(max_length=10, choices=Status, default=Status.DRAFT)
In rind, the column stays a character varying(10) in the database, and
the field is a Rust enum, so that the code can never hold a status that
does not exist:
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "lab_order")]
pub struct Order {
pub id: i64,
#[column(sql = "character varying(10)", default = "'draft'")]
pub status: Status,
}
}
CREATE TABLE "lab_order" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"status" character varying(10) NOT NULL DEFAULT 'draft'
);
What a type needs
A type can be a column when it has four things:
| What | Why |
|---|---|
#[column(sql = "…")] on the field | rind cannot guess the SQL type of a type it does not know |
Debug, Clone and Default | the model derives them, and a model read partially (as serializers read them) fills the columns it did not read with their default |
rind::query::ToValue | how the value is sent to the database: in an insert, an update, or a comparison in a query |
tokio_postgres::types::FromSql | how the value is read from a row |
The type
#![allow(unused)]
fn main() {
/// The state of an order: stored as a text column.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Status {
#[default]
Draft,
Sent,
Paid,
}
impl Status {
pub fn as_str(self) -> &'static str {
match self {
Status::Draft => "draft",
Status::Sent => "sent",
Status::Paid => "paid",
}
}
}
}
#[default] says which variant Default gives. It does not have to be
the column’s SQL default, but keeping them the same avoids surprises.
Writing: ToValue
#![allow(unused)]
fn main() {
/// How the status is sent to the database.
impl rind::query::ToValue for Status {
fn to_value(self) -> rind::query::Value {
rind::query::Value::Text(self.as_str().to_owned())
}
}
}
ToValue turns the value into a rind::query::Value, the type of every
query parameter. Value has a variant for each kind of value PostgreSQL
receives: Text, Int, Float, Bool, Date, Timestamp, Json,
arrays, and Binary for a type sent in PostgreSQL’s binary form.
Reading: FromSql
Reading uses the PostgreSQL driver’s trait, FromSql. rind does not
re-export the driver, so add it to the models crate:
tokio-postgres = "0.7"
#![allow(unused)]
fn main() {
/// How the status is read from a row.
impl<'a> tokio_postgres::types::FromSql<'a> for Status {
fn from_sql(
ty: &tokio_postgres::types::Type,
raw: &'a [u8],
) -> Result<Status, Box<dyn std::error::Error + Sync + Send>> {
match <&str as tokio_postgres::types::FromSql>::from_sql(ty, raw)? {
"draft" => Ok(Status::Draft),
"sent" => Ok(Status::Sent),
"paid" => Ok(Status::Paid),
other => Err(format!("not a status: {other}").into()),
}
}
fn accepts(ty: &tokio_postgres::types::Type) -> bool {
<&str as tokio_postgres::types::FromSql>::accepts(ty)
}
}
}
The function reads the column as a &str, using the driver’s own
implementation, then turns it into a Status. accepts says which SQL
types it can read: the same as a &str (text, varchar…).
A value in the table that is not a status (written by hand, by another
program) is an error when the row is read, not a silent Draft.
Using it
The column now has a path of type Path<Status>, which compares with a
Status:
#![allow(unused)]
fn main() {
/// The orders not paid yet.
pub fn unpaid() -> Query<Order> {
Query::new().filter(Order::status().ne(Status::Paid))
}
/// Marks an order as paid.
pub async fn pay(db: &Db, id: i64) -> Result<u64, rind::db::Error> {
db.execute(
&Update::<Order>::new()
.set(Order::status(), Status::Paid)
.filter(Order::id().eq(id)),
)
.await
}
}
Comparing it with a text, Order::status().eq("paid"), does not compile:
the type does its job.
An insert that does not give the status gets the column’s default, read
back as Status::Draft:
#![allow(unused)]
fn main() {
let order: Order = db.insert(&Insert::<Order>::new()).await?;
assert_eq!(order.status, Status::Draft);
}
In the API
To send the field in a serializer or read it in an
input, the type also needs serde’s Serialize and
Deserialize, and rind’s rind::api::openapi::JsonSchema (the
OpenAPI document describes every field). Without
JsonSchema, the serializer does not compile.
A simpler path, often enough, is to keep the column a String in the
model, and let the input restrict its values:
#![allow(unused)]
fn main() {
// the model
#[column(max_length = 10, default = "'draft'")]
pub status: String,
// the input
#[input(choices("draft", "sent", "paid"), default = "draft")]
pub status: Option<String>,
}
This is what the sample does for its statuses. Choose the enum when
Rust code takes decisions on the value, and the String when the value
mostly goes in and out of the API.
Other examples
The same four pieces work for any type:
- A newtype (
pub struct Siret(String)):ToValuegivesValue::Text(self.0),FromSqlreads a&strand checks it. - An
i16code (enum Level { Low = 1, High = 2 }):sql = "smallint",Value::Int(self as i64),FromSqlreads ani16. - A PostgreSQL enumerated type: rind already has one,
rind::db::types::EnumValue(Fields).
Next: Primary keys.
Primary keys
Every model has one primary key, made of one column. This page shows the
usual key, id, and the other cases: a key with another name, a key the
application gives, a key that is not a number.
The usual key: id
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "lab_tag")]
pub struct Tag {
pub id: i64,
pub name: String,
}
}
CREATE TABLE "lab_tag" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"name" text NOT NULL
);
A field called id is the primary key. Its column is an identity: the
database gives each new row the next number. This is Django’s
BigAutoField, the default of new Django projects.
Unlike Django, the field is written in the struct: rind adds no field of
its own. Use i64. An i32 key works too (it is an integer identity),
but the foreign keys that point to it must then be i32 too, and the
rest of rind (resources, deletions that follow keys) is written for
i64 keys.
Inserts do not send it. An identity key is left out of every insert, and the database’s value comes back:
#![allow(unused)]
fn main() {
let tag = Tag { id: 0, name: "rust".into() }.insert(&db).await?;
// Tag { id: 1, name: "rust" }: the 0 was not sent
}
The id: 0 in the struct is only a placeholder; any value would do.
GENERATED BY DEFAULT (and not ALWAYS) lets an insert written in SQL
give a key all the same, for an import or a test fixture:
INSERT INTO catalog_author (id, name) VALUES (1, 'Frank Herbert');
After such inserts, the identity’s counter does not know the keys you gave. Move it past them, or the next insert through rind fails on a duplicate key:
SELECT setval(pg_get_serial_sequence('catalog_author', 'id'), (SELECT max(id) FROM catalog_author));
A key with another name: pk
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "lab_k3", pk = "number")]
pub struct K3 {
pub number: i32,
}
}
CREATE TABLE "lab_k3" (
"number" integer GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY
);
pk = "…" names the field of the key, when it is not id: Django’s
primary_key=True on another field. The key is still an identity, unless
the model also says manual_key.
A key the application gives: manual_key
Sometimes the key is not a counter: a country’s ISO code, a key copied
from another system, a key shared with another table. Say so with
manual_key:
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "lab_country", pk = "code", manual_key)]
pub struct Country {
#[column(max_length = 2)]
pub code: String,
pub name: String,
}
}
CREATE TABLE "lab_country" (
"code" character varying(2) PRIMARY KEY,
"name" text NOT NULL
);
There is no identity, and inserts write the key:
#![allow(unused)]
fn main() {
let fr = Country { code: "FR".into(), name: "France".into() }.insert(&db).await?;
}
manual_key works with an i64 id too:
#![allow(unused)]
fn main() {
#[model(table = "lab_k2", manual_key)]
pub struct K2 { pub id: i64 }
// "id" bigint PRIMARY KEY
}
Watch out: a key that is not an integer must have
manual_key. Without it, the migration says"code" text GENERATED BY DEFAULT AS IDENTITY, which PostgreSQL refuses when the migration is applied. The derive does not stop it yet.
A foreign key to a model with a text key is an Option<String> or a
String:
#![allow(unused)]
fn main() {
#[fk(Country)]
pub country_id: Option<String>,
// ALTER TABLE … ADD CONSTRAINT "lab_article_country_id_fkey" FOREIGN KEY ("country_id") REFERENCES "lab_country" ("code");
}
Some features need an i64 key: deletions that follow foreign
keys (delete_cascade),
many-to-many links (db.link), and the loaders that read
a page’s relations. Prefer an i64 id and a unique code, unless you
describe a database that already has another key.
The name of the key’s constraint: key_name
PostgreSQL names the primary key’s constraint <table>_pkey. A database
made by another tool may have another name; describe it with key_name,
so that rind’s migrations and checks match it:
#![allow(unused)]
fn main() {
#[model(table = "lab_country", pk = "code", manual_key, key_name = "lab_country_code_pk")]
// "code" character varying(2) CONSTRAINT "lab_country_code_pk" PRIMARY KEY,
}
Keys of several columns
A primary key of several columns (Django 5.2’s CompositePrimaryKey) is
not supported. Give the table an id, and make the columns
unique together.
Summary
| You want | Write | Column |
|---|---|---|
| the usual key | pub id: i64 | bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY |
| another name | #[model(pk = "number")] | an identity on that column |
| a key you give | #[model(manual_key)] | PRIMARY KEY, no identity |
| a text key | #[model(pk = "code", manual_key)] | character varying(n) PRIMARY KEY |
| a constraint’s own name | #[model(key_name = "…")] | CONSTRAINT "…" PRIMARY KEY |
Next: Foreign keys.
Foreign keys
A foreign key is a column that holds the key of a row of another table:
a wagon holds the id of its train. It is Django’s ForeignKey. This page
shows how to declare one, how it is named, what happens when the row it
points to is deleted, and every option.
Declaring a foreign key
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
#[derive(Debug, Clone, Model)]
#[model(table = "fleet_wagon")]
pub struct Wagon {
pub id: i64,
#[fk(Train, on_delete = cascade)]
pub train_id: i64,
pub position: i32,
// …
}
}
CREATE TABLE "fleet_wagon" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"train_id" bigint NOT NULL,
"position" integer NOT NULL,
…
);
ALTER TABLE "fleet_wagon" ADD CONSTRAINT "fleet_wagon_train_id_fkey" FOREIGN KEY ("train_id") REFERENCES "fleet_train" ("id") ON DELETE CASCADE;
CREATE INDEX "fleet_wagon_train_id_idx" ON "fleet_wagon" ("train_id");
Three things to notice:
- The field holds the key itself. Its type is the type of the
target’s key,
i64. There is no “related object” in the struct: what Django callswagon.train_idis the field, and there is nowagon.trainthat loads the train when you touch it. (Loading related rows is always explicit in rind, and done for many rows at once: see Queries.) - The first argument is the target model,
Train. The crate must be able to name it: the target is in the same crate, or in a crate this one depends on. - The key gets an index by itself, as in Django.
Nullable keys
A key that may point to nothing is an Option:
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
/// Someone who drives trains. A driver may have an account.
#[fk(User, on_delete = set_null, reverse = drivers)]
pub user_id: Option<i64>,
}
This is Django’s ForeignKey(..., null=True).
The relation and its name
The field is the column; the relation is what queries follow from one
model to the other. The relation is named after the field without its
_id: the field train_id gives the relation train.
#![allow(unused)]
fn main() {
// the wagons of the trains named "Le Mistral"
Query::<Wagon>::new().filter(Wagon::train().name().eq("Le Mistral"))
}
Wagon::train() is a path to the related train, and .name() a path to
its column. This is Django’s Wagon.objects.filter(train__name="Le Mistral"), checked by the compiler. A relation can be followed as far as
you like: Wagon::train().depot().city().
To give the relation another name, write name:
#![allow(unused)]
fn main() {
#[fk(Station, on_delete = restrict, name = depot)]
pub depot_id: i64, // the relation is `depot`
#[fk(Tag, on_delete = set_null, name = editor)]
pub editor_tag_id: Option<i64>, // the relation is `editor`, not `editor_tag`
}
A field whose name does not end in _id must have a name:
error: a foreign key field is named `<relation>_id`, or the relation is given: #[fk(Target, name = relation)]
|
| #[fk(Tag)] pub owner: i64
| ^^^^^
What a deletion does: on_delete
When a train is deleted, what becomes of its wagons? on_delete answers,
as in Django:
on_delete | When the target is deleted | SQL | Django |
|---|---|---|---|
cascade | this row is deleted too | ON DELETE CASCADE | CASCADE |
set_null | this row’s key becomes NULL | ON DELETE SET NULL | SET_NULL |
restrict | the deletion is refused | ON DELETE RESTRICT | PROTECT |
| (none) | the deletion is refused while this row points to it | (no clause) | DO_NOTHING with a real constraint |
Choose by asking what the row is without its target:
- a wagon without its train means nothing:
cascade; - a driver can lose their account and stay a driver:
set_null; - a train cannot lose its depot by accident:
restrict. The station must be emptied of its trains first, on purpose.
set_null needs a nullable field (Option<i64>).
Watch out: the derive does not check it yet.
#[fk(Tag, on_delete = set_null)] pub tag_id: i64compiles, and writesON DELETE SET NULLon aNOT NULLcolumn: the deletion of a tag then fails in the database.
Without on_delete, the constraint has no ON DELETE clause: PostgreSQL
refuses to delete a row that is still pointed to, as with restrict
(the difference is only when the check runs, which matters with
deferred, below).
Who applies the rule. It is the database: the migrations write the
rule in the constraint, so it holds for every deletion, through rind or
through psql. rind also reads it when the API deletes an object, to say
what goes with it (Deleting through the API).
When the key is checked: deferred
#![allow(unused)]
fn main() {
#[fk(Tag, on_delete = restrict, deferred)]
pub reviewer_id: Option<i64>,
// … FOREIGN KEY ("reviewer_id") REFERENCES "lab_tag" ("id") ON DELETE RESTRICT DEFERRABLE INITIALLY DEFERRED;
}
By default PostgreSQL checks a key at each statement. A deferred key is
checked when the transaction commits. This allows, inside one
transaction, a moment where the key points to a row that does not exist
yet: two rows that point to each other, inserted one after the other.
Django creates all its keys deferred. Use deferred to describe a Django
database exactly, or when you need the moment above.
No index: unindexed
#![allow(unused)]
fn main() {
#[fk(Tag, unindexed)]
pub other_id: Option<i64>,
// … FOREIGN KEY ("other_id") REFERENCES "lab_tag" ("id"); and no CREATE INDEX
}
Every key gets an index, because a key is almost always filtered on (the wagons of a train), and because deleting the target must find the rows that point to it. Leave it out only for a key that is never searched and whose target is never deleted, on a large table where the index costs.
Rules kept in code: in_code
#![allow(unused)]
fn main() {
#[fk(Tag, on_delete = cascade, in_code)]
pub coded_id: Option<i64>,
// … FOREIGN KEY ("coded_id") REFERENCES "lab_tag" ("id"); no ON DELETE
}
in_code keeps the rule out of the database: the constraint has no ON DELETE clause, but rind’s deletions (the API’s, delete_cascade) still
follow on_delete.
This is for a database that Django made. Django never writes its
on_delete rules in the database: it applies them in Python, before it
deletes. To describe such a database exactly, and to delete as Django
would, write the rule with in_code:
#![allow(unused)]
fn main() {
#[fk(GeoCountry, on_delete = set_null, in_code, deferred)]
pub country_id: Option<i64>,
}
The migrations then match the database as it is. In a new database, prefer real rules: they protect the data from every program.
Names of the constraint and the index
The constraint is named <table>_<column>_fkey, and its index
<table>_<column>_idx. A database made by another tool has other names;
give them so that rind’s migrations and checks match:
#![allow(unused)]
fn main() {
#[fk(Station, on_delete = restrict, constraint = "fleet_train_depot_fk", index = "fleet_train_depot_ix")]
pub depot_id: i64,
}
See Migrations.
One-to-one relations
Django’s OneToOneField is a foreign key whose column is unique. Write
exactly that:
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "lab_profile")]
pub struct Profile {
pub id: i64,
#[fk(Tag, on_delete = cascade)]
#[column(unique)]
pub tag_id: i64,
}
}
"tag_id" bigint NOT NULL CONSTRAINT "lab_profile_tag_id_key" UNIQUE
(The key also gets its usual index, which the unique constraint makes unnecessary.)
A model that points to itself
A key may point to its own model: a region inside a region, an employee and their manager.
#![allow(unused)]
fn main() {
#[fk(Region, on_delete = cascade)]
pub parent_id: Option<i64>,
}
When the key is the parent of a hierarchy, declare it as a tree too, to get the recursive queries.
A model that points twice to the same model
A journey has an origin and a destination, both stations:
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-models/src/lib.rs
#[fk(Station, on_delete = restrict, reverse = departures)]
pub origin_id: i64,
#[fk(Station, on_delete = restrict, reverse = arrivals)]
pub destination_id: i64,
}
The relations are origin and destination. On the way back, each key
gives the station a relation of its own name, departures and
arrivals: see Reverse relations.
A key to a model this crate cannot name
The domains are ordered, and a crate can only use the crates before it. A key that must point up, to a model of a later domain, is written with the name of the table instead of the model:
#![allow(unused)]
fn main() {
// network-models: a station's manager is a user, declared in a later domain
#[fk(table = "accounts_user", on_delete = set_null)]
pub manager_id: Option<i64>,
}
The relation is then declared where both models are known. Organising
an application explains it, with the
keys key, external and unfollowed.
Summary
| Key | What it does |
|---|---|
Target (first) | the model the key points to |
name = relation | the relation’s name, when it is not the field without _id |
on_delete = cascade | set_null | restrict | what a deletion of the target does to this row |
reverse = relation | the relation the target gets back (Reverse relations) |
deferred | checked at commit: DEFERRABLE INITIALLY DEFERRED |
unindexed | no index |
in_code | the rule is applied by rind, not written in the database |
constraint = "…", index = "…" | the names an existing database gives them |
table = "…" (first), key, external, unfollowed | a key to a table this crate cannot name (Organising an application) |
Next: Reverse and many-to-many relations.
Reverse and many-to-many relations
A foreign key goes from one model to another: a wagon has a train. This
page shows the two other kinds of relations:
- the reverse of a foreign key, which goes the other way: a train has
wagons; - the many-to-many relation, through a link table: a user has
groups, and a group has users.
Why rind asks you to declare the way back
In Django, ForeignKey(Train) on Wagon silently gives every train a
wagon_set (or the related_name). rind gives nothing back unless you
ask. There are two reasons:
- Nothing is implicit. Reading
Train, you see every relation it has. - Crates have an order.
fleet-modelscannot add a function toStation, which lives innetwork-models, unless it does so in a way Rust allows: a trait. The two ways to declare a reverse relation follow from that.
On the target: #[reverse(..)]
When the target model’s crate can name the model that holds the key (both are in the same crate, or the target’s crate depends on the other), declare the relation on the target’s struct:
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
#[derive(Debug, Clone, Model)]
#[model(table = "fleet_train")]
#[reverse(name = wagons, model = Wagon, fk = "train_id")]
pub struct Train { … }
#[derive(Debug, Clone, Model)]
#[model(table = "fleet_wagon")]
pub struct Wagon {
pub id: i64,
#[fk(Train, on_delete = cascade)]
pub train_id: i64,
// …
}
}
| Key | What it is |
|---|---|
name | the relation’s name: Django’s related_name |
model | the model that holds the key |
fk | the column of that model that points here, as a string |
Train::wagons() is now a path, used like any other:
#![allow(unused)]
fn main() {
// the trains with at least 8 wagons
Query::<Train>::new().filter(Train::wagons().count().ge(8))
// the trains that have a sleeper wagon
Query::<Train>::new().filter(Train::wagons().any(|w| w.kind().eq("sleeper")))
}
A reverse relation is a many relation: a train has several wagons. It
is followed with any, count, sum and the other functions of
Filtering through a many relation,
never by a plain .kind(), which would not say which wagon.
The reverse relation adds nothing to the database: it is the same foreign key, walked the other way.
On the key: reverse = …
Often the target cannot name the model that holds the key. A Station
(in network-models) cannot name a Journey (in timetable-models,
which comes after). Then the foreign key gives the relation back itself:
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-models/src/lib.rs
pub struct Journey {
// …
#[fk(Station, on_delete = restrict, reverse = departures)]
pub origin_id: i64,
#[fk(Station, on_delete = restrict, reverse = arrivals)]
pub destination_id: i64,
}
}
The derive writes a trait, named <Target><Relation>, here
StationDepartures and StationArrivals, with the function
departures(), and implements it for Station. Code that follows the
relation imports the trait:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/serializers.rs
use timetable_models::StationDepartures as _;
Query::<Station>::new().filter(Station::departures().count().ge(2))
}
as _ imports the trait without giving it a name in the file: only its
functions are needed.
The import is needed even in the crate that declares the key. If you forget it, the compiler tells you which trait to import:
error[E0599]: no associated function or constant named `notes` found for struct `Tag` in the current scope
|
| Query::new().filter(Tag::notes().count().ge(2))
| ^^^^^ associated function or constant not found in `Tag`
|
= help: items from traits can only be used if the trait is in scope
help: trait `TagNotes` which provides `notes` is implemented but not in scope; perhaps you want to import it
|
+ use crate::TagNotes;
The derive also writes <Target>Path<Relation> (StationPathDepartures),
which lets a relation be followed from a path, inside a closure. When you
use it that way, import that trait too.
Which one to use
| Situation | Use |
|---|---|
| both models in the same crate | #[reverse(..)] on the target: no import needed |
| the key’s crate comes after the target’s | reverse = … on the key, and import the trait where it is used |
Two keys to the same model
A journey points twice to the stations. Each key gives its own reverse
relation, with its own name: a station has departures and arrivals.
Two relations with the same name on a model are refused when the code
compiles.
Many-to-many relations
A user belongs to several groups, and a group has several users. The relation goes through a link table, with one row per pair:
#![allow(unused)]
fn main() {
// sample/crates/accounts/accounts-models/src/lib.rs
#[derive(Debug, Clone, Model)]
#[model(table = "accounts_user")]
#[m2m(name = groups, model = Group, through = "accounts_user_groups",
from = "user_id", to = "group_id")]
pub struct User { … }
}
| Key | What it is |
|---|---|
name | the relation’s name |
model | the model at the other end |
through | the name of the link table |
from | the link table’s column that points to this model |
to | the link table’s column that points to the other model |
This is Django’s ManyToManyField. Django names the link table
<app>_<model>_<field>; rind asks you for the name, so that a Django
database is described as it is.
The link table
The link table has no model of its own: the migrations make it from the
declaration. For an Article with tags:
#![allow(unused)]
fn main() {
#[m2m(name = tags, model = Tag, through = "lab_article_tags", from = "article_id", to = "tag_id")]
pub struct Article { … }
}
CREATE TABLE "lab_article_tags" (
"id" bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
"article_id" bigint NOT NULL,
"tag_id" bigint NOT NULL
);
ALTER TABLE "lab_article_tags" ADD CONSTRAINT "lab_article_tags_article_id_tag_id_key" UNIQUE ("article_id", "tag_id");
ALTER TABLE "lab_article_tags" ADD CONSTRAINT "lab_article_tags_article_id_fkey" FOREIGN KEY ("article_id") REFERENCES "lab_article" ("id") ON DELETE CASCADE;
CREATE INDEX "lab_article_tags_article_id_idx" ON "lab_article_tags" ("article_id");
ALTER TABLE "lab_article_tags" ADD CONSTRAINT "lab_article_tags_tag_id_fkey" FOREIGN KEY ("tag_id") REFERENCES "lab_tag" ("id") ON DELETE CASCADE;
CREATE INDEX "lab_article_tags_tag_id_idx" ON "lab_article_tags" ("tag_id");
It is the table Django makes: an id, the two keys, each pair once, and
the links deleted with either end.
When the links carry data of their own (the date a user joined a group,
a role), the link is a model of its own, with two foreign keys: Django’s
through= model. Declare it as a normal model, and its two keys give the
relations.
Following it in queries
#![allow(unused)]
fn main() {
// the articles tagged "rust"
Query::<Article>::new().filter(Article::tags().any(|t| t.name().eq("rust")))
}
Like a reverse relation, a many-to-many relation is followed with any,
count and the other functions of a many relation. The filter is an
EXISTS: an article with two matching tags appears once, without a
.distinct().
The other side
The m2m attribute gives the relation to the model that declares it,
and only to it: User::groups() exists, Group::users() does not.
For the other side, query from the side that has the relation. The users of a group are the users whose groups include it:
#![allow(unused)]
fn main() {
// the users of the group "drivers"
Query::<User>::new().filter(User::groups().any(|g| g.slug().eq("drivers")))
}
Watch out: declaring a second
#[m2m(..)]onGroupwith the same link table,fromandtoswapped, compiles, but the two declarations disagree on the link table’s unique constraint ((user_id, group_id)against(group_id, user_id)), andrind makethen wants to drop and re-create it. Declare a many-to-many relation on one side only.
Adding and removing links
#![allow(unused)]
fn main() {
db.link(&ARTICLE_TAGS, article.id, tag.id).await?; // true: added
db.link(&ARTICLE_TAGS, article.id, tag.id).await?; // false: it was there already
db.unlink(&ARTICLE_TAGS, article.id, tag.id).await?; // true: removed
}
These are Django’s article.tags.add(tag) and .remove(tag).
ARTICLE_TAGS is the relation’s hop: a constant the derive writes for
each relation, named <MODEL>_<RELATION> in capitals. Loaders take it
too, to read the tags of a whole page of articles in one query
(Queries).
In the API, a serializer sends the ids of a many-to-many relation with
#[m2m_ids], and an input writes them.
Next: Trees.
Trees
Some tables hold a hierarchy: regions inside regions, categories inside categories, the folders of a file system. Each row has a parent, which is a row of the same table. rind calls such a model a tree.
In Django, you would use django-mptt or django-treebeard, which add
columns (lft, rght, path, depth) and keep them up to date at
every write. rind adds nothing to the table: it walks the parent column
with PostgreSQL’s recursive queries (WITH RECURSIVE), when you ask.
Declaring a tree
A tree is a model with a foreign key to itself, and tree = "…" naming
that key:
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
#[derive(Debug, Clone, Model)]
#[model(table = "network_region", tree = "parent_id")]
#[reverse(name = children, model = Region, fk = "parent_id")]
pub struct Region {
pub id: i64,
#[column(max_length = 100)]
pub name: String,
/// The region it is part of; none for a country.
#[fk(Region, on_delete = cascade)]
pub parent_id: Option<i64>,
// …
}
}
parent_idis an ordinary foreign key, nullable: the roots of the tree (here, the countries) have no parent.tree = "parent_id"gives the model the tree functions below.#[reverse(name = children, ..)]is optional: it gives the relation to the direct children,Region::children(), as for any foreign key.on_delete = cascadedeletes a region’s sub-regions with it. Chooserestrictif a region with children must not be deleted.
A table can have several roots (France and Italia): it is then a forest, and each walk stays inside its own tree.
The sample’s data
The examples below use these regions:
1 France
├── 2 Bretagne
│ └── 3 Finistère
└── 4 Occitanie
5 Italia
A region and everything below it
The most common question: “the stations of Bretagne, including those of
its sub-regions”. subtree(id) is the keys of a region and of every
region below it, ready for in_sub:
#![allow(unused)]
fn main() {
// the stations of Bretagne, or of any region inside it
Query::<Station>::new().filter(Station::region_id().in_sub(Region::subtree(2)))
}
It is a sub-query, so it goes anywhere a condition goes. The tree is walked once per request, however deep it is.
Options narrow the walk:
#![allow(unused)]
fn main() {
Region::subtree(1).max_down(1) // France and its direct children: 1, 2, 4
Region::subtree(1).without_self() // strictly below France: 2, 3, 4
Region::subtree(vec![1, 5]).at_level(1) // the level-1 regions of France and Italia: 2, 4
}
A region and everything above it
ancestry(id) goes up instead: a region, its parent, and so on to the
root.
#![allow(unused)]
fn main() {
Region::id().in_sub(Region::ancestry(3)) // Finistère, Bretagne, France
Region::id().in_sub(Region::ancestry(3).max_up(1)) // Finistère and Bretagne
}
Starting from a condition
A walk can start from the rows that match a condition rather than from keys:
#![allow(unused)]
fn main() {
// the stations whose region, or one of the regions above it, is called "Bretagne"
Station::region_id().in_sub(Region::subtree_where(Region::name().eq("Bretagne")))
}
“Its region or one above it matches” is the same as “its region is below a region that matches”, and the second is much faster: one walk down from the matching regions, instead of a walk up from every station.
A path, for a breadcrumb
paths reads, for some rows, their ancestors from the root down, with
one column of each, in one query:
#![allow(unused)]
fn main() {
let paths = Region::paths(&db, vec![3, 4], Region::name()).await?;
// paths[&3]: [(1, "France"), (2, "Bretagne"), (3, "Finistère")]
// paths[&4]: [(1, "France"), (4, "Occitanie")]
}
It is what a “France › Bretagne › Finistère” field of a serializer needs.
The whole tree, in order
tree(order) gives every row with its depth and its path, to list a tree
depth-first, siblings ordered by an expression:
#![allow(unused)]
fn main() {
let tree = Region::tree_by_text(Region::name().expr());
let select = Query::<Region>::new()
.with_tree(&tree)
.select((Region::id(), tree.depth(), tree.path()))
.order_by([tree.asc()])
.into_select();
let rows: Vec<(i64, i64, Vec<i64>)> = db.rows(&select).await?;
// [(1, 0, [1]), (2, 1, [1, 2]), (3, 2, [1, 2, 3]), (4, 1, [1, 4]), (5, 0, [5])]
}
tree_by_text turns the ordering expression into text first, which a
character varying column needs.
Every function
| Function | Gives |
|---|---|
subtree(start) | the keys of the rows and every row below them, for in_sub |
subtree_where(cond) | the same, starting from the rows that match cond |
ancestry(start) | the keys of the rows and every row above them |
ancestry_where(cond) | the same, starting from the rows that match cond |
descendants(id), descendants_of(ids), ancestors_of(ids) | the same walks as common table expressions (CTEs), to join |
tree(order), tree_by_text(order) | every row with depth(), path() and an order |
paths(&db, ids, column) | each row’s ancestors from the root, with a column of each |
The options of a walk (max_down, max_up, at_level, down_to_level,
up_to_level, without_self, stop_at, with_start) and the CTE
functions are explained in Queries: trees.
Mistakes in the data
A row that is, by mistake, its own ancestor (1 → 2 → 1) would make a
naive recursive query run forever. rind’s walks stop when they meet a row
again. Such a row has no level, so it is left out of the walks that use
levels (at_level, down_to_level).
To prevent the mistake, check it in the input that changes a parent: the new parent must not be in the row’s own subtree.
Next: Indexes and constraints.
Indexes and constraints
Indexes and constraints are part of the model, like its columns. The
migrations write them, so nothing about the schema lives only in a
migration file, and rind check notices when the model and the
migrations disagree.
Column options showed the simple cases, on one
column (#[column(unique)], #[column(index)]). This page shows the
attributes written on the struct, for everything else:
| Attribute | What it is | Django |
|---|---|---|
#[index(on(a, b))] | an index on several columns | Meta.indexes = [Index(fields=[…])] |
#[index(name, sql)] | an index on an expression, partial, GIN… | Index(expressions…, condition=…), GinIndex |
#[unique(on(a, b))] | columns unique together | UniqueConstraint(fields=[…]), unique_together |
#[check(name, sql)] | a condition every row must meet | CheckConstraint |
The examples come from one model:
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "lab_article")]
#[index(on(author_id, published))]
#[index(name = "lab_article_title_lower_idx", sql = "(lower(title))")]
#[index(name = "lab_article_one_draft_idx", unique, sql = "(author_id) WHERE NOT published")]
#[index(name = "lab_article_words_idx", sql = "USING gin (words)")]
#[unique(on(author_id, title))]
#[unique(name = "lab_article_ref_uniq", on(reference, version), nulls_not_distinct)]
#[check(name = "lab_article_version_check", sql = "version > 0")]
pub struct Article {
pub id: i64,
pub title: String,
pub published: bool,
pub words: Vec<String>,
pub reference: Option<String>,
pub version: i32,
#[fk(Tag, on_delete = cascade)]
pub author_id: i64,
}
}
An index on several columns
#![allow(unused)]
fn main() {
#[index(on(author_id, published))]
}
CREATE INDEX "lab_article_author_id_published_idx" ON "lab_article" ("author_id", "published");
An index on (a, b) helps the queries that filter on a, or on a and
b. The order of the columns matters: put first the column the queries
always filter on.
The name is <table>_<columns>_idx. Give name = "…" to describe an
existing database whose index has another name.
An index written in SQL
An index that a list of columns cannot describe is written in SQL. sql
is what follows ON <table> in CREATE INDEX, and such an index must
have a name:
#![allow(unused)]
fn main() {
// an index on an expression: for filters on lower(title)
#[index(name = "lab_article_title_lower_idx", sql = "(lower(title))")]
// CREATE INDEX "lab_article_title_lower_idx" ON "lab_article" (lower(title));
// a GIN index on an array: for "contains" and "overlaps" filters
#[index(name = "lab_article_words_idx", sql = "USING gin (words)")]
// CREATE INDEX "lab_article_words_idx" ON "lab_article" USING gin (words);
}
With unique, it is a unique index. Combined with a WHERE, it makes a
partial uniqueness: here an author may have only one draft at a time,
but any number of published articles:
#![allow(unused)]
fn main() {
#[index(name = "lab_article_one_draft_idx", unique, sql = "(author_id) WHERE NOT published")]
// CREATE UNIQUE INDEX "lab_article_one_draft_idx" ON "lab_article" (author_id) WHERE NOT published;
}
The sample uses one so that a seat is booked once per journey, the cancelled reservations left aside:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-models/src/lib.rs
#[index(
name = "booking_reservation_seat_idx",
unique,
sql = "(journey_id, wagon_id, seat) WHERE status = 'booked' AND seat IS NOT NULL"
)]
}
Other common indexes, written the same way:
| Index | sql = … |
|---|---|
a trigram index, for searches with contains | "USING gin (upper(name) gin_trgm_ops)" (extension pg_trgm) |
| a spatial index | "USING gist (position)" |
| a full-text index | "USING gin (to_tsvector('french', title))" |
| a descending index | "(created DESC)" |
An index that needs an extension needs the extension declared on the
domain: rind::migrations::domain!("network", schema()).extension("pg_trgm").
Unique together
#![allow(unused)]
fn main() {
#[unique(on(author_id, title))]
}
ALTER TABLE "lab_article" ADD CONSTRAINT "lab_article_author_id_title_key" UNIQUE ("author_id", "title");
Two articles of the same author cannot have the same title; two authors
can. This is Django’s UniqueConstraint(fields=["author", "title"]) (or
the older unique_together). The sample uses it so that each place of a
train has one wagon:
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-models/src/lib.rs
#[unique(on(train_id, position))]
pub struct Wagon { … }
}
NULLs. By default PostgreSQL counts each NULL as different: two
rows (NULL, 1) do not break the constraint. nulls_not_distinct
counts them as equal (PostgreSQL 15 and later):
#![allow(unused)]
fn main() {
#[unique(name = "lab_article_ref_uniq", on(reference, version), nulls_not_distinct)]
// ALTER TABLE "lab_article" ADD CONSTRAINT "lab_article_ref_uniq" UNIQUE NULLS NOT DISTINCT ("reference", "version");
}
The derive checks the names of the columns:
error: the model has no column `nope`
|
| #[unique(on(id, nope))]
| ^^^^
When a write through the API breaks the constraint, the answer is a 400. To have the message on a field, declare the uniqueness on the input too.
Checks
#![allow(unused)]
fn main() {
#[check(name = "lab_article_version_check", sql = "version > 0")]
}
ALTER TABLE "lab_article" ADD CONSTRAINT "lab_article_version_check" CHECK (version > 0);
A check constraint is a condition, in SQL, that every row must meet:
Django’s CheckConstraint(condition=Q(version__gt=0)). The condition can
use every column of the row, not the other rows.
name and sql are both required. A write that breaks it is refused by
the database:
database: ERROR: new row for relation "lab_article" violates check constraint "lab_article_version_check"
Through the API, it is a 400. Checks are the place for rules that must
hold whoever writes: a positive number ("capacity > 0"), an order
between two dates ("arrives_at > departs_at"), a value in a list
("status IN ('draft', 'sent', 'paid')").
Names an existing database already has
Every constraint and index rind writes has a name, built from PostgreSQL’s
conventions (_key, _idx, _fkey, _pkey). To describe a database
made by Django or by hand, give each its existing name, so that the
migrations do not rename it: name = "…" on these attributes,
unique = "…" and index = "…" on columns, constraint and index on
foreign keys, key_name on the model. rind constraints lists those that
differ. See Migrations.
Next: Scopes and scoped models.
Scopes and scoped models
A scope is a named query on a model: “the open loans”, “the stations of
a region”, “the reservations a user made”. In Django you would write a
method on a custom manager or a queryset, Loan.objects.open(). In rind
it is a plain function on the model that returns a Query.
This page shows how to write scopes, how to combine them, and what a scoped model is: a model that has no default query at all.
A first scope
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-models/src/lib.rs
impl Reservation {
/// The reservations a user made.
pub fn made_by(user: &Identity) -> Query<Reservation> {
Query::new().filter(Reservation::booked_by_id().eq(user.id))
}
}
}
There is nothing special about it: an associated function, in the model’s crate, that builds a query. It does not run anything. The caller runs it, or narrows it further:
#![allow(unused)]
fn main() {
// every reservation of the user
let all = db.all(&Reservation::made_by(&user)).await?;
// only the booked ones, newest first
let booked = Reservation::made_by(&user)
.filter(Reservation::status().eq("booked"))
.order_by([Reservation::created().desc()]);
let page = db.all(&booked.limit(20)).await?;
}
A Query is a value: filtering it gives a new query, and the scope
itself is not changed.
Why scopes are worth writing
- They have a name.
Loan::open()says what it means; a filter onreturned_on IS NULLrepeated in ten places does not, and one of the ten will be wrong. - They are tested without HTTP. A scope is a function: a test builds a few rows, runs the scope and checks what comes back.
- The API uses them. A permission mode is a
scope:
#[mode(LoanMode::Own, query = Loan::of(user))]. So is a filter’s method, and a nested field’s query. - They live with the model. Every crate that uses the model gets the same definition.
Scopes with parameters
A scope takes what it needs as arguments: a user, an id, a date.
#![allow(unused)]
fn main() {
impl Station {
/// The stations of a region, or of any region inside it.
pub fn in_region(region: i64) -> Query<Station> {
Query::new().filter(Station::region_id().in_sub(Region::subtree(region)))
}
/// The stations opened on or before a day.
pub fn opened_by(day: NaiveDate) -> Query<Station> {
Query::new().filter(Station::opened().le(day))
}
}
}
Combining scopes
A scope returns a Query, and a query takes more filters, but two
queries cannot be merged into one. To combine scopes, write the
conditions as functions too, and build the queries from them:
#![allow(unused)]
fn main() {
impl Loan {
/// Not given back yet.
pub fn is_out() -> Cond {
Loan::returned_on().is_null()
}
/// The loans not given back yet.
pub fn out() -> Query<Loan> {
Query::new().filter(Loan::is_out())
}
/// A user's loans not given back yet.
pub fn out_for(user: &Identity) -> Query<Loan> {
Loan::of(user).filter(Loan::is_out())
}
}
}
A Cond (a condition) combines with & (and), | (or) and ! (not),
like Django’s Q objects: see Queries.
Scoped models
Some tables hold rows that most code must not read: drafts, rows waiting for a validation, rejected imports, soft-deleted rows. In Django you give the model a default manager that filters them out:
class Loan(models.Model):
objects = OpenLoanManager() # hides the returned loans
all_objects = models.Manager()
and you hope nobody uses Loan._base_manager, a related manager, or the
admin, which do not use your default manager.
In rind, you mark the model scoped. It then has no default query:
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Model)]
#[model(table = "library_loan", scoped)]
pub struct Loan {
pub id: i64,
pub returned: bool,
// …
}
impl Loan {
/// The loans not returned yet.
pub fn open() -> Query<Loan> {
Query::all().filter(Loan::returned().eq(false))
}
}
}
Query::<Loan>::new(), which reads every row of an ordinary model, does
not compile for a scoped one:
error[E0277]: `Loan` is a scoped model: it has no default query
|
| Query::<Loan>::new()
| ^^^^^^^^^^^^^^^^^^^^ use one of the scopes `Loan` defines, or `Query::all()` for every row
Every use of the model must say what it reads:
- one of its scopes,
Loan::open(); - or
Query::all(), when it really means every row: a report, a migration of data, an admin tool.all()is easy to find in a review.
Scopes of a scoped model start from Query::all(), since Query::new()
is not available to them either.
Coming from Django: a default manager filters silently, and is bypassed silently. A scoped model never filters by itself: every query names its scope in the code, so a reader sees what is read, and a forgotten filter is a compile error.
Where the compiler stops, and where it does not
scoped protects the queries that start from the model. A query that
reaches the model through a relation (Book::loans().any(..)) or a
nested field of a serializer also reads its rows. Give those a query too:
a nested field of a scoped model needs query = Loan::open(), and the
derive refuses it otherwise (Serializers).
Scopes and the API
The rows a resource works on are a scope as well, given in one of two places:
#[resource(.., query = Loan::open())]makes every request of the resource start from a scope: Django’s viewsetqueryset =;- or, when the resource has permission modes,
each mode gives its own:
#[mode(.., query = Reservation::made_by(user))]. The two are exclusive: with modes, a resource’squeryis refused, and each mode must have one.
Without either, the resource reads Query::new(), every row; for a
scoped model that does not compile, so its resource must say which rows
it serves. A query that uses user matches no row for an anonymous
request.
Next: Sharing fields.
Sharing fields
Several models often have the same fields: created and updated on
every table, an image with its width and height, the columns a user
model needs to sign in. In Django you write them once in an abstract
model or a mixin, and inherit from it:
class Tracked(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Shelf(Tracked):
name = models.CharField(max_length=100)
Rust structs have no inheritance. rind has field groups instead: fields written once, and pasted into each struct that asks for them, before the derives read the struct.
Defining a group
#![allow(unused)]
fn main() {
rind::field_group! {
tracked {
#[column(default = "now()")]
pub created: DateTime<Utc>,
#[column(default = "now()")]
pub updated: DateTime<Utc>,
}
}
}
field_group! takes a name, tracked, and a list of fields written
exactly as in a struct, with their attributes and doc comments.
Using it
#![allow(unused)]
fn main() {
#[rind::with_fields(tracked)]
#[derive(Debug, Clone, Model)]
#[model(table = "shelf")]
pub struct Shelf {
pub id: i64,
#[column(max_length = 100)]
pub name: String,
}
}
#[rind::with_fields(tracked)] adds the group’s fields at the end of the
struct. For the derive, and for the rest of your code, Shelf simply has
four fields: id, name, created and updated. It has the columns,
the paths (Shelf::created()), and the migrations create them.
Write with_fields above the derives. Attributes run from top to
bottom: the fields must be in the struct before #[derive(Model)] reads
it. Below the derive, the fields would arrive too late, and the derive
would not see them.
Several groups can be included at once: #[rind::with_fields(tracked, flags)].
Groups across crates
A group is visible in its own crate. Written pub, it can be used from
other crates, by its path:
#![allow(unused)]
fn main() {
// in a crate `common-models`
rind::field_group! {
pub tracked { … }
}
// in another crate
#[rind::with_fields(common_models::tracked)]
#[derive(Debug, Clone, Model)]
pub struct Shelf { … }
}
(A group is a macro behind the scenes, so it can also be imported with
use common_models::tracked; and named alone.)
Groups that rind gives
| Group | Fields | For |
|---|---|---|
rind::behaviours::tracking | created, updated (timestamp with time zone, default now()) | the Tracking behaviour |
rind::behaviours::flags | flags (character varying(30)[], default '{}') | the Flags behaviour |
rind::behaviours::content | content_src, content_html (text, default '') | the Content behaviour (markdown) |
rind::images::image | image (a File), image_width, image_height | Images |
rind_auth::user_base | password, last_login, is_active | Signing in: Django’s AbstractBaseUser |
The sample’s user model, for example:
#![allow(unused)]
fn main() {
// sample/crates/accounts/accounts-models/src/lib.rs
#[rind::with_fields(rind_auth::user_base)]
#[derive(Debug, Clone, Model)]
#[model(table = "accounts_user")]
pub struct User {
pub id: i64,
pub username: String,
// … and `password`, `last_login`, `is_active` from the group
}
}
A behaviour checks, when the application compiles, that the model has the columns it needs. Including its group is the easy way to have them.
Not only for models
A field group is a list of fields, and any struct can include it. The
same mechanism works for filtersets,
serializers and inputs: the filters
every list of located objects has, the output fields that go with
tracked.
A group can leave a name open, given by each struct that includes it. This is how a group of filters can name the paths of a model it does not know:
#![allow(unused)]
fn main() {
rind::field_group! {
location_filters {
#[filter(path = Root::location().city())]
pub city: Option<String>,
}
}
#[rind::with_fields(location_filters(Root = Storage))]
#[derive(Debug, Default, FilterSet)]
#[filterset(model = Storage)]
pub struct StorageFilters {
#[filter(path = Storage::status())]
pub status: Option<String>,
}
}
Root = Storage replaces Root by Storage in the group’s fields.
What a group cannot do
- It adds fields only: not attributes of the struct
(
#[model(..)],#[index(..)],#[reverse(..)]). Write those on each model. - It cannot add methods. Write a trait, or functions, for shared code.
- Two groups, or a group and the struct, cannot define the same field.
Coming from Django: there is no table for the group and no inheritance between models:
Shelfis not aTracked. Django’s multi-table inheritance (a child table with a one-to-one key to its parent) has no equivalent; write the two models and the one-to-one key yourself.
Next: Writing objects.
Writing objects
The Model derive gives each object its own writes: insert, save,
update, refresh, delete. They are Django’s obj.save(),
obj.save(update_fields=[…]), obj.refresh_from_db() and
obj.delete().
They are for code that runs outside a request: an operation of an
ops crate, a job, a command, a test, an import. Writes
through the API go through a resource and its
input, which validate and check permissions; these do
neither.
There is a second way to write: statements on rows, Insert, Update
and Delete, run by the database (Writing rows).
The difference is explained at the end of this page.
A first example
#![allow(unused)]
fn main() {
// sample/tests/model_writes.rs
let mut station = brest.clone();
station.code = "BRE2".into();
let mut station = station.insert(&db).await?; // the row back, with its new id
station.name = "Brest Saint-Marc".into();
station.save(&db).await?; // every column, by the key
station.city = "Plouzané".into();
station.update(&db, &[StationColumn::City]).await?; // only this column
station.refresh(&db).await?; // read it again
station.delete(&db).await?; // one DELETE
}
Each method takes a &Db: the pool’s, or a transaction’s.
insert: a new row
#![allow(unused)]
fn main() {
let tag = Tag { id: 0, name: "rust".into() }.insert(&db).await?;
// Tag { id: 1, name: "rust" }
}
insert writes every column of the object, except:
- an identity key (the usual
id), which the database gives; - generated columns and columns read through SQL.
It answers the row as the database stored it: with its new key, and the values the database computed. The object you called it on is consumed; use the one it answers.
A key of a manual_key
model is written: Country { code: "FR".into(), .. }.insert(&db).
Since every column is written, the columns’ SQL defaults are not used.
To let the database fill a default, insert with Insert and leave the
column out (column defaults).
save: every column, by the key
#![allow(unused)]
fn main() {
tag.name = "Rust".into();
tag.save(&db).await?;
}
save writes every column (except the key, generated and read ones) to
the row that has the object’s key, then reads the row again into the
object. A row that is not there is Error::NotFound: save never
inserts. (Django’s save() inserts or updates depending on the key; in
rind you say which one you mean.)
Watch out:
savewrites every column. An object read partially (the serializers read only the columns their fields need) holds default values in the fields that were not read, andsavewould write those defaults over the real values. When you did not read the whole row, useupdatewith the columns you changed.
update: some columns
#![allow(unused)]
fn main() {
tag.name = "RUST".into();
tag.update(&db, &[TagColumn::Name]).await?;
}
update writes only the columns named, then reads the row again. This is
Django’s save(update_fields=["name"]).
The columns are the variants of an enum the derive writes for each
model, <Model>Column, with one variant per column, in CamelCase:
TagColumn::Name, StationColumn::City. A wrong name does not compile.
Prefer update to save when two programs may change the same row at
the same time: each writes only what it changed.
refresh: read the row again
#![allow(unused)]
fn main() {
tag.refresh(&db).await?;
}
Reads the row again into the object: Django’s refresh_from_db(). A row
that is gone is Error::NotFound.
delete: remove the row
#![allow(unused)]
fn main() {
let gone: u64 = tag.delete(&db).await?; // 1, or 0 if it was not there
}
One DELETE by the key. The database’s foreign keys decide what goes
with it: a cascade key deletes the rows that point to it, a restrict
key refuses the deletion with an error.
Deleting what depends on an object
A database that Django made has foreign keys that do nothing (Django
applies on_delete in Python). On such a database, delete alone fails,
or leaves rows that point nowhere. delete_cascade does what Django’s
delete() does:
#![allow(unused)]
fn main() {
let gone = journey.delete_cascade(&db, &app.schema()).await?;
}
It deletes the object and, table by table, what the models say depends on
it, following each relation’s on_delete as a
deletion through the API does. A relation with
on_delete = restrict refuses the whole deletion. It answers what went,
table by table.
The second argument is the list of the application’s tables, which it
needs to find the keys that point to the object: app.schema(), or
ctx.tables() inside a request. delete_cascade exists only for a model
whose key is an i64.
In a transaction
Each method runs in what its Db is. Several writes that must succeed
or fail together go in a transaction:
#![allow(unused)]
fn main() {
let tx = db.begin().await?;
let train = train.insert(tx.db()).await?;
for wagon in wagons {
Wagon { train_id: train.id, ..wagon }.insert(tx.db()).await?;
}
tx.commit().await?; // without it, nothing is kept
}
A transaction that is dropped without commit is rolled back. Inside a
request’s write (a resource’s hook), ctx.db is
already the write’s transaction: write with it, and do not begin another
one (rind has no nested transactions).
Writes that skip the model’s behaviours
insert, save and update run the model’s
behaviours and hooks: they set updated,
render a text, move a journey’s stops. The _raw variants do the same
writes without them, and do not read the row again:
| Method | Runs behaviours and hooks | Reads the row again |
|---|---|---|
insert(&db) | yes | yes (it answers it) |
insert_raw(&db) | no | yes (it answers it) |
save(&db) | yes | yes |
save_raw(&db) | no | no |
update(&db, &[…]) | yes | yes |
update_raw(&db, &[…]) | no | no |
Use them for an import that keeps its own times, or to repair data without triggering what a normal write does.
Objects or rows?
The same change can be written on an object, or as a statement on rows:
#![allow(unused)]
fn main() {
// an object
tag.name = "Rust".into();
tag.update(&db, &[TagColumn::Name]).await?;
// rows
db.execute(&Update::<Tag>::new()
.set(Tag::name(), "Rust".to_owned())
.filter(Tag::id().eq(tag.id)))
.await?;
}
| Object writes | Row statements (Insert, Update, Delete) | |
|---|---|---|
| How many rows | one, by its key | any number, by a filter |
| Behaviours and hooks | run | never run |
| Reading back | the object is up to date | insert answers the row; execute the count |
| A value computed by the database | no | yes: .set(Station::platforms(), Station::platforms() + 1) |
| In Django | obj.save() | QuerySet.update(), .delete() |
Use objects for “this train”, rows for “every train of this depot”. As in
Django, where QuerySet.update() sends no signal, a statement on rows
runs none of the model’s hooks.
Every method
| Method | What it does |
|---|---|
insert(&db) | every column but an identity key (a manual_key one is written), generated columns and columns read through SQL; runs behaviours and hooks; answers the row as the database has it |
insert_raw(&db) | the same, without behaviours or hooks |
save(&db) | every column but the key, generated and read ones; runs behaviours and hooks; reads the row again. A row that is not there is Error::NotFound |
save_raw(&db) | the same, without behaviours or hooks, and without reading the row again |
update(&db, &[columns]) | these columns, and what the behaviours add (updated); runs hooks; reads the row again |
update_raw(&db, &[columns]) | the same, without behaviours or hooks, and without reading the row again |
refresh(&db) | reads the row again; Error::NotFound when it is gone |
delete(&db) | one DELETE by the key; runs the deleting hooks before; answers 0 or 1 |
delete_cascade(&db, tables) | the object and what the models say depends on it, table by table; refused by a restrict relation; answers what went. Only for a model whose key is an i64 |
Next: Behaviours and hooks.
Behaviours and hooks
Some things must happen at every write of a model, whoever writes it: set
the time of the last change, render a text into HTML, move a journey’s
stops when its departure moves. Django does this with auto_now, with an
overridden save(), or with signals (pre_save, post_save,
pre_delete).
rind has two tools, listed on the model so that a reader sees them:
| A behaviour | A hook | |
|---|---|---|
| What it changes | the model’s own statement: it adds columns to the insert or the update | other rows, other tables: it runs its own statements |
| When | while the statement is built | after an insert or an update, before a deletion |
| Declared with | #[model(behaviours(..))] | #[model(hooks(..))] |
| In Django | auto_now, auto_now_add, a save() that sets fields | signals, a save() that writes elsewhere |
Both run for the object writes (insert, save, update,
delete) and for every write of a resource of the
model. Neither runs for a statement on rows (db.execute(&Update…)) nor
for the _raw writes.
There are no signals. In Django, any module can connect a receiver to
post_saveof any model, and a reader of the model cannot know what its writes do. In rind, everything a write of a model does is listed on the model.
Behaviours
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
#[rind::with_fields(
rind::behaviours::tracking,
rind::behaviours::flags,
rind::behaviours::content
)]
#[derive(Debug, Clone, Model)]
#[model(
table = "network_line",
behaviours(rind::behaviours::Tracking, rind::behaviours::Content)
)]
pub struct Line { /* … */ }
}
rind has two behaviours for models:
Trackingsetscreatedandupdatedto the current time on an insert, whatever the object held, andupdatedon a save or an update (it adds the column to those written). It is Django’sauto_now_addandauto_now. Its columns come from the field grouprind::behaviours::tracking.Contentrenderscontent_htmlfromcontent_src(markdown) whenevercontent_srcis written. Its columns come fromrind::behaviours::content.
The model must have the columns the behaviour needs; this is checked when the application compiles. Including the behaviour’s field group is the easy way to have them.
The behaviours run in the order they are listed, before the resource’s own behaviours and hooks.
Writing a behaviour
A behaviour of a model is a type that implements
rind::query::ModelBehaviour<M>. It has:
COLUMNS, the columns it needs, checked when the application compiles;inserting, which receives theInsertstatement being built and may add values to it;updating, which does the same for anUpdate.
A behaviour that needs the request (the user who writes), or that adds
filters and routes to the API (Flags’ actions, Images), is a
resource behaviour instead: see Behaviours.
Hooks
When a journey’s departure moves, its stops must move by as much. That is a write elsewhere, so it is a hook:
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-models/src/lib.rs
pub struct MoveStops;
impl rind::db::hooks::ModelHook<Journey> for MoveStops {
/// `updated` compares the departure before and after.
const OLD: bool = true;
async fn updated(db: &Db, old: Option<&Journey>, new: &Journey) -> Result<(), rind::db::Error> {
let Some(old) = old else {
return Ok(());
};
let by = new.departs_at - old.departs_at;
if by.is_zero() {
return Ok(());
}
db.execute_sql(
"UPDATE timetable_stop SET arrives_at = arrives_at + make_interval(secs => $1::float8) \
WHERE journey_id = $2",
&[Value::Float(by.num_seconds() as f64), Value::Int(new.id)],
)
.await?;
Ok(())
}
}
#[model(table = "timetable_journey", hooks(MoveStops))]
pub struct Journey { /* … */ }
}
A hook implements any of three functions; the others do nothing:
| Function | When it runs | Django |
|---|---|---|
inserted(db, new) | after an insert; new is the row as the database has it | post_save with created=True |
updated(db, old, new) | after an update; old is the row before, when the hook’s OLD is true | post_save with created=False |
deleting(db, row) | before a deletion, while the row is still there | pre_delete |
The row before the update: OLD
To compare the row before and after, the hook sets const OLD: bool = true. A model’s save and update then read the row first, with
SELECT … FOR UPDATE, which also locks it until the write commits. A
resource already has that row. Without OLD, old is None and nothing
is read.
In the write’s transaction
What a hook does is kept or dropped with the write. A model with hooks
written through a pool’s Db gets a transaction of its own for the
write and its hooks; given a transaction’s Db, it runs in that
transaction. A model without hooks pays nothing: no row read before, no
transaction.
An error from a hook fails the write: the whole transaction is rolled back.
What runs hooks, and what does not
| Runs hooks | Does not |
|---|---|
insert, save, update, delete | insert_raw, save_raw, update_raw |
delete_cascade, for the object itself | the rows delete_cascade deletes with it |
| every create, update and delete of a resource | a statement: db.execute(&Update…), execute_sql |
A statement is about rows, not about an object, so it runs no hook,
just as Django’s QuerySet.update() sends no signal.
What a hook can reach
A hook is declared in the model’s crate, so it can use only what that
crate sees. A hook of Journey can write timetable_stop with a typed
query, since both models are in the same crate, but a table of a domain
above only by its name, with execute_sql.
When the work belongs to another domain, the hook is the wrong place: call that domain’s function from the operation or the resource hook that does the write.
Model hooks or resource hooks?
A resource has hooks of its own (creating,
updating, saved, deleting), which see the request: the user, the
input. Choose by asking whether the rule depends on the request:
- always true, whoever writes (stops follow their journey): a model hook;
- about this request (the borrower is the signed-in user, a check that needs the input): a resource hook.
Next: Reference.
Reference
Every attribute of a model, and every key, in tables. The other pages of this chapter explain them with examples; the links lead there.
Django’s Meta options and their equivalents
| Django | rind |
|---|---|
db_table | #[model(table = "…")] (required) |
a field with primary_key=True | the field id, or #[model(pk = "…")] (Primary keys) |
ordering | none on the model: a resource’s #[ordering(.., default("…"))] (Filters), or an order_by in a scope |
unique_together, UniqueConstraint | #[unique(on(a, b))] (Indexes and constraints) |
indexes, Index | #[index(on(a, b))], or #[index(name, sql)] |
constraints, CheckConstraint | #[check(name = "…", sql = "…")] |
abstract = True | rind::field_group! and #[rind::with_fields(..)] (Sharing fields) |
| a custom default manager | #[model(scoped)] and the model’s own scopes (Scopes) |
using, database routers | #[model(database = "…")] (Databases) |
help_text | the field’s doc comment |
verbose_name, verbose_name_plural | none |
get_latest_by, default_related_name, permissions | none |
Django’s field options and their equivalents
| Django | rind |
|---|---|
null=True | Option<T> (Fields) |
blank=True | the input’s business |
max_length= | #[column(max_length = n)] |
default=, db_default= | #[column(default = "SQL")] (Column options) |
unique=True | #[column(unique)] |
db_index=True | #[column(index)] |
choices= | the input’s choices(..), or an enum (Types of your own) |
db_column= | none: the field is named as the column |
editable=False | leave the field out of the input |
auto_now, auto_now_add | the Tracking behaviour (Behaviours and hooks) |
GeneratedField | #[column(generated = "SQL")] |
#[model(..)]
| Key | Meaning |
|---|---|
table = "…" | the table’s name (required) |
pk = "…" | the field of the primary key, when it is not id |
manual_key | the inserts give the key: no identity |
key_name = "…" | the name of the primary key’s constraint, when it is not <table>_pkey |
tree = "…" | the column of the parent: the model is a tree |
scoped | no default query: Query::new() does not compile (Scopes) |
database = "…" | the database the table is in, by the name the application gives it |
behaviours(A, B) | what every write of the model runs on its statement |
hooks(A, B) | what every write of an object runs after it (or before a deletion), in this order |
#[column(..)]
| Key | Meaning |
|---|---|
max_length = 200 | the length of a text: character varying(200) |
default = "'open'" | the column’s default, in SQL |
unique, unique = "…" | the column is unique; with a name, the constraint’s name |
index, index = "…" | the column is indexed; with a name, the index’s name |
sql = "geometry(Point,4326)" | the SQL type, when rind cannot tell it |
read = "ST_AsGeoJSON({})::jsonb" | the SQL the column is read through, {} being the column |
generated = "md5(params::text)" | a generated column (GENERATED ALWAYS AS (…) STORED) |
Rust types and SQL types
| Rust | PostgreSQL | Needs sql = … |
|---|---|---|
i64, i32, i16 | bigint, integer, smallint | |
f64, f32 | double precision, real | |
bool | boolean | |
String | text, or character varying(n) with max_length | |
chrono::NaiveDate | date | |
chrono::DateTime<Utc> | timestamp with time zone | |
chrono::NaiveDateTime | timestamp without time zone | |
serde_json::Value | jsonb | |
rind::db::types::File | text, or character varying(n) with max_length | |
Vec<T> | T[] | |
Option<T> | T, nullable | |
Vec<u8> | bytea | yes |
rind::db::types::Decimal | numeric(p, s) | yes |
rind::db::types::Inet | inet | yes |
rind::db::geo::Point, Polygon, MultiPolygon, Geometry, Shape | PostGIS types | yes |
rind::db::types::Vector | vector(n) | yes |
rind::db::types::TsVector | tsvector | yes |
rind::db::types::EnumValue | an enumerated type | yes |
| a type of your own | any | yes (Types of your own) |
#[fk(..)]
| Key | Meaning |
|---|---|
Target (first) | the model the key points to |
name = relation | the relation’s name, when it is not the field without _id |
reverse = relation | the relation the target gets back, as a trait to import (Relations) |
on_delete = … | cascade, set_null or restrict; without it, the deletion is refused while the row points to it |
in_code | the rule is applied by rind’s deletions, not by the database |
deferred | the key is checked at commit (DEFERRABLE INITIALLY DEFERRED) |
unindexed | no index for the key |
constraint = "…", index = "…" | the names the constraint and its index already have (Migrations) |
table = "…" (first), key = "…" | a key to a table this crate cannot name (Organising an application) |
external | with table: the table has no model in the application |
unfollowed | with table: no relation follows the key (models written from a database) |
#[reverse(..)] and #[m2m(..)]
| Attribute | Keys |
|---|---|
#[reverse(..)] | name, model, fk = "<column of the other table>"; forward = relation gives the other model the relation along its key (Organising an application) |
#[m2m(..)] | name, model, through = "<link table>", from = "<its column to this model>", to = "<its column to the target>" |
#[index(..)], #[unique(..)], #[check(..)]
| Attribute | Keys |
|---|---|
#[index(..)] | on(columns), or sql = "…" (what follows ON <table>) with name = "…"; unique (with sql only); name = "…" |
#[unique(..)] | on(columns), name = "…", nulls_not_distinct |
#[check(..)] | name = "…" and sql = "…", both required |
Names rind gives
| Object | Name |
|---|---|
| primary key | <table>_pkey |
| unique column | <table>_<column>_key |
| unique together | <table>_<col1>_<col2>_key |
| index | <table>_<columns>_idx |
| foreign key | <table>_<column>_fkey, and its index <table>_<column>_idx |
| check | the name you give |
What the derive generates
For a model Station with a column city and a relation region:
| Item | What it is |
|---|---|
Station::city() | a Path<String> to the column; an integer column is a Path<i64> whatever its width, a float a Path<f64> |
Station::region() | a path to the related model, from which its columns are reached |
StationPath | the type of a path that ends at a Station; it has any, count, rows and filter for a many relation (Queries) |
STATION_REGION | the relation’s hop, <MODEL>_<RELATION>: what loaders and db.link take |
StationColumn | an enum with a variant per written column, for update |
StationDepartures, StationPathDepartures | the traits a reverse = departures on another model gives (<Target><Relation>) |
Region::subtree() and the other tree functions | only with tree (Trees) |
insert, save, update, refresh, delete, delete_cascade | the object writes |
A field whose name is a Rust keyword, r#type, is the column type and
the path Model::type_().
Error messages of the derive
| Mistake | Message |
|---|---|
an unknown key in #[model(..)] | unknown key: expected `table`, `pk`, `tree`, `database`, `scoped`, `manual_key`, `key_name`, `behaviours` or `hooks` |
an unknown key in #[column(..)] | unknown key: expected `max_length`, `sql`, `default`, `unique`, `index`, `read` or `generated` |
a type rind does not know, without sql | cannot tell the SQL type of this field: give it, #[column(sql = "…")] |
a foreign key field not ending in _id | a foreign key field is named `<relation>_id`, or the relation is given: #[fk(Target, name = relation)] |
a column name in on(..) that does not exist | the model has no column `nope` |
Query::new() on a scoped model | `Loan` is a scoped model: it has no default query |
| a reverse relation used without its trait | no associated function or constant named `notes` found, with a hint naming the trait to import |
Queries
Geography
rind reads and writes PostGIS columns: points, polygons and any other geometry. Queries can filter and order by distance, test whether a shape holds a point, and measure areas. An API can answer GeoJSON for a map.
This is what GeoDjango (django.contrib.gis) and
djangorestframework-gis do for a Django application. rind covers the
common part of it: geographic coordinates in WGS 84 (SRID 4326), stored as
geography, with distances in metres.
The types are in rind::db::geo. The path methods come with the
query layer.
Setting up the database
The database needs the postgis extension. The domain whose models have
geographic columns asks for it in its migrations:
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
pub fn migrations() -> rind::migrations::Domain {
rind::migrations::domain!("network", schema()).extension("postgis")
}
}
The migrations then create the extension before the tables (Migrations).
Geographic columns
A geographic column is a field of one of the rind::db::geo types, with
its SQL type given by sql. rind cannot choose the SQL type by itself: a
point can be a geography or a geometry.
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
pub struct Station {
// …
/// Where it is: a PostGIS point.
#[column(sql = "geography(Point,4326)")]
pub position: Option<rind::db::geo::Point>,
}
pub struct Region {
// …
/// Its outline: a PostGIS multipolygon, GeoJSON in the API.
#[column(sql = "geography(MultiPolygon,4326)")]
pub shape: Option<rind::db::geo::MultiPolygon>,
}
}
Use geography, as here. The query methods below compute on a
geography, in metres, on the spheroid. This is GeoDjango’s
PointField(geography=True).
There is a type for each kind of value:
| Type | Holds | In JSON |
|---|---|---|
Point | a point | {"lng": 2.3212, "lat": 48.8412} |
Polygon | a polygon | GeoJSON: {"type": "Polygon", "coordinates": [[[2.2, 48.8], …]]} |
MultiPolygon | a multipolygon | GeoJSON: {"type": "MultiPolygon", "coordinates": [[[[2.2, 48.8], …]]]} |
Geometry | any geometry: points, lines, polygons, their multiples, collections | any GeoJSON geometry |
Shape | any PostGIS value, kept byte for byte | its EWKB, in hexadecimal |
A Point is sent as an object with lng and lat, which is easier to
read in an API than GeoJSON’s [lng, lat]. The shapes are sent as GeoJSON
geometries. Shape is for a value that must come back exactly as it was
read, whatever it holds.
How values are read and written
rind reads the values as PostGIS sends them, in EWKB (or ISO WKB), from a
geography or a geometry column. A third and a fourth coordinate (Z and
M) are read and dropped. Values are written with the SRID 4326.
What a client may send
A shape that a client sends is checked before the database sees it:
- every longitude is between -180 and 180, every latitude between -90 and 90;
- a line has two positions or more;
- a ring of a polygon has four positions or more, and is closed (its last position is its first).
A wrong shape is the field’s error, and says what is wrong:
PATCH /regions/2
{"shape": ["A ring has four positions or more, its last one its first."]}
A value that is not a GeoJSON geometry is refused in the same way. A
geometry of another kind than the field’s (a polygon sent to a
MultiPolygon field) is refused too, with the general “Invalid value.”.
A Point sent as {"lng": …, "lat": …} is not checked by rind yet: a
longitude or a latitude out of range is sent to the database as it is.
Querying by distance and by shape
A path to a geographic column has methods that give conditions and values. A station near a point is the most common case:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
/// `near=lng,lat,km`; a value that is not three numbers matches nothing.
pub fn near(q: Query<Station>, value: &str) -> Query<Station> {
let numbers: Vec<f64> = value
.split(',')
.filter_map(|n| n.trim().parse().ok())
.collect();
match numbers.as_slice() {
[lng, lat, km] => q.filter(Station::position().within_meters(*lng, *lat, km * 1000.0)),
_ => q.filter(Station::id().eq(-1)),
}
}
}
This is the method of a filter, so a client asks for it in the query string:
GET /stations?near=2.3212,48.8412,400
The answer has the stations at most 400 km from the point. In the sample’s tests, where Paris Montparnasse and Rennes are given a position, these are the two stations it lists. A row without a position does not match.
within_meters is GeoDjango’s dwithin lookup. It is written with
PostGIS’s ST_DWithin, which a GiST index on the column serves. rind does
not make that index by itself; declare it on the model:
#[index(name = "network_station_position_idx", sql = "USING gist (position)")].
The methods
| Method | What it gives | GeoDjango |
|---|---|---|
within_meters(lng, lat, m) | a condition: at most m metres from the point | dwithin, distance_lte |
distance_to(lng, lat) | a value: the distance to the point, in metres | Distance("position", point) |
within_meters_of(other, m) | a condition: at most m metres from another column | dwithin with an F() |
distance(other) | a value: the distance to another column, in metres | Distance("a", "b") |
covers(lng, lat) | a condition: the shape holds the point | covers, contains |
area() | a value: the shape’s area, in square metres (0 for a point or a line) | Area("shape") |
centroid() | a value: the shape’s centroid, as a point | Centroid("shape") |
is_point(lng, lat) | a condition: the point is exactly this one | position=point |
A value (a distance, an area) is null when a column is null. It is an expression like any other: it is selected, compared, and ordered by.
#![allow(unused)]
fn main() {
// Stations by distance from a point, the nearest first.
Query::<Station>::new()
.filter(Station::position().is_not_null())
.order_by([Station::position().distance_to(2.3212, 48.8412).asc()])
}
Between two columns
The other column can be reached through relations, so the length of a journey, from its origin to its destination as the crow flies, is one expression. A serializer sends it when it is asked for:
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/serializers.rs
/// From its origin to its destination as the crow flies, in metres.
#[annotated(
expr = Journey::origin().position().distance(Journey::destination().position()),
on_request
)]
pub distance: Option<Option<f64>>,
}
A filter on it is just as short:
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/filters.rs
/// `min_km`: origin and destination further apart than this.
pub fn longer_than(q: Query<Journey>, km: f64) -> Query<Journey> {
q.filter(!Journey::origin().position().within_meters_of(Journey::destination().position(), km * 1000.0))
}
}
Shapes that hold a point
A region whose outline holds a point:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/regions.rs
q.filter(Region::shape().covers(lng, lat))
}
The railway answers it as GET /regions?covers=lng,lat, and sends each
region’s area when it is asked for
(#[annotated(expr = Region::shape().area(), on_request)]).
A centroid, and an exact point
shape.centroid() is a shape’s centroid, as a point. It is GEOS’s
centroid (Django’s poly.centroid), computed on the coordinates. Its
type is the point type of the column it is written to, so it fits in an
update:
#![allow(unused)]
fn main() {
// a model with a polygon `shape` and a point `position`
db.execute(&Update::<Town>::new()
.set(Town::position(), Town::shape().centroid())
.filter(Town::position().is_null()))
.await?;
}
position.is_point(lng, lat) matches a row at that point exactly
(Django’s filter(position=point)). A row without a point does not
match.
Other PostGIS functions
The methods above are the common ones. Another PostGIS function is written
in SQL where an operation needs it (ST_ConcaveHull, ST_Union), with
db.query_sql (Queries). Inside
a typed query, rind::query::func::call calls a function of one
argument, and rind::query::Expr::Func takes any function with any
arguments.
GeoJSON answers
A map wants a layer: a GeoJSON FeatureCollection, one feature per
object. rind::db::geo::Feature and FeatureCollection write it, as
Django’s rest_framework_gis does with its GeoFeatureModelSerializer:
- a feature has the object’s
idbeside itstype; - its
geometryis aPoint, aPolygon, or anyGeometry, as a GeoJSON geometry, ornullwhen the object has none; - its other values are in
properties, added with.with(name, value).
An action answers it. The railway maps the stations that the list would show:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[action(GET, cached)]
pub async fn geojson(ctx: &Ctx, params: &QueryParams) -> Result<FeatureCollection, ApiError> {
let query = rind::api::resource::list_query::<StationResource>(ctx, (), params)?;
let select = query
.select((Station::id(), Station::name(), Station::status(), Station::position()))
.into_select();
let rows: Vec<(i64, String, String, Option<Point>)> = ctx.db.rows(&select).await?;
Ok(FeatureCollection::new(
rows.into_iter()
.map(|(id, name, status, position)| {
Feature::new(id, position).with("name", name).with("status", status)
})
.collect(),
))
}
}
GET /stations/geojson?status=open
The answer has this shape (a station without a position has
"geometry": null):
{"type": "FeatureCollection", "features": [
{"id": 1, "type": "Feature",
"geometry": {"type": "Point", "coordinates": [2.3212, 48.8412]},
"properties": {"name": "Paris Montparnasse", "status": "open"}},
…
]}
In a feature, a point is a GeoJSON geometry, [lng, lat], and not the
{"lng", "lat"} object of an ordinary answer: this is what map libraries
read.
To put two layers in one answer, chain them:
stations.chain(depots) is a collection with the features of both.
What is not handled yet
- A list answered as a GeoJSON feature collection by the list itself
(
?format=geojson) will come with the exports. Until then, write an action, as above. - Geometries in another SRID than 4326, rasters and topologies are not handled.
- GeoDjango’s other lookups (
intersects,within,overlaps,touches…) and functions have no method yet: write them in SQL.
Reference
Types of rind::db::geo
| Type | Column | JSON in and out |
|---|---|---|
Point { lng, lat } | geography(Point,4326), or a geometry point | {"lng": …, "lat": …} |
Polygon | geography(Polygon,4326) | a GeoJSON Polygon |
MultiPolygon | geography(MultiPolygon,4326) | a GeoJSON MultiPolygon |
Geometry | any geography or geometry | any GeoJSON geometry |
Shape | any PostGIS value | its EWKB in hexadecimal |
Feature | (an answer) | a GeoJSON Feature |
FeatureCollection | (an answer) | a GeoJSON FeatureCollection |
Position is [f64; 2], a longitude and a latitude, in GeoJSON’s order.
Path methods
| Method | On | SQL |
|---|---|---|
within_meters(lng, lat, m) | any geographic column | ST_DWithin(col, point, m) |
distance_to(lng, lat) | any geographic column | ST_Distance(col, point) |
within_meters_of(other, m) | any geographic column | ST_DWithin(col, other, m) |
distance(other) | any geographic column | ST_Distance(col, other) |
covers(lng, lat) | any geographic column | ST_Covers(col, point) |
area() | any geographic column | ST_Area(col) |
centroid() | any geographic column | ST_Centroid(col::geometry)::geography |
is_point(lng, lat) | a point column | ST_Equals(col::geometry, point::geometry) |
The point (lng, lat) is sent as ST_GeogFromText('SRID=4326;POINT(lng lat)').
Migrations
When you change a model, the database must change with it. In Django,
makemigrations writes a migration file, migrate applies it, and
showmigrations tells you where a database stands. rind works the same
way, with the same three steps:
| Django | rind |
|---|---|
python manage.py makemigrations | rind make |
python manage.py makemigrations --check | rind check |
python manage.py migrate | rind migrate |
python manage.py showmigrations | rind status |
python manage.py migrate --fake | rind migrate --fake |
python manage.py migrate <app> --fake | rind migrate --fake --only <domain> |
python manage.py sqlmigrate | not needed: the migration is SQL |
the django_migrations table | the rind_migrations table |
rind makes four choices of its own:
- the migration files are plain SQL, not code;
- a rename is a question that
makeasks you, as Django does; - there is no going back: to undo a change, you write a new migration;
- the migrations are compiled into the binary, so a deployed server needs no source tree to migrate its database.
A first migration
Say you add a field to the Station model of the sample:
#![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>,
}
}
You ask rind to write the migration:
rind make
network 0003_station_photo
add network_station.photo
make has written a new file in the folder of the domain’s migrations.
It is plain SQL, and you can read it before anything runs:
-- rind migration: network 0003_station_photo
-- add network_station.photo
ALTER TABLE "network_station" ADD COLUMN "photo" character varying(500);
rind status lists every migration, in the order they are applied, with
[x] for the ones the database has and [ ] for the others:
[x] network 0001_initial
[x] accounts 0001_initial
[x] network 0002_keys
[ ] network 0003_station_photo
Then you apply what is missing:
rind migrate
applied network 0003_station_photo
rind … runs the application’s own binary (cargo run -p app -- …),
with the project’s .env as its environment. The database is
DATABASE_URL, or the one you give with --database URL. See
The command line.
Why the migrations are plain SQL
A Django migration is Python code: a list of operations
(AddField, AlterField, RunPython…) that Django turns into SQL when it
runs. rind writes the SQL itself, once, into the file. There are three
reasons for this:
- What you review is what runs. There is no translation step left. A reviewer, or a database administrator who does not know Rust, reads the exact statements the database will receive.
- The file is yours to edit.
makewrites the first draft. You may then add a statement, a data step or a backfill: where Django needs aRunPythonor aRunSQLoperation, you write the SQL in the file. - Old migrations never break. A Django migration imports historical models, and old migrations can stop working when the code around them changes. A SQL file depends on nothing in your code, so it runs the same way in five years.
To know what changed since the last migration without code, rind keeps a second file beside each migration: the schema of the domain once that migration is applied (see the files of a domain). This is what Django rebuilds by replaying its migrations in memory.
A domain’s migrations
A domain is one crate of models, like a Django app (see the glossary). Each domain has its own folder of migrations, inside its models crate:
network-models/migrations/
0001_initial.sql
0001_initial.state.json
0002_keys.sql
0002_keys.state.json
embedded.rs
- The
.sqlfile is the migration. Its first lines say what it is and which migrations of other domains it depends on.makewrites it, and then it belongs to you. - The
.state.jsonfile is the schema of the domain once the migration is applied: its tables, columns, keys, indexes. The nextmakecompares the models with it. This is why making a migration needs no database, and whymakecan see that a column was perhaps renamed. embedded.rslists the files for the compiler.makekeeps it up to date; do not edit it by hand.
The crate gives its domain to the application with a function, usually
called migrations():
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
pub fn migrations() -> rind::migrations::Domain {
rind::migrations::domain!("network", schema()).extension("postgis")
}
}
The domain! macro takes the domain’s name and its tables (the
schema() function of the crate), and compiles in the files of the
crate’s migrations folder. The application lists every domain in its
app():
#![allow(unused)]
fn main() {
// sample/src/lib.rs
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
.models(network_models::migrations())
.models(accounts_models::migrations())
// …
}
rind add domain creates a new models crate with an empty index,
migrations/embedded.rs, so that the crate builds before its first
migration exists.
Extensions, types and functions the tables need
Some tables need something that is not a table: a PostgreSQL extension
(postgis, vector), or a type, a function or a text search
configuration. You declare it on the domain, and the domain’s migrations
create it before the tables:
#![allow(unused)]
fn main() {
rind::migrations::domain!("classify", schema())
.extension("vector")
.object("TYPE", "classify_embedding_kind", include_str!("../sql/classify_embedding_kind.sql"))
}
.extension(name)is created withCREATE EXTENSION IF NOT EXISTS..object(kind, name, sql)is created by the SQL you give.kindis the word that followsDROPto remove it (TYPE,FUNCTION…).
Writing migrations: make and check
rind make compares each domain’s models with the state its last
migration recorded, and writes a migration for each domain that changed.
It reads no database. The first migration of a domain is named
initial; a later one is named after what it does when it does one thing
(0003_station_photo), and changes otherwise. --name gives your own
name: rind make --name add_photos.
Most changes of a model become one SQL statement each:
| You change the model | The migration has |
|---|---|
| a new model, a new link table | CREATE TABLE, then its keys |
| a model removed | DROP TABLE |
| a field added or removed | ADD COLUMN, DROP COLUMN |
| a type, a length | ALTER COLUMN … TYPE … USING |
Option added or removed | DROP NOT NULL / SET NOT NULL |
| a default | SET DEFAULT / DROP DEFAULT |
a foreign key, its target, its on_delete | the constraint and its index |
| an index, a uniqueness, a condition | CREATE INDEX, ADD CONSTRAINT, or their drop |
| the name of a constraint or of an index | a rename |
rind check writes nothing. It fails when a model changed and has no
migration yet, as Django’s makemigrations --check does. It also fails
when the models do not hold together across domains (a key to a table
that does not exist, two constraints with the same name), or when a
folder’s embedded.rs is not what the folder has. Run it in CI.
The sample also runs the same check with its tests
(sample/tests/schema.rs, through rind::testing::check), so
cargo test fails when a model changed without its migration.
When a column was renamed
When a column (or a table) disappeared and another one of the same shape
appeared, make cannot know whether you renamed it or replaced it. So it
asks you, as Django does:
Was network_station.code renamed to network_station.reference? [y/N]
If you answer yes, the migration has a RENAME, and the data stays. If you
answer no, the old column is dropped, with its data, and the new one is
added empty.
When nobody can answer (in a script, in CI), give the renames beforehand.
A column is table.old=new, and a table is old=new:
rind make --rename network_station.code=reference
rind make --rename network_stop=network_station
Without a terminal and without --rename, the answer is no.
A new required field: what only you can write
A new field that is not an Option and has no default is a problem for
the rows that already exist: they have no value for it. Django asks you
for a one-off default when you run makemigrations. rind writes the
migration in three steps and leaves the middle one to you:
ALTER TABLE "network_station" ADD COLUMN "rank" integer;
-- TO COMPLETE: the rows that exist need a value. Write it here, then remove this line:
-- UPDATE "network_station" SET "rank" = …;
ALTER TABLE "network_station" ALTER COLUMN "rank" SET NOT NULL;
The column is added empty, you fill it, and then it becomes required.
make tells you which file is waiting:
network 0007_station_rank
add network_station.rank
TO COMPLETE before it can be applied: "…/0007_station_rank.sql"
A migration that still has a -- TO COMPLETE line is not applied:
migrate stops there and applies nothing after it. Write the UPDATE,
remove the line, and migrate again.
Applying migrations: migrate and status
rind migrate applies, in order, every migration the database does not
have yet.
- Each migration runs in its own transaction. A migration that fails
leaves nothing of itself behind, and nothing after it is tried. You fix
the file and run
migrateagain. - What is applied is recorded in a table,
rind_migrations, with a fingerprint of the file’s text. The table is created by the firstmigrate;statusonly reads it, and changes nothing in the database. rind statusshows an edited migration. A migration whose file changed after it was applied is marked[!] edited since it was applied. Editing it does not apply the change: write a new migration instead.migratewarns about forgotten migrations. If the binary’s models have changes that no migration has, it says so before it applies the others.
Migrating when the server starts
Several processes can migrate the same database at once, for example the instances of a deployment that start together. One of them applies each migration; the others wait, then find it done. So an application can safely migrate when it starts:
#![allow(unused)]
fn main() {
rind::migrations::migrate(&db, sample::app().migrations(), false).await?;
}
The last argument is fake (see below). A
deployed binary needs no source tree: it applies the migrations that were
compiled into it.
Coming from Django: there is no
migrate <app> 0002to go back to an older migration, and no reverse operation in a migration. To undo a change, change the model back and runmake: the new migration does the opposite of the old one.
Migrations across domains
A migration comes after the one before it in its domain. When its foreign
keys point to tables of another domain, it also comes after the migration
of that domain that creates those tables. make writes these
dependencies as -- depends: lines at the top of the file, and migrate
finds an order that respects them all:
-- rind migration: network 0002_keys
-- depends: accounts 0001_initial
Two domains can point to each other. In the sample, a station has a
manager (a user of accounts), and a user has a home station (in
network). Neither domain’s first migration can come after the other’s.
make then does what Django’s makemigrations does in that case: it
creates the tables first, without the keys between them, and adds those
keys in a second migration of each domain:
network 0001_initial the stations, without their key to the users
accounts 0001_initial the users, without their key to the stations
network 0002_keys
accounts 0002_keys
Naming constraints and indexes
rind gives a name to every constraint and index it creates:
<table>_<columns>_idx for an index, _key for a unique column, _fkey
for a foreign key. You can give any of them another name. This is how a
model describes a database that already exists, created by Django for
example, whose names are not rind’s:
| On | The name is given with |
|---|---|
| a foreign key | #[fk(Target, constraint = "…", index = "…")] |
| a unique column | #[column(unique = "…")] |
| an indexed column | #[column(index = "…")] |
#[index(on(..))], #[unique(on(..))] | name = "…" |
| a condition | #[check(name = "…", sql = "…")] |
If you change a name on the model, the next migration renames the constraint or the index in the database.
Taking over a database
Sometimes the tables already exist: a Django application, or another
program, created them, and rind now takes over. You write the models that
describe these tables (rind can write them for you: see
Starting from a database), and make writes their first
migrations as usual. But these migrations must not run, since the tables
are already there. You record them as applied instead, as Django’s
migrate --fake does:
rind migrate --fake
--fake records every migration the database does not have, and runs
none. A -- TO COMPLETE line does not stop it.
Often only some domains already exist in the database, and the others are
new: the application’s own tables, which rind must create. --only
chooses the domains, as migrate <app> --fake does in Django:
rind migrate --fake --only locations,structures,users # recorded, not run
rind migrate # the others, run
--only puts the migrations of every domain in order, so it knows the
dependencies between domains, and then applies only those of the domains
you named. A migration that depends on another domain (because one of its
keys points to that domain’s table) is refused until that other domain is
applied or recorded. For example, rind migrate --only documents is
refused while the users migrations that documents points to are not
in the database.
Checking the models against the database first
Before you record anything, check that the models describe the database faithfully. Two commands compare them:
rind dbcheckcompares tables, columns and types (db.check_schema(&tables)in code).rind constraintscompares constraints and indexes, by name and by what they are. With--sql, it prints theRENAMEstatements that would give the database the models’ names.
rind dbcheck
rind constraints # what differs, by name and by what it is
rind constraints --sql # the renames that give the database the models' names
rind verify goes further: it applies every migration to an empty schema
and compares the result with the models. With --against URL, it also
compares it with the database the models were written from (see
Starting from a database).
Reference
The commands
rind make [--name NAME] [--rename OLD=NEW]... # write what changed in the models
rind check # fail if a change has no migration
rind status # on DATABASE_URL, or --database URL
rind migrate [--fake] [--only a,b]
rind constraints [--sql] # the constraints and indexes that differ
rind verify # every migration on an empty schema, compared with the models
rind verify --against URL [--schema S] # … and with that database
make and check read no database, and refuse --database. status,
migrate and constraints read DATABASE_URL or --database URL.
| Command | What it does |
|---|---|
make | writes a migration for each domain whose models changed; asks about renames |
make --name NAME | names the new migrations NNNN_<name> |
make --rename old=new | a table renamed, answered beforehand |
make --rename table.old=new | a column renamed, answered beforehand (table is the new table name) |
check | fails if the models do not hold together, if a change has no migration, or if an embedded.rs is stale |
status | every migration in order: [x] applied, [ ] not, [!] edited since it was applied |
migrate | applies what the database does not have, each migration in a transaction |
migrate --fake | records the migrations without running them |
migrate --only a,b | only the migrations of these domains (with --fake or without) |
constraints | the constraints and indexes the models and the database do not have alike |
constraints --sql | the statements that rename them to the models’ names |
verify | applies every migration to a temporary schema, compares it with the models, drops the schema |
In code
An application that does not use rind::cli can call the same commands
itself, with the arguments of the command line (without the program’s
name; status and migrate then take the database’s address as their
first argument):
#![allow(unused)]
fn main() {
rind::migrations::run(app.migrations(), &args).await?;
}
The functions behind the commands are in rind::migrations:
| Function | Does |
|---|---|
migrate(&db, domains, fake) | rind migrate, rind migrate --fake |
migrate_only(&db, domains, Some(&["a", "b"][..]), fake) | rind migrate --only a,b |
status(&db, domains) | rind status: a Status per migration (domain, name, applied, changed) |
make(domains, &mut ask, name) | rind make; ask answers the renames (NoRename, Renames(..)) |
pending_changes(domains, &mut ask) | what check reports: the changes without a migration |
The files
| File | Written by | Holds |
|---|---|---|
NNNN_name.sql | make, then you | the SQL; a -- rind migration: line, then -- depends: <domain> <name> lines |
NNNN_name.state.json | make | the schema of the domain after this migration |
embedded.rs | make (and rind add domain, empty) | the list of files compiled into the binary |
rind_migrations (a table) | migrate | domain, name, applied_at, fingerprint |
Databases: primary and replicas
This chapter covers two needs. The first is to spread the reads of a busy application over replicas: read-only copies of the database that PostgreSQL keeps up to date. The second is to keep some tables in another database.
In Django, both go through the DATABASES setting and a database
router, a class whose db_for_read and db_for_write methods choose a
database for each query. rind has no router class. Instead:
- each database is a
Cluster: one primary, the server that is written, and its replicas; - a request that only reads goes to a replica, and a request that writes goes to the primary, automatically;
- a model says which database its table is in, with
#[model(database = "…")].
Reading on replicas
You build a Cluster from the primary, add its replicas, and give it to
the application’s state:
#![allow(unused)]
fn main() {
use rind::api::Databases;
use rind::prelude::*;
let primary = Db::connect(&std::env::var("DATABASE_URL")?)?;
let replica = Db::connect(&std::env::var("REPLICA_URL")?)?;
let cluster = Cluster::new(primary).replica(replica);
let state = app.state_with(Databases::of(cluster));
}
app.state_with(..) is the state your web server is given (see
The command line for a server of your own, with
rind::cli::Cli::serve). The serve command of rind’s own server uses
one database only, DATABASE_URL: to use replicas, you write that server
yourself.
From then on, each request picks its server by itself:
- A request that only reads (a
GET) works on a replica. With several replicas, the requests take turns. - A request that writes (anything but a
GET) works on the primary. - A replica refuses a write before it reaches the server: the query
fails with a
ReadOnlyerror. A bug cannot write to a replica by mistake.
Reading your own writes
A replica is always a little late: the primary sends it its changes, and applying them takes a moment. Most reads do not care. But a client that creates an object and then reads the list right after must find the new object in it.
rind handles this with a position: how far the primary’s log has got
(PostgreSQL’s LSN, written like 16/B374D848).
- Every answer to a write carries the position the primary reached, in
the header
X-Db-Position. - The client sends this header back with the requests that follow.
- A read that comes with a position goes to a replica only if that replica has caught up with it. Otherwise it goes to the primary.
POST /stations
201 Created
X-Db-Position: 16/B374D848
GET /stations
X-Db-Position: 16/B374D848
A client that sends nothing back is covered too, in part: the server remembers, per process, the position of each signed-in user’s last write, and sends that user’s reads to the primary until a replica has caught up. This memory is not shared between processes. Behind a load balancer, the next request may reach another process, so a client that must read its own writes should send the header back.
The header is only sent when the database has replicas: without them, nothing can be late. rind’s CORS lets a browser read it.
A read that must not be late
Sometimes a piece of code that runs in a reading request must see the latest data, for example to check a value just before it answers. It asks for the primary:
#![allow(unused)]
fn main() {
let db = ctx.primary()?;
}
ctx.primary() gives the primary of the default database, whatever the
request does.
Several databases
A model says which database its table is in. Without it, the table is in
the database named default:
#![allow(unused)]
fn main() {
#[derive(Model)]
#[model(table = "visits", database = "stats")]
pub struct Visit { … }
}
The application gives each database a name, and a Cluster:
#![allow(unused)]
fn main() {
let databases = Databases::new(db).with("stats", Cluster::new(stats).read_only());
let state = app.state_with(databases);
}
Databases::new(db) is the default database on a single server;
Databases::of(cluster) is the same with replicas. .with(name, cluster)
adds another database. .read_only() says that the application never
writes this one: even its primary refuses writes.
In a handler, ctx.db is the default database. You ask for another one
by its name:
#![allow(unused)]
fn main() {
let stats = ctx.database("stats").await?;
let visits = stats.all(&Query::<Visit>::new()).await?;
}
The database you get follows the same rule as the request: its primary for a request that writes, a replica otherwise.
A query on a model sent to another database than its own is refused
before any SQL is sent: a WrongDatabase error. Asking for a database the
application does not have is an error too.
Coming from Django: there is no
.using("stats")on a query. The model knows its database, so the query cannot go to the wrong one; you choose only theDbyou run it on.
What is not covered
- A transaction covers one database. A transaction on the default
database does not include the writes made with
ctx.database("stats"). - A relation does not cross databases. A foreign key, a nested field or a filter cannot join a table of another database.
- Raw SQL is not checked. A query written as SQL text is not checked for its database, nor for being a write sent to a read-only server (PostgreSQL itself refuses a write on a replica).
- The position is the default database’s. It says how far the default primary’s log has got, and means nothing to the replicas of another database. Do not count on reading your own writes there: ask for that database in a request that writes, or give it no replicas.
- Migrations know one database.
rind migrateapplies every domain’s migrations to the database it is given, whateverdatabase = "…"the models say.
Resources
A resource serves one model over HTTP. It is what Django REST framework
calls a viewset, and most often a ModelViewSet: it answers the list of
objects, each object, the writes (create, update, delete) and the actions
you add to it.
In Django REST framework, a viewset is a class with attributes:
queryset, serializer_class, filterset_class, search_fields,
ordering_fields, permission_classes. A rind resource says the same
things, but as attributes of a derive on an empty struct. The derive reads
them when the code compiles, so a mistake (a field that does not exist, a
rule that names an action the resource does not have) is a compile error,
not a 500 at the first request.
A first resource
This is the trains resource of the sample application:
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-api/src/trains/views.rs
use fleet_models::Train;
use rind::Resource;
use super::filters::TrainFilters;
use super::serializers::{TrainIn, TrainOut};
/// Signed-in users read the trains; the staff writes them.
#[derive(Resource)]
#[resource(
model = Train,
path = "trains",
out = TrainOut,
filters = TrainFilters,
input = TrainIn,
delete,
options(cache_ttl = 30, cache_by_mode)
)]
#[rule(superuser)]
#[rule(staff)]
#[rule(authenticated, actions(list, retrieve))]
#[search(Train::name(), unaccent)]
#[search(Train::number(), starts_with)]
#[ordering(by(id, number, name), default("number"))]
pub struct TrainResource;
}
The struct has no fields and no methods: everything is in the attributes.
The keys of #[resource(..)] are:
model: the model the resource serves (DRF’squeryset.model).path: the URL prefix, as given to DRF’srouter.register("trains", …).out: the serializer, which says what an object looks like in an answer.input: the input, which says what a client may write.filters: the filterset, which says what the list can be filtered on (django-filter’sFilterSet).delete: the resource acceptsDELETE.options(..): settings read by plugins, here the cache.
The other attributes are #[rule], which says who may do what
(Permissions), and #[search] and #[ordering], which
are DRF’s search_fields, ordering_fields and ordering
(Filters).
Coming from Django: there is no
Meta.orderingon the model. The resource says its default ordering with#[ordering(.., default("number"))].
What it serves
That one struct serves six routes:
| Request | Action | Answer |
|---|---|---|
GET /trains | list | a page of trains, filtered, searched and ordered |
GET /trains/{id} | retrieve | one train |
POST /trains | create | the new train, with status 201 |
PUT /trains/{id} | update | the train after the change |
PATCH /trains/{id} | partial_update | the train after the change |
DELETE /trains/{id} | destroy | an empty 204 |
The action names in the second column are the ones DRF uses. Rules name
them: #[rule(authenticated, actions(list, retrieve))] lets every
signed-in user read the trains, and nothing more.
A list answer is a page. It always has the same three keys:
GET /trains?page_size=2
Authorization: Bearer alice-token
{
"parameters": {"page": "page", "pagesize": "page_size"},
"nav": {"size": 2, "page": 1, "next": 2, "prev": null, "count": 3, "pages": 2},
"results": [
{"id": 2, "number": "FRET42", "name": "Armor Fret", "kind": "freight", "status": "active", "depot": 2},
{"id": 3, "number": "TER77", "name": "Cornouaille", "kind": "passenger", "status": "maintenance", "depot": 3}
]
}
parametersgives the names of the paging parameters, so a client does not have to hard-code them.navsays where the page is: its size, its number, the next and previous page numbers (nullwhen there is none), the number of rows that match the request, and the number of pages.resultsholds the objects, as the serializer writes them.
Filters, search, ordering, pages explains page and
page_size. A retrieve answers one object, without the envelope:
GET /trains/1
{"id": 1, "number": "TGV8601", "name": "Atlantique", "kind": "passenger", "status": "active", "depot": 1}
Which routes exist
A resource only serves what it has the pieces for:
- Without
input, the resource is read-only, like DRF’sReadOnlyModelViewSet.POST,PUTandPATCHanswer 405. - Without
delete,DELETEanswers 405. - With
actions, the resource also serves the actions written in its#[actions]block, as DRF’s@actionmethods.
A rule can only name actions the resource has. A typo in
actions(list, retreive) does not compile.
Putting the resources together
A resource is not tied to a web framework. The same resource is served by actix-web or by axum.
Resources are grouped by domain: a part of the application with its own models and its own API crate (see Organising an application). The API crate of a domain lists each of its resources once, in a function that depends on neither framework:
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-api/src/lib.rs
pub mod trains;
/// The API of this domain: its resources, mounted by the application.
pub fn api() -> rind::api::Api {
rind::api::Api::new("fleet").resource::<trains::TrainResource>()
}
}
This list is the equivalent of the DRF router and its register() calls.
The application then gathers every domain’s api() in one value,
app() (see The command line).
When you add a resource with rind add resource, the tool adds it to this
chain for you (Starting a project).
To serve the application, you give it an AppState. The state holds the
database, the way users sign in, and the tables of the application. Then
you mount the routes in the framework you use:
#![allow(unused)]
fn main() {
let app = sample::app();
// axum
let router = app.router(app.state(db));
// actix-web
App::new()
.app_data(web::Data::new(app.state(db)))
.configure(|cfg| app.configure(cfg))
}
Most applications do not write this code: rind serve does it (see
The command line).
A single resource can still be mounted alone, for a test or a small
service: rind::api::axum::router::<R>() for axum, and
rind::api::actix::scope::<R>() for actix-web.
Who is asking
Before a resource runs, rind finds out who sent the request. This part
belongs to the application: it implements the trait Authenticate. The
trait reads the Authorization header and answers an Identity, or no
identity for an anonymous request.
An Identity holds what the permission rules look at:
id, the user’s id;is_superuserandis_staff, as on Django’s user;groups, the slugs of the user’s groups;data, whatever else the application wants its resources to find there (read it back withidentity.data::<T>()).
The sample application keeps a token in a column of its user table
(accounts-ops). A real application checks a signed token, for example
with rind-auth.
A request without credentials is anonymous. A request with wrong credentials is a 401, even on a resource that anonymous users may read: a client that sends a bad token is told so, rather than silently treated as anonymous. Authentication has the details.
What a resource’s code receives: the context
Everything a resource runs (a hook, an action, a loader of a serializer, a
mode’s query) receives a Ctx, the context of the request. It is what
DRF gives you through self.request:
ctx.dbis the database the request works on. During a write, it is the write’s transaction: what you do with it is kept or dropped with the write.ctx.useris theIdentity, orNonefor an anonymous request.ctx.parameters::<P>()gives the request’s typed parameters of typeP.ctx.action()gives the action being run ("list","create", an action’s name). See Permissions.ctx.tables()gives every table of the application (used by deletions).ctx.service::<T>()gives a service a plugin shares, such as the mailer.
When a request fails
A request that fails gets one of these statuses:
| Status | When |
|---|---|
| 400 | a body or a query parameter that is not valid; the answer says what is wrong, field by field |
| 401 | no credentials where they are needed, or wrong credentials |
| 403 | the user is signed in, and no rule allows the action |
| 404 | no such object, or an object the user’s mode does not let them see |
| 405 | the resource does not do that (no input, no delete) |
| 409 | a deletion refused because other rows still point to the object (Inputs) |
The body of an error is JSON. Most errors have a detail key, as in DRF:
{"detail": "You do not have permission to perform this action."}
An invalid body is answered per field, with every error at once:
{"number": ["An object with this value already exists."]}
A constraint that the database refuses (a uniqueness, a check, a foreign key) is a 400 too, not a server error. Most of the time the input catches it first and names the field (Inputs); when it does not, the answer names the constraint:
{"detail": "These values are not allowed (fleet_wagon_capacity_check)."}
Only a fault of the server is a 500. Its cause is logged, and never sent to the client.
Reference
#[resource(..)]
| Key | Meaning | DRF |
|---|---|---|
model = M | the model served (required) | queryset |
path = "…" | the URL prefix (required) | router.register(prefix, …) |
out = S | the serializer (required) | serializer_class, read side |
input = I | the input; without it the resource is read-only | serializer_class, write side |
filters = F | the filterset | filterset_class |
delete | DELETE is accepted | DestroyModelMixin |
hooks | you write impl Writes for … yourself, to check or complete the writes | perform_create, perform_update, perform_destroy |
mode = T | the type of the resource’s permission modes | get_queryset per user |
query = … | the base query of a resource without modes: the rows it can see; if it mentions user, an anonymous request sees no row | get_queryset |
actions | the resource serves the actions of its #[actions] block | @action |
behaviours(..) | what it shares with other resources: tracking, flags, markdown, images | mixins |
exports(..) | its export formats (xlsx) | |
parameters(..) | the typed parameters it reads, besides its filters’ and its behaviours’ | |
options(..) | settings that plugins read: cache_ttl = 60, usage = "skip", a bare name for true | |
page_size = N | the default page size, 100 if not given | PAGE_SIZE |
max_page_size = N | the largest page a client may ask for, 50 000 if not given | max_page_size |
ignore_unknown_fields | an unknown name in fields, omit or include is ignored instead of being a 400 |
A resource needs at least one #[rule(..)]: without one, nobody could
call it, and the derive refuses to compile.
The doc comment of the struct becomes the resource’s description in the OpenAPI document.
The other attributes
| Attribute | Chapter |
|---|---|
#[rule(who, actions(..), mode = ..)] | Permissions |
#[mode(Value, query = .., hide(..))] | Permissions |
#[search(path, mode)] | Filters |
#[ordering(by(..), default(..), hidden(..))] | Filters |
Errors
| Status | ApiError | Body |
|---|---|---|
| 400 | BadRequest(message) | {"detail": message} |
| 400 | Validation(errors) | {"field": ["message", …], …} |
| 401 | Unauthorized | {"detail": "Authentication credentials were not provided or are invalid."} |
| 403 | Forbidden | {"detail": "You do not have permission to perform this action."} |
| 404 | NotFound | {"detail": "Not found."} |
| 405 | MethodNotAllowed | {"detail": "Method not allowed."} |
| 413 | {"detail": "Request body too large."}: a body larger than RIND_BODY_LIMIT bytes (32 MiB by default) | |
| any | Response(status, body) | a status and a body of your own |
| 500 | Database(..), Internal(..) | {"detail": "Internal server error."}; the cause is logged |
Serializers: what an answer contains
A serializer says what an object looks like in an answer: which keys
the JSON has, and where each value comes from. It is the read side of
Django REST framework’s ModelSerializer.
In DRF, one ModelSerializer usually does two jobs: it turns an object
into JSON, and it reads and validates the JSON a client sends. rind splits
these two jobs into two structs:
- the serializer (this chapter) says what goes out;
- the input (Inputs) says what can be written.
They are separate because they are rarely the same. An answer has nested
objects, counts, values the application computes, and ids sent under the
name of their relation. A write has none of these: it has the columns a
client may change, with their checks (a maximum length, a list of
choices, a key that must exist). With one class, DRF needs read_only,
write_only and read_only_fields to tell the two apart. With two
structs, each one only has what it needs, and a field that is not in the
input cannot be written, whatever the serializer sends.
A first serializer
This is part of the serializer of the sample’s stations:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/serializers.rs
use chrono::NaiveDate;
use network_models::Station;
use rind::Serializer;
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Station)]
pub struct StationOut {
#[field(mandatory)]
pub id: Option<i64>,
#[field(mandatory)]
pub code: Option<String>,
#[field(mandatory)]
pub name: Option<String>,
pub city: Option<String>,
#[field(mandatory)]
pub status: Option<String>,
pub platforms: Option<i32>,
pub services: Option<Vec<String>>,
pub opened: Option<Option<NaiveDate>>,
#[field(name = "region")]
pub region_id: Option<i64>,
#[field(name = "manager")]
pub manager_id: Option<Option<i64>>,
// …
}
}
#[serializer(model = Station)] says which model the serializer reads,
like DRF’s Meta.model. A field without an attribute is the model’s
column of the same name. The resource names the serializer with
out = StationOut (Resources).
The derive writes the JSON itself: do not also derive serde::Serialize.
A request for one station gets:
GET /stations/3
{"id": 3, "code": "BRE", "name": "Brest", "city": "Brest", "status": "open",
"platforms": 6, "services": ["wifi"], "opened": null, "region": 3,
"manager": null, "photo": null, "position": null}
Why every field is an Option
Every field of a serializer is an Option. The client chooses which
fields it wants (see below), and None means “this
field was not asked for”. A field that was not asked for is not read from
the database, and its key is not in the JSON. It is not sent as null:
it is absent.
A column that can be NULL therefore has two Options:
Option<Option<NaiveDate>>. The outer one says whether the field was
selected; the inner one is the value, None for NULL. A selected
NULL goes out as null, as "opened": null above.
The derive checks this: a field that is not an Option does not compile.
The name of a field in the JSON
The key in the JSON is the name of the Rust field, unless the field says
another one with name = "…". A raw identifier loses its r#:
pub r#type: Option<String> goes out as "type".
A foreign key is the common case. The model’s field is region_id, and
DRF sends it under the relation’s name, region. rind does the same only
when you say so:
#![allow(unused)]
fn main() {
#[field(name = "region")]
pub region_id: Option<i64>,
}
Without name, the key is region_id.
Note:
rind add resourcewrites a serializer with one field per column of the model, under the column’s name. A foreign key such asauthor_idtherefore goes out as"author_id". Add#[field(name = "author")]to send it as DRF does, and give the input’s field the same name (#[input(name = "author", fk = Author)], see Inputs) so that a client reads and writes the same key.
A field can also read a column of another name, with column = …:
#![allow(unused)]
fn main() {
// crates/rind/tests/derive.rs
#[field(name = "editor", column = edited_by)]
pub editor_id: Option<Option<i64>>,
}
Choosing which fields are sent
By default, an answer has every field except those marked on_request.
The client can change this with three query parameters:
| Parameter | What is sent |
|---|---|
fields=a,b | only a, b, and the mandatory fields |
omit=a,b | everything that would be sent, except a and b, even if they are mandatory |
include=a,b | the default fields, and also a and b (usually on_request fields) |
This is what the DynamicFieldsMixin of many DRF projects does. Two keys
of a field control it:
mandatory: the field is always sent, even whenfieldsdoes not name it. Onlyomitremoves it. Theidis usually mandatory.on_request: the field is not sent by default. A client must ask for it withfieldsorinclude. Use it for costly fields: nested objects, counts, computed values.
For example, with id, code, name and status mandatory:
GET /stations?fields=city&page_size=1
{"parameters": {…}, "nav": {…},
"results": [{"id": 3, "code": "BRE", "name": "Brest", "city": "Brest", "status": "open"}]}
GET /stations?fields=city&omit=name,status,code&page_size=1
{"parameters": {…}, "nav": {…}, "results": [{"id": 3, "city": "Brest"}]}
A few rules apply at the edges:
- A name that is not a field is a 400:
{"detail": "Unknown field(s): nope."}. A resource declared withignore_unknown_fieldsignores such names instead. - An empty
fields=selects no field, except the mandatory ones. - When
fieldsis given,includeis not read, except for its nested selections. - A field the user may not read is never sent, even when it is asked for
(see Who may read a field and a
mode’s
hide(..)in Permissions). - The same parameters apply to the answer of a write: a
POSTor aPATCHwith?fields=…gets those fields back.
A list reads only the columns its fields need. GET /stations?fields=city
reads the columns of city and of the mandatory fields, not the whole
row.
A field that brings others: implies
Sometimes a field only makes sense with another one: a client that asks
for a book’s tags also needs its title, say. implies(..) selects the
other fields too, one level deep:
#![allow(unused)]
fn main() {
// crates/rind/tests/derive.rs
#[nested(many, m2m = BOOK_TAGS, on_request, implies(title))]
pub tags_details: Option<Vec<TagOut>>,
}
A field sent by default when a parameter is there
A distance to a point only exists when the request gives the point.
default_with = "near", together with on_request, sends the field by
default when the request has a non-empty near parameter, and keeps it
on request otherwise:
#![allow(unused)]
fn main() {
#[computed(loader = near_km, key = id, optional, on_request, default_with = "near")]
pub near_km: Option<i64>,
}
fields and omit still decide: ?near=…&fields=id,name does not send
near_km. With optional on the #[computed] field and a loader that
gives no value without near, the key is not there either. The
parameter is read at every level, so this also works for a field of a
nested serializer.
Leaving a null out
A selected field whose value is NULL goes out as null. Sometimes you
want the key to be absent instead. DRF does that when a dotted source
goes through a null key (source="manager.username" on a station
without a manager), and some serializers drop every null. skip_null
does the same for one field:
#![allow(unused)]
fn main() {
/// The manager's user name; absent for a station without a manager.
#[annotated(expr = Station::manager().username(), skip_null, on_request)]
pub manager_name: Option<Option<String>>,
}
GET /stations?fields=id,manager_name&omit=code,name,status&ordering=id
{"parameters": {…}, "nav": {…},
"results": [{"id": 1, "manager_name": "sam"}, {"id": 2, "manager_name": "sam"}, {"id": 3}, …]}
#[serializer(.., skip_nulls)] puts skip_null on every field that can
be null. The OpenAPI document then says that the field is never null,
and may be absent.
Objects inside an object
A nested field sends a related object, or a list of them, inside the
answer. It is DRF’s nested serializer (region = RegionSerializer()).
There are three kinds:
#![allow(unused)]
fn main() {
/// One object, behind a foreign key.
#[nested(key = region_id, fields(id, name), on_request)]
pub region_details: Option<RegionOut>,
/// Behind a foreign key that can be null.
#[nested(key = passenger_id, on_request)]
pub passenger_details: Option<Option<PassengerOut>>,
/// A list: the rows that point to this one.
#[nested(many, by = Wagon::train_id(), fields(id, position, kind, capacity), on_request)]
pub wagons_details: Option<Vec<WagonOut>>,
}
key = region_idnames the model’s foreign key. The type is the nested serializer. For a nullable key, writeOption<Option<S>>so that a missing target goes out asnull.many, by = Wagon::train_id()sends the rows whosetrain_idis this row’s id. The type isOption<Vec<S>>.many, m2m = HOPsends the targets of a many-to-many relation (HOPis the constant that the model’s#[m2m(..)]makes).fields(..)fixes which fields of the nested serializer are sent there. Without it, the nested serializer sends its own default fields.
The nested serializer must derive Clone, since several rows of a page
can point to the same object.
GET /stations?fields=region_details&page_size=2
{"parameters": {…}, "nav": {…},
"results": [{"id": 3, "code": "BRE", "name": "Brest", "status": "open",
"region_details": {"id": 3, "name": "Finistère"}},
{"id": 6, "code": "MIL", "name": "Milano Centrale", "status": "open",
"region_details": {"id": 5, "name": "Italia"}}]}
Nested objects are read for the whole page. rind runs one query per
nested field, whatever the number of rows, never one per row. This is
what you would write by hand in DRF with select_related and
prefetch_related; here there is nothing to forget.
Coming from Django: a serializer can use a serializer of another domain. The trains send their depot with
StationBrief, which the network domain shares in itsnetwork-sharedcrate (Organising an application).
Choosing fields inside a nested field
The same three parameters choose the fields inside a nested field, with the same rules:
| Parameter | What is sent |
|---|---|
fields=id,region_details[parent] | region_details, with parent and its mandatory fields |
fields=region_details.parent | the same, in a short form; it can be repeated |
include=region_details[parent] | what the field sends by default, and parent (read even when fields is given) |
omit=region_details[name] | what the field sends, without name; omit=region_details removes the whole field |
Selections go as deep as the nested fields do, up to five levels. A name
given several times is merged: wagons_details.kind,wagons_details.capacity
is wagons_details[kind,capacity]. When a request says nothing about a
nested field, it sends what the derive fixes with fields(..).
A nested field only opens what it says. Inside a nested field, a
request can ask for the fields that the derive sends there (its
fields(..), or the child’s default fields) and the fields named in
allow(..). Any other name is unknown there, and is a 400. Without
allow, a request can narrow what the field sends, never widen it:
#![allow(unused)]
fn main() {
#[nested(key = region_id, fields(id, name), allow(parent), on_request)]
pub region_details: Option<RegionOut>,
}
GET /stations?fields=region_details.parent&page_size=2
{"parameters": {…}, "nav": {…},
"results": [{"id": 3, "code": "BRE", "name": "Brest", "status": "open",
"region_details": {"id": 3, "name": "Finistère", "parent": 2}},
{"id": 6, "code": "MIL", "name": "Milano Centrale", "status": "open",
"region_details": {"id": 5, "name": "Italia", "parent": null}}]}
allow(*) opens every field of the child serializer, the on_request
ones included.
Filtering a nested list
A many nested field can take filters, an ordering and a search. The
derive names them:
#![allow(unused)]
fn main() {
#[nested(
many,
by = Wagon::train_id(),
fields(id, position, kind, capacity),
filters = WagonFilters, // a FilterSet of the nested model
ordering = wagon_ordering, // fn() -> Ordering
search = wagon_search, // fn() -> Vec<SearchField>
on_request
)]
pub wagons_details: Option<Vec<WagonOut>>,
}
The client gives them in parentheses, right after the field’s name:
GET /trains?fields=wagons_details(kind=freight)
GET /trains?fields=wagons_details(positions=1,2;ordering=-capacity)[kind,capacity]
GET /trains?fields=wagons_details(search=sleep).kind
GET /trains?fields=wagons_details(kind=freight)[kind]&omit=number
{"parameters": {…}, "nav": {…},
"results": [{"id": 2, "wagons_details": [{"id": 4, "kind": "freight"}, {"id": 5, "kind": "freight"}]},
{"id": 3, "wagons_details": []},
{"id": 1, "wagons_details": []}]}
- Filters are separated by
;, because a value can be a comma-separated list. A value cannot hold;or). - The filters come before the selection:
wagons_details(kind=freight)[id]. - They narrow the rows of the field (a
query = ..of the derive still applies), for the whole page, in the same single query. A client’sorderingreplaces the derive’s. - These are 400 errors that name the field: an unknown filter, a wrong
value, the same filter given two values, and parentheses on a field
that takes none (a foreign key’s target, a value). For example:
{"detail": "Unknown filter(s) for `wagons_details`: colour."}. - The filterset is usually the one of the nested model’s own resource.
The ordering and the search can be that resource’s too
(
Labels::ordering,Labels::search).
A real Django application often sends values under made-up names, such as
cdata_12 for “the data with key 12”. With rind, this becomes a filter:
cdata_details(keys=12,14).
The ids of a many-to-many relation
For a many-to-many field, DRF sends the list of the related ids by
default. #[m2m_ids(..)] does the same:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/lines.rs
/// The images of its gallery, added and removed by the actions of `Images`.
#[m2m_ids(hop = network_models::LINE_IMAGES, link_order)]
pub images: Option<Vec<i64>>,
}
hop is the relation’s constant, <MODEL>_<RELATION>, made by the
model’s #[m2m(..)] (Models). The ids are read in one query
per page. They are ordered by the related key or, with link_order, by
the link table’s id, which is the order in which the links were made.
DRF reads instance.images.all(), so the ids come in the target model’s
Meta.ordering. rind does not know such an ordering, so you say it with
query = .., a query on the target. The ids are read through it, in its
order, and only those it keeps are sent (still one query per page, with
the link table joined to the target):
#![allow(unused)]
fn main() {
#[m2m_ids(
hop = network_models::LINE_IMAGES,
query = Query::<Image>::new().order_by([Image::title().asc()]),
on_request
)]
pub images_by_title: Option<Vec<i64>>,
}
query and link_order say two different orders, so they cannot be
used together.
Values the database computes
#[annotated(expr = …)] adds an SQL expression to the list’s query. It
is DRF’s queryset.annotate(..) with a field that reads the annotation:
#![allow(unused)]
fn main() {
#[annotated(expr = Station::departures().count(), on_request)]
pub departures_count: Option<i64>,
#[annotated(
expr = Train::wagons().filter(|w| w.kind().ne("freight")).sum(|w| w.capacity()),
on_request
)]
pub seats: Option<Option<i64>>,
}
GET /trains?fields=wagons_count,seats&omit=number&ordering=id
{"parameters": {…}, "nav": {…},
"results": [{"id": 1, "wagons_count": 3, "seats": 8},
{"id": 2, "wagons_count": 2, "seats": null},
{"id": 3, "wagons_count": 1, "seats": 50}]}
The expression is only computed when the field is asked for. It can be
any expression of the query layer, and the same
expression can order the list. It can use ctx, the request (its user,
its parameters), and it can be an Option: when it is None for a
request, the field is left out.
Values the application computes
Some values are easier to compute in Rust than in SQL. A loader is an async function that receives the keys of the whole page and gives back a value for each key. It is called once per page, and usually runs one query:
#![allow(unused)]
fn main() {
#[computed(loader = region_path, key = region_id, on_request)]
pub region_path: Option<Vec<String>>,
/// The names of each region's ancestors and its own, from the root.
async fn region_path(ctx: &Ctx, ids: Vec<i64>) -> Result<HashMap<i64, Vec<String>>, ApiError> {
let up = Region::ancestors_of(ids);
…
}
}
key names the model’s field whose values are given to the loader. A key
that the loader gives no value for gets the type’s default value (an
empty list here). With optional, the field is left out for that row
instead.
This replaces DRF’s SerializerMethodField, which runs once per object
and so often makes one query per row.
A loader that reads typed parameters says so on the
serializer: #[serializer(model = Station, parameters(StationFilters))].
Names that stand for fields
A column that a client shows is not always a field. A list may show
region_name, which the client reads from region_details. The
serializer can say which names bring which fields:
#![allow(unused)]
fn main() {
#[derive(Debug, Clone, Serializer)]
#[serializer(
model = Station,
alias(departures = (departures_count, planned_departures)),
prefix(region_ = region_details),
)]
pub struct StationOut { … }
}
| Request | What it brings |
|---|---|
fields=departures | departures_count and planned_departures |
fields=region_name,region_code | region_details, once |
fields=region | the field region: a field’s own name is the field |
omit=departures | removes the two counts |
- An alias is one name. A prefix matches every longer name that starts with it and that is not a field or an alias. Every matching prefix applies.
- What they bring is read as if the request had named it: it must be a
field the user may read and, inside a nested field, one the field lets
the request reach. Its own
implies(..)apply. - They take no selection and no filters:
departures[id]is a 400. Give the selection to the field itself. - A nested serializer’s aliases work inside its field.
- The derive checks that each target is a field, and that an alias is not
a field’s name. A field that brings others says so with
implies(..). - The OpenAPI document lists them in the
fieldsparameter.
Types of your own
A type of your application used in a serializer must say its JSON schema,
for the OpenAPI document. Implement
rind::api::openapi::JsonSchema for it; without it, the code does not
compile.
Reference
Kinds of fields
| Attribute | The value | DRF |
|---|---|---|
none, or #[field(..)] | the model’s column of the same name, or column = … | a model field |
#[nested(key = fk, ..)] | the target of a foreign key, through a serializer | a nested serializer |
#[nested(many, by = Child::fk(), ..)] | the rows that point to this one | many=True on a reverse relation |
#[nested(many, m2m = HOP, ..)] | the targets of a many-to-many relation | many=True on an m2m |
#[m2m_ids(hop = HOP, ..)] | the ids of a many-to-many relation | PrimaryKeyRelatedField(many=True) |
#[annotated(expr = …, ..)] | an SQL expression, computed by the database | annotate() |
#[computed(loader = f, key = k, ..)] | a value computed by a function, for the whole page | SerializerMethodField |
Keys every kind takes
| Key | Meaning |
|---|---|
name = "…" | the key in the JSON; by default the Rust field’s name (without r#) |
description = "…" | the OpenAPI description, instead of the doc comment; "" gives none |
mandatory | always sent, unless omit names it |
on_request | sent only when fields or include names it |
default_with = "param" | with on_request: sent by default when the request has param, not empty |
skip_null | a null value is left out, as if not selected; only on a field that can be null (Option<Option<T>> or Option<serde_json::Value>) |
implies(a, b) | selecting this field also selects a and b (one level) |
readable(..) | who may read the field: staff, superuser, authenticated, group = "…", with = function (Permissions) |
Keys of each kind
| Kind | Keys |
|---|---|
#[field] | column = other (the model’s field); with = function (turns the model’s value into the output’s: a date format, a unit) |
#[nested] | key = fk (a foreign key) and optionally via(Model, field) (through one intermediate model); or many with by = Child::fk() or m2m = HOP; from = field (the row’s own key, when it is not id); query = … (the rows of a many relation, when not all of them; required when the related model is scoped); fields(..); allow(..) or allow(*); for many only: filters = F, ordering = f, search = f |
#[m2m_ids] | hop = HOP (required); key = field (the row’s own key, when it is not id); link_order or query = … |
#[annotated] | expr = … (required); from = field (the row’s own key, when it is not id); with = function (the value is read as the type the function takes, then turned into the field’s) |
#[computed] | loader = f and key = field (required); optional |
The loader of a #[computed] field is
async fn(ctx: &Ctx, keys: Vec<i64>) -> Result<HashMap<i64, V>, E>.
The target of a foreign key (#[nested(key = ..)]) is read whatever the
target model’s scope, and it takes no query, filters, ordering or
search: a target that a filter left out could not be told apart from
no target.
#[serializer(..)] on the struct
| Key | Meaning |
|---|---|
model = M | the model (required) |
alias(name = field, other = (a, b)) | names that stand for fields |
prefix(name_ = field) | every longer name starting with name_ that is not a field or an alias |
skip_nulls | skip_null on every field that can be null |
parameters(P, ..) | the typed parameters its loaders read |
The doc comment of the struct becomes its description in the OpenAPI document, and each field’s doc comment becomes the field’s.
The selection syntax
list := item ("," item)*
item := name ("(" filters ")")? ("." item | "[" list "]")?
filters := filter (";" filter)*
filter := name "=" value
A selection goes at most five levels deep, and one parameter holds at
most 200 names, all levels together. Filters in omit are a 400: they
mean nothing there.
Nulls and joins
A dotted value read through a join, such as Station::manager().username(),
is null both when the key is null and when the value itself is null. On a
nullable column, skip_null leaves out both. DRF sends null for the
second case.
Inputs: what a client can write
An input says what a client may send to create or change an object, and
how each value is checked. It is the write side of Django REST
framework’s ModelSerializer: its fields with their validators,
validate_<field>(), validate(), create() and update().
The read side is a separate struct, the serializer.
That chapter explains why there are two: in short, an
answer and a write rarely have the same fields, and a field that is not in
the input cannot be written at all. In the sample, a reservation’s
status is not in ReservationIn: a client can only change it through
the cancel action.
A first input
This is the input of the sample’s stations:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/serializers.rs
use chrono::NaiveDate;
use network_models::{Region, Station};
use rind::Input;
/// What can be written on a station.
#[derive(Debug, Input)]
#[input(model = Station, unique(code))]
pub struct StationIn {
#[input(max_length = 8, validate = upper_case)]
pub code: Option<String>,
#[input(max_length = 200)]
pub name: Option<String>,
#[input(max_length = 100)]
pub city: Option<String>,
#[input(choices("open", "closed"), default = "open")]
pub status: Option<String>,
#[input(min = 0, max = 50, default = 0)]
pub platforms: Option<i32>,
#[input(default = Vec::<String>::new())]
pub services: Option<Vec<String>>,
pub opened: Option<Option<NaiveDate>>,
#[input(name = "region", fk = Region)]
pub region_id: Option<i64>,
#[input(name = "manager", fk = accounts_models::User)]
pub manager_id: Option<Option<i64>>,
/// Sent in a form, or in JSON as `{name, type, content}` (base64);
/// null removes it.
pub photo: Option<Option<rind::api::files::Upload>>,
/// `{lng, lat}`; null removes it.
pub position: Option<Option<rind::db::geo::Point>>,
}
fn upper_case(code: &str) -> Result<(), String> {
if code.chars().any(char::is_lowercase) {
return Err("Use upper case.".to_owned());
}
Ok(())
}
}
#[input(model = Station)] says which model the input writes. Each field
is a column of that model, with the same name unless column = … says
another. The resource names the input with input = StationIn
(Resources); a resource without an input is read-only.
A creation sends the fields as JSON, and gets the new object back, as a read would show it, with status 201:
POST /stations
Authorization: Bearer staff-token
Content-Type: application/json
{"code": "NTE", "name": "Nantes", "city": "Nantes", "region": 1}
{"id": 101, "code": "NTE", "name": "Nantes", "city": "Nantes", "status": "open",
"platforms": 0, "services": [], "opened": null, "region": 1, "manager": null,
"photo": null, "position": null}
status, platforms and services were not sent, so they got their
default. The answer is written by the resource’s serializer, and it
follows fields= as a read does.
A body that is not right gets a 400 with every error at once, per field, in the words that DRF uses:
POST /stations
{"code": "far-too-long", "name": " ", "city": "x", "status": "burning",
"platforms": 99, "services": "wifi", "opened": "yesterday", "region": 404,
"manager": 404}
{"code": ["Ensure this field has no more than 8 characters.", "Use upper case."],
"name": ["This field may not be blank."],
"status": ["\"burning\" is not a valid choice."],
"platforms": ["Ensure this value is less than or equal to 50."],
"services": ["Invalid value."],
"opened": ["Invalid value."],
"region": ["Invalid pk \"404\" - object does not exist."],
"manager": ["Invalid pk \"404\" - object does not exist."]}
A client written for a DRF API can show these messages as it did before.
Why every field is an Option
Every field of an input is an Option, and None means “the client did
not send this field”. This is how rind tells “not sent” from “sent”: a
PATCH changes only the fields that are Some.
A column that can be NULL has two Options: Option<Option<T>>. The
outer one says whether the field was sent; the inner one is the value,
None when the client sent null. A field with a single Option cannot
be set to null: sending null is the error “This field may not be null.”
On a creation, a field is required unless one of these is true:
- it has a
default; - it is nullable (
Option<Option<T>>); - it is marked
optional: the column’s default in the database then applies.
A missing required field is “This field is required.”:
POST /stations
{}
{"code": ["This field is required."],
"name": ["This field is required."],
"city": ["This field is required."],
"region": ["This field is required."]}
POST, PUT and PATCH
The three write methods read the same input, in different ways:
POSTcreates an object. A field that is not sent takes itsdefault. A required field that is not sent is an error.PUTreplaces the object’s fields. Every required field must be sent, as for a creation. The fields that are not required and not sent keep their value: adefaultis only for creations.PATCHchanges the fields that are sent, and nothing else. No field is required.
All three answer the object as it is after the write (201 for a creation, 200 for the others).
A write must leave the object where the user can still see it. When a user’s mode only shows some rows, a write that would move the object out of those rows is refused with a 403, and nothing is written. DRF has no such check.
Checking a value
Each field can carry checks. They run on the value that was sent, and every failure is reported:
#![allow(unused)]
fn main() {
#[input(max_length = 8, validate = upper_case)]
pub code: Option<String>,
#[input(choices("open", "closed"), default = "open")]
pub status: Option<String>,
#[input(min = 0, max = 50, default = 0)]
pub platforms: Option<i32>,
}
max_length = N: a text of at mostNcharacters.min = Nandmax = N: bounds for a number.choices("a", "b"): the values accepted, as DRF’sChoiceField.validate = function: a check of your own, as DRF’svalidate_<field>(). The function receives the value and gives backErr(message)to refuse it:fn(&T) -> Result<(), String>.
Texts get some care, as in DRF:
- A text is written without the spaces around it:
" Rennes "is written as"Rennes".keep_spaceswrites it as it was sent. - An empty text (or one made only of spaces) is refused with “This field
may not be blank.”.
allow_blankaccepts it. normalize = functionchanges the text before it is written, for examplenormalize = str::to_uppercasefor a code. It runs after the spaces are removed, and before the checks.
JSON values are read strictly. "12" is not a number, and "false"
is not a boolean: both are “Invalid value.”. A value of the wrong type
never reaches the checks.
Checks across fields
A rule that involves several fields goes on the struct, as DRF’s
validate():
#![allow(unused)]
fn main() {
// A fragment: the sample's JourneyIn does not have this check.
#[derive(Debug, Input)]
#[input(model = Journey, validate = times_in_order)]
pub struct JourneyIn { … }
fn times_in_order(input: &JourneyIn) -> Result<(), Vec<(&'static str, String)>> {
match (input.departs_at, input.arrives_at) {
(Some(departs), Some(arrives)) if arrives <= departs => {
Err(vec![("arrives_at", "Must be after the departure.".to_owned())])
}
_ => Ok(()),
}
}
}
Each error names the field it belongs to. The function sees only what the
body sent: on a PATCH, a field that was not sent is None. A check
that needs the object as it is in the database goes in a
hook.
Foreign keys, uniqueness and many-to-many fields
Some checks need the database. The input runs them itself, before the write, so that the client gets an answer per field rather than a refused constraint.
A foreign key is checked with fk = Model: the key sent must be the
key of a row that exists. Most foreign keys also have a name, so that
the client writes the key under the relation’s name, as DRF does and as
the serializer sends it:
#![allow(unused)]
fn main() {
#[input(name = "region", fk = Region)]
pub region_id: Option<i64>,
}
A key that does not exist is
"Invalid pk \"404\" - object does not exist.". A field without fk
is not checked by the input; the database’s foreign key still refuses a
wrong key, but the answer is then a general 400 that names the
constraint, not the field.
Note:
rind add resourcewrites the input with one field per column, under the column’s name, and withoutfk. For a foreign key such asauthor_id, add#[input(name = "author", fk = Author)]yourself.
Uniqueness is checked with unique(..) on the struct:
#![allow(unused)]
fn main() {
#[input(model = Station, unique(code))]
}
No other row may have the same value (or, with several fields, the same
values together). The object being changed does not count. The answer is
{"code": ["An object with this value already exists."]} for one field,
and {"non_field_errors": ["The fields a, b must make a unique set."]}
for several. Uniqueness is only checked when every other check passed.
A many-to-many field is a list of ids, with m2m = HOP. HOP is the
constant that the model’s #[m2m(..)] makes (LINE_IMAGES):
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/lines.rs
/// The images of its gallery, all at once: the ids of existing images.
#[input(m2m = network_models::LINE_IMAGES)]
pub images: Option<Vec<i64>>,
}
Each id must exist. After the row is written, in the same transaction,
the link table’s rows become exactly that set: links that are not in the
list are deleted, and missing ones are added. This is DRF’s
ManyRelatedField and its set(). A field that is not sent leaves the
links as they are.
Forms and files
A body can also be a form (multipart/form-data). Its values are text,
so rind reads each one as the field’s type: 12 for a number, true for
a boolean. An empty value for a nullable field that is not a text is
null.
A field of type Upload is a file. It can be sent in a form, or in JSON
as {name, type, content} with the content in base64. The file is stored
before the write. folder = "images" stores it in that folder, as
images/<sha1>/<name>, as Django’s upload_to does. See
Files.
How a write can be checked or completed
Some writes need more than an input: a check that reads other tables, a
column the server sets itself, a row to write elsewhere. In DRF, this
goes in perform_create(), in serializer.create(), or in the model’s
save(). In rind, it goes in hooks.
A resource declared with hooks implements the trait Writes itself.
Each hook has a default that does nothing, so you write only the ones you
need:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
#[derive(Resource)]
#[resource(model = Reservation, path = "reservations", /* … */ input = ReservationIn, hooks)]
pub struct ReservationResource;
impl Writes for ReservationResource {
async fn creating(
ctx: &Ctx,
input: &ReservationIn,
insert: Insert<Reservation>,
) -> Result<Insert<Reservation>, ApiError> {
let user = ctx.user.as_ref().ok_or(ApiError::Unauthorized)?;
// The room is checked, and kept until the reservation is written:
// the journey's row is locked.
booking_ops::check(&ctx.db, request(input)).await.map_err(refused)?;
Ok(insert
.value(Reservation::code(), new_code())
.value(Reservation::booked_by_id(), user.id))
}
}
}
creating receives the input that was read and checked, and the insert
it produced. It can refuse the write by returning an error, or add
columns to the insert: here the reservation’s code, and the user who made
it.
Every hook runs in the write’s transaction: ctx.db is that
transaction. If a hook fails, nothing of the write is kept.
| Hook | When it runs | What it is for |
|---|---|---|
creating(ctx, input, insert) | before the insert | checks that need the database; columns a creation sets by itself |
updating(ctx, current, input, partial, update) | before the update | the same, with the object as it is now; partial is false for a PUT |
saved(ctx, id, input, created) | after the insert or the update | what a write changes outside the object’s own row |
deleting(ctx, id) | instead of the delete | what a deletion takes with it (below) |
To refuse a write on one field, return an ApiError::Validation. It is
answered as the input’s own errors are:
#![allow(unused)]
fn main() {
fn invalid(field: &str, message: &str) -> ApiError {
ApiError::Validation([(field.to_owned(), vec![message.to_owned()])].into())
}
}
Coming from Django: there are no signals. What must happen when something else happens is an operation of the domain, a plain function, and each write that needs it calls it by name. You can read a write and see everything it does.
Going further
The order of a write. A creation runs these steps, in one transaction:
- The body is read and checked by the input, then the foreign keys and the uniqueness are checked. Any error stops here.
- The files sent are stored.
- The model’s behaviours, then the resource’s, change the insert.
- The
creatinghook changes the insert, or refuses it. - The row is inserted, and the model’s own hooks run on it.
- The many-to-many links are written.
- The
savedhook runs. - The object is read back through the user’s mode, and answered.
An update runs the same steps with updating. An update that sets
nothing (a PATCH with an empty body) runs no statement, but still runs
saved.
The answer’s parameters. Writes::answer_params(params, created)
gives the query parameters the written object is answered with. By
default, they are the request’s own, so fields= applies to a write’s
answer as it does to a read.
Writing an object of another resource. An action that creates or
changes an object of another resource, in its own transaction, can run
that resource’s whole write with
rind::api::resource::insert_from::<R>(ctx, &body) and
update_from::<R>(ctx, ¤t, id, &body, partial): the input, the
behaviours and the hooks, without the permission check or the answer.
Deleting
By default, DELETE runs one statement and answers an empty 204. What
points to the row is then the database’s business: its ON DELETE
rules, which the migrations write from the models
(#[fk(.., on_delete = …)], see Models).
A resource can instead follow the models itself, in its deleting hook.
This lets it say what a deletion would take with it before doing it,
much as Django’s admin shows the objects a deletion would remove:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
/// What a deletion of a station reads; the resource lists it,
/// `#[resource(.., parameters(StationDelete))]`.
#[derive(Debug, Parameters)]
#[parameters(read_by(StationResource), on(destroy))]
pub struct StationDelete {
/// `yes` deletes; without it the deletion is only tried.
pub confirm: Option<Confirm>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, ParamValue)]
pub enum Confirm {
Yes,
}
impl Writes for StationResource {
async fn deleting(ctx: &Ctx, id: i64) -> Result<Deleted, ApiError> {
let deleted = delete::cascade(&ctx.db, ctx.tables(), Station::TABLE, vec![id])
.await
.map_err(write_error)?;
Ok(Deleted {
body: Some(json!({ "count": deleted.count, "details": deleted.details })),
simulated: ctx.parameters::<StationDelete>().confirm != Some(Confirm::Yes),
})
}
}
}
Deleted says what the deletion answers. With a body, the answer is a
200 with that body; without one, an empty 204. With simulated, the
transaction is rolled back, so nothing is deleted.
Without confirm=yes, the deletion is only tried:
DELETE /stations/4
{"count": 1, "details": [["network_station", 1]]}
Nothing is deleted. DELETE /stations/4?confirm=yes deletes, and answers
the same. confirm is a typed parameter:
?confirm=sure is a 400, and the OpenAPI document lists confirm on the
deletion.
delete::cascade follows each foreign key’s on_delete, whoever would
apply it otherwise: the database (the migrations’ ON DELETE), or nobody
(a key marked in_code, or a database that Django made, whose keys do
nothing). Where the database would have done it, nothing is left for it
to do; either way, the walk is what counts the rows.
A key that neither cascades nor empties (restrict, or no rule) refuses
the deletion while a row that is not deleted with the rest points to the
object. The error is Referenced, and the answer is a 409 that names
the key:
{"detail": "This object cannot be deleted: booking_reservation.wagon_id still refers to it.",
"referenced_by": "booking_reservation.wagon_id"}
Django raises ProtectedError in this case, which is a 500 unless
something catches it.
Tried first: safe_delete
The same thing is ready made, in the form that a real Django application
used: the deletion is only tried unless the request says ?doit=really,
and the answer is {"count", "details"} by table name. The function
reads the parameters SafeDelete, which the resource lists: without
them, safe_delete does not compile for that resource.
#![allow(unused)]
fn main() {
#[resource(model = Line, path = "lines", delete, hooks,
parameters(rind::api::delete::SafeDelete))]
pub struct LineResource;
impl Writes for LineResource {
async fn deleting(ctx: &Ctx, id: i64) -> Result<Deleted, ApiError> {
rind::api::delete::safe_delete::<LineResource>(ctx, id).await
}
}
}
A row that refuses (restrict, no_action) makes it a 409 that names
it, whether the deletion is tried or confirmed.
Tables no model describes
When you port part of a database to rind, you model some tables. The others still belong to the old application, and some of them point to the modelled ones. A deletion must know them, or the database refuses it. The application gives them as foreign tables: a name, a primary key, the foreign keys, and nothing else.
#![allow(unused)]
fn main() {
static FOREIGN: &[Table] = &[Table::foreign("sales_billitem", "id", &[
ColumnDef::key("bill_id", "sales_bill", OnDelete::Cascade),
ColumnDef::key("producer_id", "structures_producer", OnDelete::SetNull),
])];
rind::Application::new("The shop", env!("CARGO_PKG_VERSION"))
.foreign_tables(FOREIGN.to_vec())
}
A deletion walks them as it walks the models’ tables: into them, on from
them (sales_billitem to its own dependants), emptying their keys, or
refused by them. They are never migrated, never read otherwise, and not
in the OpenAPI document. dbcheck checks that each one exists, with its
key columns and their foreign keys. rind inspect writes them, from the
database and from the old application’s rules (Inspect).
Reference
Keys of a field
| Key | Meaning |
|---|---|
name = "…" | the key in the body, when it is not the field’s name |
column = … | the model’s column, when it is not the field’s name |
description = "…" | the OpenAPI description, instead of the doc comment (or the model column’s); "" gives none |
max_length = N | a text of at most N characters |
min = N, max = N | bounds for a number |
choices("a", "b") | the values accepted |
default = … | the value of a creation that does not send the field; for a nullable field too, a value and not null |
optional | can be left out of a creation: the column’s database default applies |
allow_blank | an empty text is accepted |
keep_spaces | a text is written as sent (by default, without the spaces around it, as DRF does) |
normalize = function | the text written is the function’s result (str::to_uppercase), after the trim and before the checks; text fields only |
validate = function | a check of your own, fn(&T) -> Result<(), String> |
fk = Model | the key must be the key of an existing row (for a list, each key) |
m2m = HOP | an Option<Vec<i64>>: the ids of a many-to-many relation’s targets; each must exist; the links become that set after the row is written, in its transaction; not sent, they are left as they are; no fk, no default |
folder = "…" | an Upload stored in that folder, folder/<sha1>/<name>, as Django’s upload_to (Files) |
skip | read and checked, but not a column: for a hook to use |
Keys of the struct
| Key | Meaning |
|---|---|
model = M | the model written (required) |
unique(a, b) | no other row has these values together; can be given several times |
validate = function | a check across fields, fn(&Self) -> Result<(), Vec<(&'static str, String)>> |
Error messages
| Message | When |
|---|---|
This field is required. | a required field is missing from a POST or a PUT |
This field may not be null. | null sent for a field that is not nullable |
This field may not be blank. | an empty text, without allow_blank |
Invalid value. | a value of the wrong type |
Ensure this field has no more than N characters. | max_length |
Ensure this value is greater than or equal to N. | min |
Ensure this value is less than or equal to N. | max |
"x" is not a valid choice. | choices |
Invalid pk "x" - object does not exist. | fk, m2m |
An object with this value already exists. | unique with one field |
The fields a, b must make a unique set. | unique with several fields, under non_field_errors |
A body that is not a JSON object is a 400, {"detail": "Expected a JSON object."},
and a body that is not JSON at all is {"detail": "Invalid JSON: …"}.
A field in the body that the input does not have is ignored, as in DRF.
Filters, search, ordering, pages
A list endpoint rarely sends every row in one block. The client narrows
it (?status=open), searches it (?search=rennes), sorts it
(?ordering=-platforms) and reads it one page at a time (?page=2).
In Django REST framework, these four jobs belong to four tools:
django-filter’s FilterSet, DRF’s SearchFilter, DRF’s
OrderingFilter, and a pagination class. rind has the same four, and
this chapter takes them in that order.
All four are declared on the resource, and all four are described in the OpenAPI document without extra work.
Filtersets
A filterset is a struct whose fields are the filters of a list. Each
field is one query-string parameter. It is the equivalent of a
django-filter FilterSet, written as a Rust struct with a derive:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
use network_models::{Region, Station};
use rind::FilterSet;
use rind::prelude::*;
#[derive(Debug, Default, FilterSet)]
#[filterset(model = Station)]
pub struct StationFilters {
#[filter(path = Station::status())]
pub status: Option<String>,
#[filter(path = Station::city())]
pub city: Option<String>,
/// Stations offering every one of these services.
#[filter(path = Station::services(), lookup = contains)]
pub services: Option<Vec<String>>,
#[filter(path = Station::platforms(), lookup = ge)]
pub min_platforms: Option<i64>,
/// Stations of a region, or of any region below it.
#[filter(method = in_region, alias = "in")]
pub region: Option<i64>,
#[filter(method = has_departures)]
pub has_departures: Option<bool>,
}
}
The resource names its filterset with filters = …:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[derive(Resource)]
#[resource(model = Station, path = "stations", out = StationOut,
filters = StationFilters, /* … */)]
pub struct StationResource;
}
A client then filters the list with the field names:
GET /stations?status=open&min_platforms=4
GET /stations?services=wifi,bar
The first request runs WHERE status = 'open' AND platforms >= 4. The
second keeps the stations whose services array holds both wifi and
bar. Filters add up: every filter the request uses must match.
Every field of a filterset is an Option. It is None when the request
does not use the filter, and the filter is then not applied. A field
without Option, or a field without #[filter(..)], does not compile.
How the value is read
The type inside the Option says how the parameter’s text is read:
String: the text as it is sent.bool:trueor1,falseor0(in any case).- a number (
i64,f64…) or a date (NaiveDate): parsed with the type’sFromStr.?day=2030-05-01reads aNaiveDate. Vec<…>of one of these: a comma-separated list.?status=planned,arrivedgivesvec!["planned", "arrived"]. Empty items are skipped (1,,2is[1, 2]).
A filter on a column: path and lookup
The most common filter compares a column with the value. path names
the column, through the model’s typed paths (Station::status()), and
lookup says how to compare. This is django-filter’s
filters.CharFilter(field_name="status", lookup_expr="exact").
Without a lookup, a single value is compared with = (eq), and a
list with IN (in):
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/filters.rs
/// One of these statuses.
#[filter(path = Journey::status(), alias = "status")]
pub statuses: Option<Vec<String>>,
}
GET /journeys?status=planned,arrived
This runs WHERE status IN ('planned', 'arrived').
The other lookups compare differently: ge for “at least”, contains
for an array that holds every value, and so on. The full list is in
the lookups table at the end of this chapter.
A path can follow a foreign key, as in a query: any typed path of the model works.
A filter written as a function: method
Some filters are not a comparison: they need a sub-query, a join, or a
computation. For these, method names a function. The function receives
the list’s query and the value, and gives back the query, narrowed. This
is django-filter’s filters.BooleanFilter(method="has_departures").
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
/// `region`: the stations of the region and of every region below it.
pub fn in_region(q: Query<Station>, region: i64) -> Query<Station> {
let below = Region::descendants(region);
q.with(&below)
.join_cte(&below.r(), Station::region_id().eq(below.col::<i64>("id")))
}
/// `has_departures`: stations a journey leaves from (or none does).
pub fn has_departures(q: Query<Station>, value: bool) -> Query<Station> {
let leaving = Query::<Journey>::new()
.filter(Journey::origin_id().eq(Station::id().outer()))
.exists();
q.filter(if value { leaving } else { !leaving })
}
}
The value is passed by value for a number, a boolean or a date. A text is
lent as &str, and a list as a slice (&[i64]):
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/filters.rs
pub fn through(q: Query<Journey>, stations: &[i64]) -> Query<Journey> { … }
}
A method is a plain function, not an async one. When it needs data
from the database first (an object by its id, say), it writes that
lookup as a sub-query of the query it returns, as has_departures does
above. The database runs everything in one statement.
Another name for a parameter: alias
alias = "…" gives a filter a second name. In the stations’ filterset,
?in=3 is the same as ?region=3. Both names are in the OpenAPI
document. You can repeat alias for more names.
When you want the parameter to have a different name from the field
(for example, a name that is a Rust keyword), use param = "…".
A filter that reads the other filters
A method declared with filters also receives the whole filterset, as
&Self. It can then read the values of the other filters. This is
useful when one filter only means something together with another:
#![allow(unused)]
fn main() {
// Not in the sample: a fragment.
#[filter(method = longer_than, filters)]
pub min_km: Option<f64>,
pub fn longer_than(q: Query<Journey>, km: f64, filters: &JourneyFilters) -> Query<Journey> {
match filters.origin {
Some(origin) => …,
None => q,
}
}
}
A filter that reads the request
A method declared with ctx also receives the request’s context,
&Ctx. It can read who is asking (ctx.user), which action runs
(ctx.action()), and the request’s typed parameters.
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/filters.rs
use rind::api::Ctx;
/// `true`: only the reservations the user made.
#[filter(method = mine, ctx)]
pub mine: Option<bool>,
pub fn mine(q: Query<Reservation>, mine: bool, ctx: &Ctx) -> Query<Reservation> {
match ctx.user.as_ref() {
Some(user) if mine => q.filter(Reservation::booked_by_id().eq(user.id)),
_ => q,
}
}
}
Why make this a filter, and not part of a mode’s query? Because a filter is listed in the OpenAPI document, and a client can use it inside a nested list too. A mode’s query that read the query string by hand would be invisible to both.
With both filters and ctx, the function takes four arguments, in
this order: (query, value, filters, ctx).
In a nested list
(?fields=reservations_details(mine=1)), filters holds the nested
field’s filters, and ctx is still the whole request.
Coming from Django: a django-filter method can read
self.request.query_paramsfor any parameter it likes. A rind filter cannot read a parameter by its name. A value that is not a filter is a typed parameter, declared in a struct and read withctx.parameters::<P>(). This is what keeps the OpenAPI document complete.
What happens with wrong or missing values
rind follows django-filter here:
- An empty value is ignored:
?status=does not filter. - An unknown parameter is ignored:
?whatever=1does not filter, and is not an error. - A boolean that cannot be read leaves the filter off:
?has_departures=maybelists every station. - Any other value that cannot be read is a 400, which names the parameter. All the errors of the request come back together:
GET /stations?region=abc
{"region": ["Enter a number."]}
The errors come before the first query runs.
Filters apply to lists. A retrieve (GET /stations/1) ignores them.
Search
?search=… finds the rows where every term of the search appears in at
least one of the resource’s search fields. It is DRF’s SearchFilter
with its search_fields. Each #[search(..)] attribute on the resource
adds one field, with a mode that says how the term must match:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[search(Station::name(), unaccent)]
#[search(Station::code(), starts_with)]
pub struct StationResource;
}
GET /stations?search=gare rennes
This finds the stations whose name contains both “gare” and “rennes”,
in any case and with or without accents. A station whose code starts
with “RNS” is found by ?search=rns.
The value is split as DRF splits it: on spaces and on commas. A quoted
phrase ("train de nuit") stays one term. Each term must match at least
one field; a row is listed when every term matches.
% and _ in a search are plain characters, not SQL wildcards.
The search modes
A mode is the second argument of #[search(..)]. Without one, the mode
is contains.
| Mode | A term matches when… | DRF prefix |
|---|---|---|
contains | it is anywhere in the text, whatever the case | (none) |
starts_with | the text starts with it, whatever the case | ^ |
exact | it is the whole value, whatever the case | = |
unaccent | it is anywhere in the text, whatever the case and the accents (PostgreSQL’s unaccent extension) | & |
full_text | PostgreSQL’s full-text search finds it | @ |
unaccent_full_text | full-text search finds it, whatever the accents | # |
regex | the text matches it as a regular expression, whatever the case (~*) | $ |
The prefixes ^, =, @ and $ are DRF’s own. & and # come from a
real Django application that extended DRF’s search filter; rind keeps
them as modes.
A regular expression that the database cannot read is a 400. A regular expression runs as it is sent: on a large table, it reads every row.
Searching through a tree
A station belongs to a region, and regions form a tree (a country, its
regions, their departments). A search for “Bretagne” should find the
stations of Brittany, and also the stations of every department inside
it. tree(..) does this:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[search(tree(Station::region_id(), Region::name()), unaccent)]
}
The first argument is the row’s key to the tree (Station::region_id()).
The second is the tree’s column to search (Region::name()). A station
matches when its region’s name, or the name of any region above it,
matches the term, at any depth. rind walks the tree once per term
(Region::subtree_where).
Coming from Django: a Django project writes this as one search field per level:
region__name,region__parent__name,region__parent__parent__name… and stops at some depth. A tree search has no depth limit. See Trees.
Going further: how the case-insensitive modes are written
contains, starts_with, exact and unaccent are written the way
Django writes its case-insensitive lookups on PostgreSQL:
UPPER(field) LIKE UPPER('%term%'), not ILIKE. The rows found are the
same, except for a few rare letters (such as the Turkish dotted i). It
is also faster when the database’s locale is not C, because ILIKE
lowercases both sides on every row: 1.6 times faster on 475,000 French
communes in fr_FR.utf8.
An index that helps these searches is a trigram index on the same expression:
CREATE INDEX … USING gin (upper(name) gin_trgm_ops);
Ordering
?ordering=name sorts a list by a name; ?ordering=-name sorts it the
other way. This is DRF’s OrderingFilter. The resource says which names
a client may use (DRF’s ordering_fields), and the ordering to use when
the request gives none (DRF’s ordering):
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[ordering(
by(id, name, code, platforms, departures = Station::departures().count()),
default("name")
)]
pub struct StationResource;
}
GET /stations?ordering=-platforms,name
This sorts by platforms, most first, then by name. Several names are separated by commas.
A name in by(..) is a column of the model, by default. With =, it is
any expression: departures = Station::departures().count() sorts by
the number of journeys that leave from the station.
A name that is not allowed is dropped, as DRF does. When no allowed name is left, the default ordering applies. An unknown name is never an error.
Coming from Django: there is no
Meta.orderingon the model. A resource says its default ordering with#[ordering(.., default("name"))].
Every ordering ends with the primary key
rind adds the primary key at the end of every ordering. This makes the order total: two rows never compare equal. Without it, two stations with the same name could swap places between two requests, and a client reading page 1 and then page 2 could see one of them twice, and miss another. With it, pages never overlap and never skip a row.
A name for the default only: hidden
Sometimes the default ordering needs a name that clients should not use.
In Django, this is ordering naming a field that ordering_fields does
not list. In rind, such a name goes in hidden(..), always with an
expression:
#![allow(unused)]
fn main() {
// A fragment: the stations by region name, then by name.
#[ordering(
by(id, name, code),
default("region__name", "name"),
hidden(region__name = Station::region().name())
)]
}
?ordering=region__name is then dropped like an unknown name, but the
default ordering still uses it.
An ordering that depends on the request
An ordering expression is given the request’s context, ctx. It can
read typed parameters, for
example to sort by distance to a point the request sends. When the
expression is an Option and is None for this request, the name is
dropped like an unknown one.
Pages
A list is always answered in pages. The answer has three parts: the
names of the paging parameters, where the page sits (nav), and the
rows (results):
GET /stations?page_size=2
{
"parameters": { "page": "page", "pagesize": "page_size" },
"nav": { "size": 2, "page": 1, "next": 2, "prev": null, "count": 6, "pages": 3 },
"results": [ … ]
}
?page=2asks for the second page.?page=lastasks for the last one.?page_size=20asks for 20 rows per page.countis the number of rows after the filters and the search, not the number of rows in the table.
A page that does not exist (?page=99, ?page=abc) gives the first
page, not an error. A page size that is missing, not a number, or not
positive gives the resource’s default size. A size larger than the
resource’s maximum is cut down to the maximum.
The default size is 100 rows, and the maximum is 50,000. A resource can change both:
#![allow(unused)]
fn main() {
#[resource(model = Station, path = "stations", out = StationOut,
page_size = 25, max_page_size = 1000)]
}
Coming from Django: this is DRF’s
PageNumberPaginationwithpage_size_query_param = "page_size"andmax_page_size, set once for every resource. The answer’s shape (parameters,nav,results) is the one of a real Django application’s custom pagination class, so its front end works unchanged. Unlike DRF, a page out of range is not a 404.
Reference
#[filterset(..)]
| Key | Meaning |
|---|---|
model = M | The model whose rows the filters narrow. Required. |
#[filter(..)]
Every field of a filterset has one, and its type is Option<T>.
| Key | Meaning |
|---|---|
path = M::col() | Compares this column (or path) with the value. |
lookup = … | How path compares: see the next table. Only with path. |
method = f | Calls f(query, value) instead. Either path or method, not both. |
filters | With method: f also takes the filterset, &Self. |
ctx | With method: f also takes the request, &Ctx (after filters). |
alias = "…" | One more name for the parameter. Repeatable. |
param = "…" | The parameter’s name, when it is not the field’s. |
description = "…" | The OpenAPI description, instead of the doc comment. "" gives none. |
A filter may not be named no_cache or nocache: those names belong to
the cache. No filter may share a name with another parameter
of the resource either (see
Parameters).
The lookups
lookup | SQL | Django lookup | Use |
|---|---|---|---|
eq (default for one value) | col = $1 | exact | |
in (default for a list) | col IN (…) | in | a Vec |
ne | col <> $1 | exclude(…) | |
lt, le, gt, ge | <, <=, >, >= | lt, lte, gt, gte | |
contains | col @> $1 | contains (array) | an array column holds every value |
overlap | col && $1 | overlap | an array column holds at least one value |
iexact | UPPER(col) = UPPER($1) | iexact | |
icontains | UPPER(col) LIKE UPPER('%term%') | icontains | % and _ in the value are plain characters |
istartswith | UPPER(col) LIKE UPPER('term%') | istartswith | the same |
under(Model, ..) | col IN (subtree) | — | a key to a tree model: the value’s rows and every row below them (Model::subtree) |
above(Model, ..) | col IN (ancestry) | — | a key to a tree model: the value’s rows and every row above them (Model::ancestry) |
The case-insensitive lookups are written as Django writes them on PostgreSQL, for the reasons given in the search section.
The tree lookups take the options of the tree walk after the model:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
/// Stations of these regions, or of a region one level below them.
#[filter(path = Station::region_id(), lookup = under(Region, max_down = 1))]
pub regions_under: Option<Vec<i64>>,
}
| Lookup | Options |
|---|---|
under | max_down, down_to_level, at_level, include_self |
above | max_up, up_to_level, at_level, include_self |
#[search(..)]
#[search(path, mode)] or #[search(tree(key, tree_column), mode)],
repeatable. The modes are contains (the default), starts_with,
exact, unaccent, full_text, unaccent_full_text and regex.
#[ordering(..)]
| Key | Meaning |
|---|---|
by(a, b, c = expr) | The names a client may order by: a column of the model, or name = expression. |
default("a", "-b") | The ordering when the request gives none (or none allowed). |
hidden(name = expr) | Names only the default may use. |
Page parameters
| Parameter or key | Meaning |
|---|---|
?page=N, ?page=last | The page; out of range or unreadable gives page 1. |
?page_size=N | Rows per page, up to the maximum. |
#[resource(page_size = N)] | The default size (100). |
#[resource(max_page_size = N)] | The maximum size (50,000). It also limits an export. |
Parameters: the other query parameters
Most of a query string is read by rind itself, or by what you derive:
the filters, search, ordering, page and page_size,
the field selection (fields, omit, include), and an action’s
#[query] arguments. But a request sometimes says other things:
- “really delete it” (
?confirm=yes), - “show the hidden ones too” (
?show_retired=true), - “do not narrow this nested list” (
?filter_wagons=0).
These values are not filters: they do not narrow a list. In Django, a
view would read them with self.request.query_params.get("confirm"). In
rind, they are typed parameters: you declare them as the fields of a
struct, and the code reads the struct.
A first example
When a client deletes a station, the sample only tries the deletion
and answers with what would be deleted. It deletes for real only when
the request says ?confirm=yes. The parameter is a struct:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
use rind::{ParamValue, Parameters};
/// What a deletion of a station reads.
#[derive(Debug, Parameters)]
#[parameters(read_by(StationResource), on(destroy))]
pub struct StationDelete {
/// `yes` deletes; without it the deletion is only tried, and the
/// answer says what it would delete.
pub confirm: Option<Confirm>,
}
/// [`StationDelete::confirm`]'s value.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ParamValue)]
pub enum Confirm {
Yes,
}
}
The resource lists the struct in parameters(..):
#![allow(unused)]
fn main() {
#[derive(Resource)]
#[resource(model = Station, path = "stations", /* … */ parameters(StationDelete))]
pub struct StationResource;
}
And the code reads it, already typed, with ctx.parameters::<P>():
#![allow(unused)]
fn main() {
impl Writes for StationResource {
async fn deleting(ctx: &Ctx, id: i64) -> Result<Deleted, ApiError> {
let deleted = /* … */;
Ok(Deleted {
body: Some(json!({ "count": deleted.count, "details": deleted.details })),
simulated: ctx.parameters::<StationDelete>().confirm != Some(Confirm::Yes),
})
}
}
}
A client then sends:
DELETE /stations/4?confirm=yes
And a value that is not allowed is refused before anything runs:
DELETE /stations/4?confirm=please
{"confirm": ["Expected one of: yes."]}
The parameter is also in the OpenAPI document of DELETE /stations/{id},
with its description (the doc comment) and its allowed values (yes).
Why a struct, and not request.query_params.get("confirm")? Because the
name is then written once. A misspelt name does not compile, a wrong
value is a clear 400, and the OpenAPI document cannot forget the
parameter. The rest of this chapter explains these guarantees.
The fields and their types
Each field of the struct is one parameter. Its name is the field’s name.
A parameter is never required: a client may always leave it out. So each field says what it is when it is not sent, in one of two ways:
- The field is an
Option<T>. It isNonewhen the parameter is not sent, or is sent empty (?confirm=). - The field has a default:
#[parameter(default)]uses the type’sDefault, and#[parameter(default = …)]gives a value.
A field that is neither does not compile. An Option with a default
does not compile either.
Here is a richer example, not taken from the sample:
#![allow(unused)]
fn main() {
// A fragment: what a list of trains could read beside its filters.
#[derive(Parameters)]
#[parameters(read_by(TrainResource, TrainOut), on(list, retrieve))]
pub struct TrainParams {
/// A superuser's: `true` adds the retired trains to the list,
/// `only` lists them alone.
#[parameter(default)]
pub show_retired: ShowRetired,
/// `0`: every wagon of a train, not only those in service.
#[parameter(default = true)]
pub filter_wagons: bool,
}
#[derive(ParamValue, Default, PartialEq)]
pub enum ShowRetired {
#[default]
False,
True,
Only,
}
}
#![allow(unused)]
fn main() {
let show = &ctx.parameters::<TrainParams>().show_retired;
if *show == ShowRetired::Only { /* … */ }
}
The value’s type says how the text is read:
String: the text as it is sent.bool:true,false,1or0, in any case. Anything else is a 400.- integers and floats: parsed as numbers.
Vec<T>: a comma-separated list. Empty items are skipped.- an enum that derives
ParamValue: one of its variants, written in snake case (ShowAllisshow_all), or the name you give with#[value(name = "…")]. The OpenAPI document lists the allowed values.
An enum is usually the best type for a parameter with a few allowed
values: the code gets a match, and the client gets the list of values.
A parameter that is only present: present
Some old APIs use a parameter without a value: ?flat. What matters is
only whether the name is in the query string. #[parameter(present)] on
a bool field reads it that way: it is true when the name is there,
whatever its value, even empty.
#![allow(unused)]
fn main() {
/// The answer without its nested objects.
#[parameter(present)]
pub flat: bool,
}
In a Django view, this is request.query_params.get("flat") is not None.
Names and descriptions
#[parameter(name = "…")]gives the parameter another name than the field’s.#[parameter(alias = "…")]gives it one more name. You can repeat it.- The field’s doc comment is the parameter’s description in the OpenAPI
document.
#[parameter(description = "…")]replaces it.
A value that cannot be read
A value that does not parse is a 400 that names the parameter:
{"show_retired": ["Expected one of: false, true, only."]}
It comes before the first query, together with the filters’ own errors.
Coming from Django: a Django view that reads
request.query_params.get(..)usually ignores a wrong value and falls back to its default. rind is stricter: a wrong value is an error the client sees. (A filter’s boolean is the one exception, because django-filter ignores it: see Filters.)
When they are read
on(..) names the operations that read the struct. Before such an
operation starts, rind reads the struct from the query string, and a
wrong value is a 400. The OpenAPI document lists the parameters on
these operations only.
The names are list, retrieve, create, update, destroy, and the
names of the resource’s actions. update covers both PUT
and PATCH; writing partial_update does not compile. Without on(..),
the struct is read by every operation of the resource.
A struct can also be read where on(..) does not say: in another
operation, or in a job. It is then read the first time the
code asks for it. A value that does not parse at that point gives the
field’s default, because it is too late for a 400.
In every case, ctx.parameters::<P>() never fails and never panics.
Each struct is read at most once per request.
What does not compile
The point of typing parameters is that a mistake is a compile error, not a parameter silently ignored, nor one the document forgets.
-
A misspelt parameter.
ctx.parameters::<StationDelete>().confrimis a field that does not exist. -
A struct that is read but not listed.
read_by(..)names the resources and serializers that read the struct. Each of them must list it in its ownparameters(..). Otherwise:error[E0277]: `StationResource` reads the parameters `StationDelete` without listing them -
A struct shared by many resources. Such a struct names no reader in
read_by. Instead, the functions that read it say whose parameters they are, with a bound:safe_delete::<R: Declares<SafeDelete>>. A resource that deletes throughsafe_deletewithout listingSafeDeletedoes not compile. -
The same name twice on a resource. A name may appear only once among the resource’s filters, its
parameters(..), its behaviours’ parameters, and rind’s own names:page,page_size,ordering,search,fields,omit,include,format,export,no_cacheandnocache. -
A parameter read by its name.
ctx.params.get("x")does not compile. The methods that read the query string by name belong to a trait that only rind’s own crates import (rind::__private::RawParams). An application that imports it steps out of the checks on purpose. Nothing in the sample, or in a project made byrind new, does.
Two places are left for you to keep in step by hand:
- a filterset written by hand (
impl FilterSetinstead of the derive). It reads through the parser rind gives it, and lists its names inparameters(); - a hand-written
Action’sparameters, which describes what it reads.
Testing a struct
rind::api::parameters::read_from::<P>("confirm=yes") reads a struct
from a query string, as a request would. It returns the 400 error when
a value does not parse. It is meant for tests.
Filtersets are parameters too
A derived filterset is also a struct of typed parameters,
read on list and retrieve. This is useful in two cases.
A filterset of another model. A resource’s mode
may filter related rows inside a sub-query, and want the client to
choose those filters. The resource lists that filterset in
parameters(..), and its query reads it with
ctx.parameters::<RelationFilters>() to filter the rows of its
EXISTS.
A serializer that reads a filter. A serializer may list its
resource’s own filterset to read a filter’s value. In the sample, the
stations’ serializer reads the near filter (near=lng,lat,km) to
compute each station’s near_km:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/serializers.rs
#[derive(Debug, Clone, Serializer)]
#[serializer(model = Station, /* … */ parameters(StationFilters))]
pub struct StationOut { /* … */ }
async fn near_km(ctx: &Ctx, ids: Vec<i64>) -> Result<HashMap<i64, i64>, ApiError> {
let point: Vec<f64> = ctx
.parameters::<StationFilters>()
/* … */;
/* … */
}
}
The OpenAPI document lists near once, as a filter.
Behaviours and rind’s own
A behaviour declares what it reads, with
type Parameters. Flags reads flags on a list; Images reads
image on get_image. Their parameters are listed with the resource’s
own, and checked against them for duplicate names.
rind’s safe_delete reads
SafeDelete (?doit=really, on destroy).
An ordering expression is given the request,
ctx, so it can read typed parameters the same way. For example,
#[ordering(by(near = near_order(ctx)))] would sort by a distance, with
near_order a function of yours that reads a struct and gives an
Option of an ordering.
ctx.ordering() gives the ordering the request asks for, as it was sent
(["-name", "id"]). It is for code that sorts by more than the
resource’s names, such as the siblings of a tree.
Reference
#[parameters(..)]
| Key | Meaning |
|---|---|
read_by(A, B) | The resources and serializers that read the struct. Each must list it in parameters(..), or the code does not compile. |
on(list, retrieve, …) | The operations that read it before they start, and whose OpenAPI document lists it. Without it: every operation. update covers partial_update. |
#[parameter(..)]
| Key | Meaning |
|---|---|
name = "…" | The parameter’s name, when it is not the field’s. |
alias = "…" | One more name. Repeatable. |
default | When not sent: the type’s Default. Not with Option. |
default = expr | When not sent: this value. Not with Option. |
present | On a bool only, without default: true when the name is in the query string, whatever its value. |
description = "…" | The OpenAPI description, instead of the doc comment. |
Value types
| Type | Read as | Schema |
|---|---|---|
String | the text | string |
bool | true, false, 1, 0 (any case) | boolean |
i16…i64, u16…u64, usize | a number | integer |
f32, f64 | a number | number |
Vec<T> | comma-separated, empty items skipped | string, “Comma-separated.” |
an enum deriving ParamValue | a variant in snake case, or #[value(name = "…")] | string with enum |
Option<T> | None when not sent or empty | T’s |
Another type can be used by implementing rind::api::ParamType (a
parse function and a schema function).
Reading them
| Code | Gives |
|---|---|
ctx.parameters::<P>() | &P, read once per request; never fails. |
ctx.ordering() | The ordering asked for, as sent. |
rind::api::parameters::read_from::<P>(query) | P, or the 400 error: for tests. |
Authentication: who is asking
Every request that reaches a resource first answers one question: who is making it? This chapter explains how rind asks that question, and how your application answers it.
In Django REST framework, the answer comes from the authentication
classes (DEFAULT_AUTHENTICATION_CLASSES): SessionAuthentication,
TokenAuthentication, simplejwt’s JWTAuthentication. Each one reads the
request and sets request.user. rind works the same way, with two
differences:
- rind itself has no user model, no passwords, no sessions and no login route. It only defines the question and the shape of the answer. Your application gives the code that answers it.
- There is one authenticator per application, not a list. When you want
several schemes, one authenticator tries them in turn (the
rind-authcrate does exactly that).
Three chapters cover users, in this order:
- This chapter, Authentication: how a request becomes a user, or nobody.
- Signing in: how users get a token in the first
place. This is the
rind-authcrate: tokens, passwords, password reset, codes by mail. It plays the part ofdjango.contrib.authanddjangorestframework-simplejwt. - Permissions: what a user may do once rind knows who they are: which actions, on which rows, seeing which fields.
A first example
The sample application (the railway, in sample/) stores a token in a
column of each user. A client sends it in the Authorization header, and
the application finds the user who has it:
#![allow(unused)]
fn main() {
// sample/crates/accounts/accounts-ops/src/lib.rs
use accounts_models::{Group, USER_GROUPS, User};
use rind::api::{ApiError, Authenticate, BoxFuture, Identity};
use rind::prelude::*;
pub struct TokenAuth;
impl Authenticate for TokenAuth {
fn authenticate<'a>(
&'a self,
db: &'a Db,
authorization: Option<&'a str>,
) -> BoxFuture<'a, Result<Option<Identity>, ApiError>> {
Box::pin(async move {
let Some(token) = authorization.and_then(|h| h.strip_prefix("Bearer ")) else {
return Ok(None);
};
let user = db
.first(&Query::<User>::new().filter(User::token().eq(token.trim())))
.await?
.ok_or(ApiError::Unauthorized)?;
let groups = db
.load_m2m(Query::<Group>::new(), &USER_GROUPS, [user.id])
.await?
.remove(&user.id)
.unwrap_or_default();
Ok(Some(Identity {
id: user.id,
is_superuser: user.is_superuser,
is_staff: user.is_staff,
groups: groups.into_iter().map(|g| g.slug).collect(),
..Default::default()
}))
})
}
}
}
The application gives it to rind once, in
app():
#![allow(unused)]
fn main() {
// sample/src/lib.rs
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
// .models(…), .api(…)
.auth(accounts_ops::TokenAuth)
}
Now a request with Authorization: Bearer root-token is the sample’s
superuser, and a request without the header is anonymous:
GET /reservations
Authorization: Bearer root-token
{"nav": {…}, "results": [{"id": 1, …}, …]}
GET /reservations
{"detail": "Authentication credentials were not provided or are invalid."}
The second request gets a 401, because the rules of the reservations resource accept nobody anonymous (Permissions).
User and Group are ordinary models of the sample. rind asks nothing of
them: not their names, not their columns. The rest of this chapter
explains each part of the example.
This scheme is fine for a sample. A token that never expires, stored in clear in the database, is not what a real application wants. Use
rind-auth, or check a signed token as shown in Checking a signed token yourself.
The identity: what rind knows about a user
The answer to “who is asking?” is an Identity, or nobody (None):
#![allow(unused)]
fn main() {
// crates/rind-api/src/auth.rs
pub struct Identity {
pub id: i64,
pub is_superuser: bool,
pub is_staff: bool,
pub groups: Vec<String>, // the slugs of the user's groups
pub data: Option<Arc<dyn Any + Send + Sync>>,
}
}
It is much smaller than a Django User. It holds only what rind itself
reads, plus a slot for your own data:
idis the user’s key. Your own code reads it, for example to filter the reservations a user made (Reservation::made_by(user)). When the application has database replicas, rind also uses it to remember who just wrote, so that this user’s next read sees the write (Databases).is_staffandis_superuserare read by the rules#[rule(staff)]and#[rule(superuser)].groupsis read by the rule#[rule(group("…"))].datais never read by rind. It is for your application: see Carrying more than the flags.
These are rind’s words, not columns of a table. An application whose users
have no is_staff column decides what “staff” means for it when it
builds the identity, or it never uses that rule.
Identity implements Default, so you can write only the fields you set:
Identity { id: 1, is_staff: true, ..Default::default() }.
Coming from Django: there is no
request.userobject with a database row behind it. A resource that needs more than the identity loads the user itself, byid, or the authenticator attaches what is needed indata.
The three answers of an authenticator
An authenticator is a value that implements the Authenticate trait:
#![allow(unused)]
fn main() {
// crates/rind-api/src/auth.rs
pub trait Authenticate: Send + Sync + 'static {
fn authenticate<'a>(
&'a self,
db: &'a Db,
authorization: Option<&'a str>,
) -> BoxFuture<'a, Result<Option<Identity>, ApiError>>;
}
}
It receives the Authorization header of the request, exactly as the
client sent it (or None when there is none), and a database to look the
user up in. It gives one of three answers:
| Answer | Meaning | What happens to the request |
|---|---|---|
Ok(None) | no credentials, or a scheme this authenticator does not handle | it goes on as anonymous |
Ok(Some(identity)) | the credentials are this user’s | it goes on as that user |
Err(ApiError::Unauthorized) | there are credentials, but they are wrong | it is answered 401, even on a resource open to anyone |
This is the same contract as DRF’s authenticate(): return None to
pass, return a user, or raise AuthenticationFailed.
The last line is deliberate. A client that sends an expired token learns it at once, with a 401, instead of quietly reading the public data as nobody and wondering where its private data went.
Giving the authenticator to the application
The application gives its authenticator in app(), with .auth(..), as
in the first example. The authenticator is a value, built once when the
application starts. It can hold a key, a client of an identity provider,
or anything else that is costly to build.
Each request’s state, app.state(db), uses it. Code that builds an
AppState by hand gives the authenticator there instead:
#![allow(unused)]
fn main() {
let state = AppState::new(db, accounts_ops::TokenAuth);
}
The usual case: rind-auth
Most applications want their users to sign in with a name and a password,
and then send a signed token (a JWT) with each request. The
rind-auth crate does all of that: it mounts the login
routes, and it installs an authenticator that checks its own tokens. It
is added as a plugin, with .with(..):
#![allow(unused)]
fn main() {
// sample/src/lib.rs
.with(
rind_auth::Auth::<accounts_models::User>::from_env()
.unwrap_or_else(|_| rind_auth::Auth::new("railway-development-secret"))
.groups(accounts_models::auth_groups()),
)
}
The plugin wraps the authenticator the application already had. A bearer
token that looks like a JWT is checked by rind-auth; any other header
goes to the previous authenticator. This is how the sample keeps its
simple Bearer root-token working beside real JWTs. Because the plugin
wraps what is there when it is installed, put .with(rind_auth::Auth…)
after .auth(..), not before.
The rest of this chapter is for applications that write their own authenticator.
Writing your own authenticator
Checking a signed token yourself
Sometimes something else signs the users in and hands out the token: an
identity provider, or another service. Each request then proves who it is
with that token. The authenticator checks the signature, then reads the
user. This fragment uses the jsonwebtoken crate:
#![allow(unused)]
fn main() {
pub struct JwtAuth {
key: DecodingKey,
validation: Validation,
}
// in `authenticate`:
let Some(token) = authorization.and_then(|h| h.strip_prefix("Bearer ")) else {
return Ok(None);
};
let claims = decode::<Claims>(token.trim(), &self.key, &self.validation)
.map_err(|_| ApiError::Unauthorized)?
.claims;
let user = db
.first(&Query::<User>::new().filter(User::id().eq(claims.user_id) & User::is_active().eq(true)))
.await?
.ok_or(ApiError::Unauthorized)?;
// … then build the Identity from `user`, as in the first example.
}
Reading the user at each request is a choice. It costs one query, and in exchange a user who was disabled a minute ago is refused now. An application that trusts its tokens for their whole lifetime can put the flags and the groups in the claims, and read no table at all.
If the tokens come from a Django service using simplejwt,
rind-auth can check them for you: see
Checking only.
Keys for other services, without a table of users
You do not need a table to have users. A service that is called by two other services can know each caller by a key, given in its settings:
#![allow(unused)]
fn main() {
pub struct Keys(pub HashMap<String, Identity>);
// in `authenticate`:
let Some(key) = authorization.and_then(|h| h.strip_prefix("Bearer ")) else {
return Ok(None);
};
self.0.get(key.trim()).cloned().map(Some).ok_or(ApiError::Unauthorized)
}
An unknown key is wrong credentials, so it gets a 401.
An application that signs nobody in
An application without .auth(..) (and without a plugin such as
rind-auth) signs nobody in. Every request is anonymous, as with the
authenticator rind::api::NoAuth. This is how rind new starts a
project.
In such an application, only #[rule(anyone)] ever accepts a request.
A resource with #[rule(staff)] or #[rule(authenticated)] answers
401 to everybody. It is closed, not broken. rind add resource warns
you when it writes a rule for the staff in an application that signs
nobody in.
Carrying more than the flags
What a user may see often depends on more than a flag: the stations they
manage, the companies they belong to. Reading that again in every
resource would cost a query each time. Instead, the authenticator reads it
once and attaches it to the identity with with_data:
#![allow(unused)]
fn main() {
pub struct Managed {
pub stations: Vec<i64>,
}
// at the end of `authenticate`:
Ok(Some(identity.with_data(Managed { stations })))
}
Any code that has the identity reads it back by its type, with
data::<T>():
#![allow(unused)]
fn main() {
pub fn managed_by(user: &Identity) -> Query<Station> {
let stations = user.data::<Managed>().map(|m| m.stations.clone()).unwrap_or_default();
Query::new().filter(Station::id().in_(stations))
}
}
data::<T>() returns None when the identity carries nothing of type
T. Put the type where both sides can name it: in a shared crate of the
users’ domain (Organising an application).
With rind-auth, the same thing is done with
.identity(..).
Where your code reads the identity
There are three places.
In the rules, without writing any code. The rules read the flags and the groups:
#![allow(unused)]
fn main() {
#[rule(superuser)]
#[rule(staff)]
#[rule(group("drivers"), actions(list, retrieve))]
#[rule(authenticated, actions(list, retrieve))]
}
In a mode’s query, where the identity is called user:
#![allow(unused)]
fn main() {
#[mode(ReservationMode::Own, query = Reservation::made_by(user), hide(booked_by))]
}
There is no Option to unwrap here. When the request is anonymous, a
query that names user matches no row.
In a hook, an action or a computed field, as ctx.user, which is an
Option<Identity>:
#![allow(unused)]
fn main() {
let user = ctx.user.as_ref().ok_or(ApiError::Unauthorized)?;
}
What a client is answered
Authentication and permissions together decide the status code:
| The request… | on a resource whose rules… | is answered |
|---|---|---|
| has wrong credentials | (anything) | 401 |
| has no credentials | accept nobody anonymous for this action | 401 |
| is a user’s | accept nobody of this kind for this action | 403 |
| is a user’s | accept, but in a mode whose query does not contain the object | 404 |
The Permissions chapter explains the last two lines.
Signing in, signing out, and passwords
The rind-auth crate gives all of these. An application
that does not use it writes them as ordinary code; rind has nothing to add:
- A login route takes a name and a password, checks them, and answers
a token. It is not a resource. It is a plain route of the web framework,
merged with rind’s router (or added to the same actix
App), that calls an operation of the users’ domain (Routes that are not resources). - Passwords are hashed with a crate made for it (
argon2, for example). An application that takes over a Django database must read Django’s format (pbkdf2_sha256$…) with the same care;rind-authdoes. - Signing out is the client forgetting its token, or the application keeping a list of revoked tokens that its authenticator reads.
- “Who am I?” is a route that answers the user of the request. Outside
any resource, with an
AppState, the user isstate.ctx(authorization).await?.user.
In the tests
A test that calls the pipeline without HTTP builds its context with the user it wants:
#![allow(unused)]
fn main() {
let staff = Identity { id: 1, is_staff: true, ..Default::default() };
let ctx = Ctx::new(db.clone(), Some(staff));
}
A scope is tested as the plain function it is: Reservation::made_by(&user)
is a query, which you run on the test database. Through HTTP, the sample’s
tests send the tokens of its seed data (sample/tests/common/api_cases.rs).
Reference
Limits
These are stated plainly, so that nobody looks for them:
- Only the
Authorizationheader reaches the authenticator. Not the cookies, not another header, not the client’s address. A session in a cookie, or a key inX-Api-Key, needs a layer of the web framework in front of rind that rewrites it as anAuthorizationheader. - The authenticator runs at every request, and rind keeps nothing between two requests. An application that wants a cache of users puts it in its authenticator.
- An identity’s
idis ani64. Users known by a UUID need a number beside it. - OpenAPI always says
bearer. The OpenAPI document declares one security scheme, an HTTP bearer token, whatever your authenticator really reads. Operations open to anyone have no security requirement.
Types
| Name | Where | What it is |
|---|---|---|
Identity | rind::api | who is asking: id, is_staff, is_superuser, groups, data |
Identity::with_data(value) | attaches application data, read back with data::<T>() | |
Authenticate | rind::api | the trait an authenticator implements |
NoAuth | rind::api | an authenticator for which every request is anonymous |
Application::auth(value) | rind | gives the application’s authenticator |
AppState::new(db, auth) | rind::api | a state built by hand, with its authenticator |
AppState::ctx(authorization) | the context (and so the user) of an Authorization header | |
Ctx::new(db, user) | rind::api | a context for a test, a command or a job |
Signing in: rind-auth
The Authentication chapter explains how a request
becomes a user: an authenticator reads the Authorization header. This
chapter explains how users get a token to put in that header in the first
place. What they may then do is the subject of
Permissions.
rind-auth is a crate of its own, for an application that wants rind to
sign its users in. It gives:
- tokens (JWTs) for a name and a password, and their refresh;
- passwords, hashed and checked;
- password reset by mail, and account activation by mail;
- sign-in codes sent by mail, as an alternative to a password.
In Django, these come from django.contrib.auth (the password hashers,
PasswordResetTokenGenerator), and from djangorestframework-simplejwt
(the /token and /token/refresh views). rind-auth works on your own
user and group models, as Django does with AUTH_USER_MODEL. It also
reads and writes the same formats as Django: a database that Django signs
its users in to, rind signs them in to the same way. This lets an
application move from Django to rind one module at a time.
Adding rind-auth to a project
rind-auth is a separate crate. The rind crate does not re-export it,
and no feature of rind turns it on: you add it as a dependency yourself.
rind is not published on crates.io yet, so the dependency points to the
same rind checkout (or the same git repository) as your rind
dependency. rind new writes the rind line in the workspace’s
Cargo.toml; add rind-auth beside it:
# Cargo.toml of the workspace
[workspace.dependencies]
rind = { path = "/path/to/rind/crates/rind" }
rind-auth = { path = "/path/to/rind/crates/rind-auth" }
# or, from git:
# rind = { git = "https://…/rind" }
# rind-auth = { git = "https://…/rind" }
Both must come from the same place. Otherwise Cargo builds two different
rind crates, and the types of one do not fit the other.
Then two crates of your application use it:
# Cargo.toml of the users' models crate (for `user_base` and `AuthUser`)
# and of the application crate (for the plugin)
[dependencies]
rind-auth.workspace = true
rind-auth turns on the mail feature of rind by itself, since it
sends mails.
A first example
Three steps: a user model that rind-auth can read, the plugin in
app(), and a client asking for a token.
The user model adds the columns that signing in needs, and tells
rind-auth how to read a user:
#![allow(unused)]
fn main() {
// sample/crates/accounts/accounts-models/src/lib.rs (shortened)
use rind::prelude::*;
#[rind::with_fields(rind_auth::user_base)] // password, last_login, is_active
#[derive(Debug, Clone, Model)]
#[model(table = "accounts_user")]
pub struct User {
pub id: i64,
#[column(max_length = 150, unique)]
pub username: String,
#[column(default = "false")]
pub is_superuser: bool,
#[column(default = "false")]
pub is_staff: bool,
#[column(max_length = 254)]
pub email: Option<String>,
}
impl rind_auth::AuthUser for User {
fn id(&self) -> i64 { self.id }
fn username(&self) -> &str { &self.username }
fn password_hash(&self) -> &str { &self.password }
fn email(&self) -> Option<&str> { self.email.as_deref() }
fn last_login(&self) -> Option<chrono::DateTime<chrono::Utc>> { self.last_login }
fn is_active(&self) -> bool { self.is_active }
fn is_superuser(&self) -> bool { self.is_superuser }
fn is_staff(&self) -> bool { self.is_staff }
}
}
The application adds the plugin, and a mailer for the routes that send mails:
#![allow(unused)]
fn main() {
// app(), in the application crate
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
// .models(…), .api(…), .auth(…)
.with(rind::mail::Mailer::from_env()?) // the mails it sends
.with(
rind_auth::Auth::<accounts_models::User>::from_env()? // RIND_JWT_SECRET
.groups(rind_auth::SlugGroups::new(
"accounts_user_groups", "user_id", "group_id", "accounts_group", "slug",
)),
)
}
Auth::from_env() reads the secret that signs the tokens from
RIND_JWT_SECRET, and fails when it is not set. The sample uses
.unwrap_or_else(|_| rind_auth::Auth::new("railway-development-secret"))
so that it runs without any setting; do not do that in production.
A client now signs in with a name and a password:
POST /token
Content-Type: application/json
{"username": "alice", "password": "alice-password"}
{"refresh": "eyJ0eXAiOiJKV1Qi…", "access": "eyJ0eXAiOiJKV1Qi…"}
and sends the access token with each request:
GET /reservations
Authorization: Bearer eyJ0eXAiOiJKV1Qi…
A wrong name or password is answered 401:
{"detail": "No active account found with the given credentials"}
The plugin is also the application’s authenticator. A bearer token that
looks like a JWT is checked here: its signature, its expiry, its audience
and issuer when they are set, then that the user exists and is active, and
then the user’s groups are read. Any other header goes to the
authenticator the application had before. The sample keeps its simple
Bearer root-token beside the JWTs this way. Install the plugin after
.auth(..): it wraps the authenticator that is there when it is
installed.
The user model
rind-auth needs two things from your user model.
The columns. #[rind::with_fields(rind_auth::user_base)] adds the
three columns of Django’s AbstractBaseUser:
| Column | Type | Default |
|---|---|---|
password | String, at most 128 characters | '' (no usable password) |
last_login | Option<DateTime<Utc>> | NULL |
is_active | bool | true |
A model of an existing Django database already has these columns. You do
not need user_base there; implement the trait on the inspected model
(Inspecting a database).
The AuthUser trait, which says how to read a user. Its methods
id, username, password_hash and email are required. The others
(last_login, is_active, is_superuser, is_staff) have defaults
(none, active, not a superuser, not staff) for a model that lacks them.
The trait’s constants name the columns, for a model whose columns are not Django’s:
| Constant | Default | Used for |
|---|---|---|
LOGIN | &["username", "email"] | where a sign-in name is looked up, without case. A name is looked up in the first column; a name with an @ is looked up in all of them |
PASSWORD | "password" | the hash, written when a password is set |
LAST_LOGIN | Some("last_login") | written at each sign-in; None when there is no such column |
IS_ACTIVE | Some("is_active") | written by activation; None when there is no such column |
When two accounts have the same name except for case (Alice and
alice), neither can sign in by that name: rind-auth takes no guess.
Using the crate’s own user model
An application without users of its own can take the crate’s:
rind_auth::models::User and rind_auth::models::Group, on the tables
auth_user, auth_group and auth_user_groups. These are the columns of
Django’s auth_user, except that a group has a slug, which the rules
name. Give their migrations and their groups:
#![allow(unused)]
fn main() {
.models(rind_auth::models::migrations()) // the domain `auth`
// …
.with(
rind_auth::Auth::<rind_auth::models::User>::from_env()?
.groups(rind_auth::models::groups()),
)
}
Where the groups come from
A user’s groups, which #[rule(group("…"))] reads, come from a value that
implements AuthGroups. Without .groups(..), a user has no group.
SlugGroups reads them through a link table, by their slugs, as Django’s
user.groups does. Its arguments are the link table, its column for the
user, its column for the group, the table of groups, and the column the
rules name:
#![allow(unused)]
fn main() {
rind_auth::SlugGroups::new("accounts_user_groups", "user_id", "group_id", "accounts_group", "slug")
}
Groups that work differently (with validity dates, say, or computed from
another table) are an AuthGroups of your own: one async function that
gives the slugs of a user.
Adding to the identity
.identity(|db, user, identity| …) adds what your application knows of
the user to the identity of each request, with Identity::with_data
(Carrying more than the flags).
It receives the database, the user row, and the identity built so far, and
returns the identity to use:
#![allow(unused)]
fn main() {
.identity(|db, user, identity| Box::pin(async move {
let stations = …; // read with `db`, for `user`
Ok(identity.with_data(Managed { stations }))
}))
}
Creating the first user and setting a password
Django has manage.py createsuperuser. rind has no such command, and
rind-auth adds none: the only command it adds is auth-clean. A user
row whose password is empty cannot sign in, and cannot ask for a
password reset either: like Django, rind-auth sends no reset mail for an
account without a usable password.
There are three ways to give the first user a password.
From code, with rind_auth::set_password. It hashes the password in
Django’s format and writes it:
#![allow(unused)]
fn main() {
rind_auth::set_password::<User>(&db, user_id, "a-good-password", rind_auth::password::ITERATIONS).await?;
}
The last argument is the number of hashing iterations.
rind_auth::password::ITERATIONS is the default, 1,200,000. The function
does not check the minimum length.
The simplest way to use it is a command of your application, as Django’s management commands are (The application’s own commands):
// the application's main.rs
use accounts_models::User;
use rind::prelude::*;
fn main() -> std::process::ExitCode {
rind::cli::Cli::new(app::app())
.command("create-superuser", "creates a superuser: <username> <password>", create_superuser)
.main()
}
async fn create_superuser(_app: &rind::Application, args: &[String]) -> rind::cli::Result {
let [username, password] = args else {
return Err("usage: create-superuser <username> <password>".into());
};
let db = Db::connect(&std::env::var("DATABASE_URL")?)?;
let user = db
.insert(
&Insert::<User>::new()
.value(User::username(), username.as_str())
.value(User::is_staff(), true)
.value(User::is_superuser(), true),
)
.await?;
rind_auth::set_password::<User>(&db, user.id, password, rind_auth::password::ITERATIONS).await?;
println!("user {} created", user.id);
Ok(())
}
cargo run -p app -- create-superuser root 'a-good-password'
Columns not given take their database default: the user is active, and its other flags are off.
From Django. When rind works on a database that a Django application
also uses, manage.py createsuperuser or changepassword there writes a
hash that rind reads.
From the tests. The sample’s tests set the passwords of the seed
users with set_password (sample/tests/auth.rs).
The routes
The plugin mounts these routes. They are plain routes, not resources:
| Route | Body | Answer |
|---|---|---|
POST /token | username (or an email), password | {refresh, access}; 401 {"detail": "No active account found with the given credentials"} |
POST /token/refresh | refresh | {access}; 401 {"detail": "Token is invalid or expired", "code": "token_not_valid"} |
POST /auth/code | username | {success: true}, and a mail with a sign-in code |
POST /auth/code/token | username, code | {refresh, access}; 401 {"detail": "Invalid or expired code."} |
POST /auth/pwreset | username | {success: true}, and a mail with a reset token |
POST /auth/pwreset/process | username, token, password | {success: true}, or 400 {success: false} |
POST /auth/activate | username | {success: true}, and a mail with an activation token |
POST /auth/activate/process | username, token | {success: true}, or 400 {success: false} |
A few rules hold for all of them:
- A body is JSON, or a form (
application/x-www-form-urlencoded), as simplejwt accepts. - A missing field is answered 400, in DRF’s shape:
{"password": ["This field is required."]}. - The routes that send a mail answer the same whether the account exists or not. A client cannot use them to learn which names exist.
.prefix("/api/v3")puts every route below a path:/api/v3/token.- The password reset routes are on by default;
.reset(false)removes them. The activation routes are off by default;.reactivation(true)mounts them.
Tokens
The tokens are simplejwt’s, so that Django and rind accept each other’s tokens when they share the secret. A token is signed with HS256 and carries these claims:
token_type:accessorrefresh;user_id, the user’s id, written as text (as simplejwt writes it);exp,iatandjti;audandiss, when an audience and an issuer are set:.audience("my-app", "my-app"), orRIND_JWT_AUDIENCEandRIND_JWT_ISSUERwithfrom_env(). Once they are set, a token without them is refused;su: "superuser"for a superuser;- your own claims, added with
.claims(|user, claims| …), whereclaimsis a JSON map.
An access token lasts 5 minutes and a refresh token 15 days.
.lifetimes(access, refresh) changes both. A sign-in sets the user’s
last_login.
POST /token/refresh gives a new access token for a refresh token, with
the same extra claims, as long as the user still exists and is active. It
does not give a new refresh token: the client signs in again when the
refresh token expires.
Coming from Django: simplejwt’s default refresh lifetime is one day; rind-auth’s is 15 days. There is no token blacklist: a token stays valid until it expires, and signing out is the client forgetting its tokens.
Checking only: tokens another service issues
While an application moves to rind module by module, its clients may
keep signing in to the old service (Django) and send the same token to
both. .verify_only() turns the plugin into a token checker only:
#![allow(unused)]
fn main() {
.with(
Auth::<User>::new(&secret)
.audience("my-app", "my-app")
.verify_only()
.groups(MyGroups),
)
}
No route is mounted (/token answers 404), no table is added (no
rind_auth_code), and no command. Each request is checked as usual: the
user is read, an inactive one is refused, and the groups and
.identity(..) are filled in. A refresh token is not accepted as an
access token.
Passwords
Passwords are stored in Django’s format, which rind reads and writes:
pbkdf2_sha256$<iterations>$<salt>$<hash>
A new password is hashed with 1,200,000 iterations, Django 6’s count;
.iterations(n) changes it. A password hashed with fewer iterations is
hashed again at its next sign-in, as Django does. A hash of another
algorithm (argon2$…), an empty one, or one that starts with ! (Django’s
“unusable password”) never matches.
Two protections are built in:
- A sign-in with an unknown name takes as long as one with a wrong password, so the time of the answer does not tell which names exist.
- A new password set through the reset route has at least 8 characters;
.min_password_length(n)changes it. A shorter one is answered 400:{"password": ["This password is too short: 8 characters at least."]}.
Password reset and activation by mail
POST /auth/pwreset mails a reset token to the user, when the account
has a usable password and an email. POST /auth/pwreset/process takes the
name, the token and the new password, and sets it. With
.reactivation(true), a successful reset also makes the account active
again.
POST /auth/activate mails a token in the same way, and
POST /auth/activate/process makes the account active.
The tokens are those of Django’s PasswordResetTokenGenerator, keyed by
Django’s SECRET_KEY: a link sent by Django works in rind, and the other
way round. The key is RIND_AUTH_SECRET_KEY (or .django_secret(key));
when it is not set, it is the JWT secret. A token stops working once the
password changes or the user signs in, and after 3 days.
Django reads its clock in local time for these tokens, so rind reads the process’s local time too. Run both in the same time zone.
Sign-in codes
A sign-in code lets a user sign in without a password: POST /auth/code
mails a code, and POST /auth/code/token exchanges it for tokens.
A code has 6 digits and is valid 10 minutes; .codes(digits, valid)
changes both (from 4 to 12 digits). A code is used once, and it is refused
after 5 wrong attempts. It is kept hashed in the plugin’s table
rind_auth_code, and asking again replaces it. Codes are only sent to an
active account with an email.
The table belongs to the domain rind_auth, which the plugin adds to the
application’s migrations by itself. The command auth-clean deletes the
expired codes:
cargo run -p app -- auth-clean
Mails
The plugin renders the templates auth_code, auth_pwreset and
auth_activate, with defaults of its own. A template of the mailer with
one of those names replaces the default (Mail). The context of
each template has:
user, withid,usernameandemail;codeandminutesfor a sign-in code, ortokenfor a reset or an activation.
An application without a rind::mail::Mailer answers these routes 500.
Limits on attempts
Signing in is limited to 5 attempts a minute per account and per client
address; the next attempt is answered 429
{"detail": "Too many attempts: wait a minute."}. .attempts(n, window)
changes the limit. The routes that send a mail, and the ones that use a
reset or activation token, are limited per account in the same way.
The client address is the peer’s. When the peer is one of the proxies
given with .trusted_proxies(..), it is the first address of its
X-Forwarded-For header instead.
The attempts are counted in the process, in memory. Several processes each count their own, and a restart forgets them.
Going further: a master password, sign-in by address
Some applications need two unusual ways to sign in. Both are off unless the application turns them on:
.master_password(hash)sets a password that opens any active account, except a superuser’s (add.master_password_for_superusers()for those). It is given as its hash in Django’s format, never in clear, or throughRIND_AUTH_MASTER_PASSWORD_HASHwithfrom_env(). Its tokens carrymaster: true, and each sign-in with it is logged at warning level..sign_in_by_ip("203.0.113.0/24", "kiosk")?makes a request from that network, signing in with the name and passwordloginbyip, the userkiosk..ip_credentials(name, password)changes the special name and password. The address is read as the limits read it. A private address is refused outside a development build, since it is a proxy’s as often as a client’s. Its tokens carryby_ip: true. The method returns aResult, because the network may not parse.
Unless the application also calls .allow_in_production(), a warning is
logged at start-up when either one is on.
Reference
What is not there
- No
createsuperusercommand and no command to set a password: see Creating the first user. - No “who am I” route, no route for a signed-in user to change their password, and no sign-out route or token blacklist.
- The routes are not in the OpenAPI document.
- Sign-in codes cannot be turned off.
The builder
| Method | Default | What it does |
|---|---|---|
Auth::new(secret) | tokens signed with secret | |
Auth::from_env() | reads the variables below; fails without RIND_JWT_SECRET | |
.groups(groups) | no groups | where a user’s groups come from: an AuthGroups (SlugGroups, models::groups()) |
.identity(f) | adds to each request’s identity | |
.claims(f) | adds claims to each token | |
.audience(audience, issuer) | none | the audience and issuer tokens carry and must carry |
.django_secret(key) | the JWT secret | Django’s SECRET_KEY, for reset and activation tokens |
.lifetimes(access, refresh) | 5 minutes, 15 days | how long tokens are valid |
.prefix(path) | none | the routes below this path |
.iterations(n) | 1,200,000 | the hashing iterations of a new password |
.min_password_length(n) | 8 | the shortest new password |
.reset(on) | on | the password reset routes |
.reactivation(on) | off | the activation routes, and reactivation by a reset |
.codes(digits, valid) | 6, 10 minutes | sign-in codes |
.attempts(n, window) | 5 a minute | the limit on attempts |
.trusted_proxies(list) | none | proxies whose X-Forwarded-For is believed |
.master_password(hash) | off | a password that opens any account |
.master_password_for_superusers() | off | …superusers’ accounts too |
.sign_in_by_ip(network, username) | off | sign-in by address; returns a Result |
.ip_credentials(name, password) | loginbyip, loginbyip | the special name and password of sign-in by address |
.allow_in_production() | no warning for the two above | |
.verify_only() | only checks tokens: no route, table or command |
Environment variables of from_env()
| Variable | Meaning |
|---|---|
RIND_JWT_SECRET | the secret that signs the tokens (required) |
RIND_AUTH_SECRET_KEY | Django’s SECRET_KEY, for reset and activation tokens |
RIND_JWT_AUDIENCE, RIND_JWT_ISSUER | the audience and issuer |
RIND_AUTH_MASTER_PASSWORD_HASH | the master password’s hash |
Functions and modules
| Name | What it is |
|---|---|
rind_auth::set_password::<U>(db, id, password, iterations) | sets a user’s password |
rind_auth::password | hash, verify, usable, and ITERATIONS |
rind_auth::tokens::Jwt | signs and checks tokens, for tests and tools |
rind_auth::models | the crate’s own User and Group, their migrations() and groups() |
rind_auth::migrations() | the domain rind_auth (the codes’ table), which the plugin adds itself |
Permissions: rules and modes
Once rind knows who is asking (Authentication), and users can get a token (Signing in), each resource decides what that user may do. rind keeps two questions apart:
- Who may do what? This is answered by the rules. A rule gives an action to a kind of user, such as “the staff may do everything” or “anyone may list”. When no rule gives the action, it is refused.
- On which rows, and seeing which fields? This is answered by the modes. A mode is a query (the rows the user can reach) and a list of fields it hides.
In Django REST framework, the first question is the viewset’s
permission_classes (IsAdminUser, IsAuthenticatedOrReadOnly…) and
get_permissions() when they change per action. The second is
get_queryset(), which filters the rows by request.user, and
has_object_permission(). In rind, both are attributes on the resource,
next to each other, and a third tool controls single fields wherever they
appear: readable(..) on a serializer field.
A first example
Everyone may read the timetable of the railway, and only the staff changes it:
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/views.rs
#[derive(Resource)]
#[resource(model = Journey, path = "journeys", /* … */ actions)]
#[rule(superuser)]
#[rule(staff)]
#[rule(anyone, actions(list, retrieve, rooms))]
pub struct JourneyResource;
}
An anonymous client can list the journeys:
GET /journeys
{"nav": {…}, "results": [{"id": 1, "code": "…", …}, …]}
but cannot create one. Without credentials, the answer is 401:
POST /journeys
{"detail": "Authentication credentials were not provided or are invalid."}
A signed-in user who is not staff gets a 403 instead:
POST /journeys
Authorization: Bearer alice-token
{"detail": "You do not have permission to perform this action."}
Rules
A rule says who it is for, and, optionally, which actions it allows.
Without actions(..), it allows all of them. A resource has at least one
rule; a resource without any is a compile error, since nobody could call
it.
The rules are read in order, and the first rule that accepts the
request decides. The others are not read. In the example, a superuser
is accepted by the first rule for every action; an anonymous request
passes over the first two rules, and the third one accepts it for list,
retrieve and rooms only.
A rule names one kind of user:
| Who | Accepts |
|---|---|
anyone | every request, signed in or not |
authenticated | any signed-in user |
staff | a user whose identity has is_staff |
superuser | a user whose identity has is_superuser |
group("…") | a signed-in user in that group (by its slug) |
staff does not include the superusers, just as DRF’s IsAdminUser only
reads is_staff. This is why the sample always writes #[rule(superuser)]
first.
group(..) takes one or more slugs, and a member of any of them is
accepted: group("drivers", "controllers"). A slug may hold *, which
stands for one or more lowercase letters or digits. A pattern with a *
only has to match the start of the slug: group("depot_*") accepts
depot_12 and depot_12_night, but not depot_ or my_depot_1.
The actions a rule names
The actions are the operations of a resource, list, retrieve,
create, update, partial_update and destroy, and the resource’s
own actions, by their name.
A name that the resource has no action of is a compile error, shown at the name:
error[E0080]: evaluation panicked: a rule of `ProducerResource` names `remove_logo`:
the resource has no such action (its operations, its `#[actions]`, its behaviours' actions)
The names rind knows are the resource’s operations, its #[actions]
(when #[resource(actions)] plugs them in), and the actions of its
behaviours (their ACTIONS: Flags gives add_flag, remove_flag and
get_flags; Images gives add_image…).
Coming from Django: in Django, a misspelt action name in a permission check matches nothing, silently. In a real Django application, a rule named
remove_logofor an action calledunset_logo, and nobody noticed. rind refuses to compile it.
What no rule allows does not exist
When no rule accepts the request, it is refused: with a 401 when the request has no credentials, and with a 403 when it is a user’s.
So an action that no rule names is closed to everybody. In the sample,
nobody but a superuser changes a reservation, because no other rule names
update:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
#[rule(superuser, mode = ReservationMode::Full)]
#[rule(staff, actions(list, retrieve, create, destroy, cancel), mode = ReservationMode::Full)]
#[rule(authenticated, actions(list, retrieve, create, cancel), mode = ReservationMode::Own)]
}
DRF’s IsAuthenticatedOrReadOnly is written as two rules:
#![allow(unused)]
fn main() {
#[rule(authenticated)]
#[rule(anyone, actions(list, retrieve))]
}
Modes: the rows and fields a user gets
The rules above also give a mode. A mode answers the second question:
on which rows does this request work, and which fields does it see? It is
rind’s get_queryset().
The modes of a resource are an enum of your own. The resource names it
with mode = …, and gives each value a query and, optionally, the fields
it hides:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReservationMode {
/// The staff: every reservation, every field.
Full,
/// A signed-in user: the reservations they made.
Own,
}
#[derive(Resource)]
#[resource(model = Reservation, path = "reservations", /* … */ mode = ReservationMode)]
#[rule(superuser, mode = ReservationMode::Full)]
#[rule(staff, actions(list, retrieve, create, destroy, cancel), mode = ReservationMode::Full)]
#[rule(authenticated, actions(list, retrieve, create, cancel), mode = ReservationMode::Own)]
#[mode(ReservationMode::Full, query = Query::new())]
#[mode(ReservationMode::Own, query = Reservation::made_by(user), hide(booked_by))]
pub struct ReservationResource;
}
The staff gets Full: every row (Query::new()) and every field. A
signed-in user gets Own: only the reservations they made, without the
booked_by field.
Two rules hold once a resource has modes, and the compiler checks both:
every rule gives a mode (mode = …), and every value of the enum has its
#[mode(..)] with a query = ….
In the query, user is the request’s Identity, and ctx is the
request’s context. You do not unwrap an Option: when the request is
anonymous, a query that names user matches no row.
An object outside the mode does not exist
Everything the resource does for the request happens inside the mode’s
query: the list, the count, the filters, and each object. An object
outside the query does not exist for that user. GET, PATCH,
DELETE and the actions on it answer 404, not 403, so that the user
learns nothing about what they cannot see. Reservation 1 of the sample was made by
Alice, so Bob gets:
GET /reservations/1
Authorization: Bearer bob-token
{"detail": "Not found."}
The same holds after a write. A request may not create or change an object into something it could not see: the object is read again through the mode’s query, inside the write’s transaction. When it is not there, the write is refused with a 403 and rolled back.
Coming from Django: there is no
has_object_permission(). What a user may touch is the query of their mode. A check that depends on the object’s values goes into that query, or into a hook of the write.
Hiding fields
A field in hide(..) is neither read from the database nor sent. If the
client asks for it with ?fields=, it is simply absent. hide(..) also
takes paths, for a field inside a nested one:
hide(client_details.siret).
A query that depends on the action
A mode’s query is used by every action: the list, the retrieve, the
object that a write or a detail action changes, and the object read again
after a write. Sometimes you want a different query for some of them.
ctx.action() says which action runs: Some("list"), "retrieve",
"create", "update", "partial_update", "destroy", or the name of
an #[action]. It is None outside a resource’s action (a job, a test’s
context, a plugin’s route).
The sample’s users do not see their cancelled reservations in their list, but a link to one still answers:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
#[mode(ReservationMode::Own, query = own(ctx, user), hide(booked_by))]
fn own(ctx: &Ctx, user: &Identity) -> Query<Reservation> {
let made = Reservation::made_by(user);
match ctx.action() {
Some("list") => made.filter(Reservation::status().ne(reservation_status::CANCELLED)),
_ => made,
}
}
}
Think of each arm as the rows its actions may touch. Here cancel falls
in _, because it must find a cancelled reservation, to answer that it is
already cancelled.
Be careful when you widen a query. Rows that are only for reading go to
"retrieve" by name, never to _, so that no write reaches them. Since a
write reads its object through the same query, a query that widens for
retrieve only does not widen what can be changed.
In Django, this is the viewset’s get_queryset() reading self.action.
Scopes: queries on the model
The queries of the modes are best written as the model’s own scopes: plain functions that return a query, and that are easy to test without HTTP:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-models/src/lib.rs
impl Reservation {
/// The reservations a user made.
pub fn made_by(user: &Identity) -> Query<Reservation> {
Query::new().filter(Reservation::booked_by_id().eq(user.id))
}
}
}
They take the place of Django’s custom managers, such as
Reservation.objects.readable(request). A scope can be as rich as the
query layer: through relations, through groups, through a
table of permissions per object. With data the authenticator attached to
the identity, it needs no query of its own to know what the user manages
(Carrying more than the flags).
A resource without modes
A resource that shows the same rows to everyone it accepts does not need
modes. It may still give one base query, #[resource(query = …)], which
works like a single mode’s query: if it names user, an anonymous request
sees no row (Resources).
Who may read a field
A mode hides fields from one resource. Sometimes a field is not for every
user, whichever resource sends it. The field then says so on the
serializer, with readable(..):
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-api/src/trains/serializers.rs
/// Its train: staff only.
#[field(name = "train", readable(staff))]
pub train_id: Option<i64>,
}
readable(..) takes one or more of staff, superuser,
authenticated, group = "pattern" (which may be given several times),
and with = function for a rule of your own, a
fn(Option<&Identity>) -> bool. Any one of them is enough to read the
field.
The rule holds wherever the serializer goes out: in its own resource, and
in every nested field that shows it. Here, WagonOut is the serializer
of the wagons inside a train (wagons_details), and a user who is not
staff does not get their train.
A field the user may not read is absent, not an error. One request
can serve every user, and each gets what they may read. The field is
neither read nor sent, and the fields it implies(..) are not selected
through it.
Coming from Django: DRF has no built-in field-level permission; one usually overrides
to_representation()orget_fields(). Here it is one attribute.
Reference
#[rule(..)]
| Part | Meaning |
|---|---|
anyone, authenticated, staff, superuser | who the rule accepts (exactly one per rule) |
group("slug", …) | a member of any of these groups; * matches one or more of [a-z0-9], and a pattern with * matches the start of the slug |
actions(name, …) | the actions it allows; all of them when absent. Each name is checked at compile time |
mode = Mode::Value | the mode it gives; required once the resource has mode = … |
The rules are read in order, and the first that accepts decides. The
OpenAPI document lists, for each operation, who may run it
(x-allowed).
#[mode(..)]
| Part | Meaning |
|---|---|
Mode::Value (first) | the value of the mode enum this attribute describes |
query = … | the rows of the mode (required). user and ctx are in scope |
hide(field, nested.field, …) | fields neither read nor sent |
readable(..) on a serializer field
| Part | Accepts |
|---|---|
staff, superuser, authenticated | as in the rules |
group = "pattern" | a member of a group matching it; may be repeated |
with = function | a fn(Option<&Identity>) -> bool of the application |
What a client is answered
| The request… | is answered |
|---|---|
| has no credentials, and no rule accepts it | 401 |
| is a user’s, and no rule accepts it | 403 |
| is accepted, but the object is outside the mode’s query | 404 |
| writes an object that ends up outside the mode’s query | 403, and the write is rolled back |
What is not there
- No per-model permissions as in Django’s
auth_permissiontable (booking.add_reservation, DRF’sDjangoModelPermissions): use groups and rules. - No
has_object_permission(): use the mode’s query or a hook.
Actions
A resource answers six standard operations: list, retrieve,
create, update, partial_update and destroy. Real APIs need more:
“cancel this reservation”, “delay this journey”, “how many stations are
there?”. These are actions: routes of your own, mounted on the
resource.
In Django REST framework, they are the methods of a ViewSet decorated
with @action. An action with detail=True works on one object
(/journeys/{id}/delay); one with detail=False works on the list
(/stations/count). rind has the same two kinds, and says which one an
action is from its arguments.
A first example
The sample’s journeys have two actions: rooms, which reads, and
delay, which writes.
#![allow(unused)]
fn main() {
// sample/crates/timetable/timetable-api/src/journeys/views.rs
use rind::api::{ApiError, Ctx, QueryParams, resource};
use rind::{Resource, actions};
/// The body of `delay`.
#[derive(Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Delay {
pub minutes: i64,
}
#[derive(Resource)]
#[resource(model = Journey, path = "journeys", /* … */ actions)]
#[rule(superuser)]
#[rule(staff)]
#[rule(anyone, actions(list, retrieve, rooms))]
pub struct JourneyResource;
#[actions]
impl JourneyResource {
/// What each wagon of the journey has left.
#[action(GET)]
pub async fn rooms(
ctx: &Ctx,
journey: Journey,
#[query] kind: Option<String>,
#[query(default = false)] free_only: bool,
) -> Result<Vec<Room>, ApiError> {
let rooms = booking_ops::rooms(&ctx.db, &journey).await?;
Ok(rooms
.into_iter()
.filter(|room| kind.as_ref().is_none_or(|kind| *kind == room.kind))
.filter(|room| !free_only || room.free > 0)
.collect())
}
/// Moves a journey that has not left by a number of minutes.
#[action(POST)]
pub async fn delay(
ctx: &Ctx,
journey: Journey,
#[body] delay: Delay,
) -> Result<JourneyOut, ApiError> {
…
resource::serialize_one::<JourneyResource>(ctx, (), moved, &QueryParams::default()).await
}
}
}
Three things make this work:
actionsin#[resource(..)]tells the resource that it has actions.#[actions]on animplblock of the resource struct collects the functions marked#[action(..)].- Each action is an
async fnwith the HTTP method in its attribute. Its name is the function’s name, and it is also the last part of its URL.
Both actions take a journey: Journey, so they work on one object:
GET /journeys/1/rooms?kind=sleeper
[{"wagon": 3, "position": 3, "kind": "sleeper", "capacity": 2, "taken": 1, "free": 1}]
POST /journeys/1/delay
{"minutes": 15}
The answer of delay is the journey as it is afterwards, exactly as
GET /journeys/1 would send it.
Choosing the method
An action is GET, POST or PATCH.
Use GET for an action that changes nothing. Such an action may be
answered by a replica of the database, and it may be
kept by the cache. Use POST or PATCH for an
action that writes.
What an action receives
An action asks for what it needs through its arguments. rind recognises most of them by their name, and two by an attribute:
| Argument | What it is |
|---|---|
ctx: &Ctx | The request’s context: the database, the user, the typed parameters. |
mode: ReservationMode | The user’s mode, for a resource that has modes. |
params: &QueryParams | The whole query string, to hand to list_query or serialize_one. |
#[query] name: T | One parameter of the query string, read as T. Required. |
#[query] name: Option<T> | The same, optional. |
#[query(default = …)] name: T | The same, optional, with a default. |
#[body] name: T | The JSON body, read as any Deserialize type. Option<T> when the body may be absent. |
any other argument (journey: Journey) | The object. Its presence makes the action a detail action. |
The object
When an action has an argument that is none of the above, rind takes it
as the object: the action is then mounted under an id,
/journeys/{id}/rooms. The object is read in the user’s mode, through
the same query as a retrieve. A user who cannot see the journey gets a
404, and the action does not run.
An action without such an argument is a list action, mounted on the
resource itself: /stations/count. An action has at most one object.
Query parameters
A #[query] argument is read from the query string under its own name
(a leading _ is dropped). #[query(name = "…")] reads another name.
A missing required parameter, or a value that is not of its type, is a 400 before the action runs. Every wrong parameter is reported in the same answer:
GET /journeys/1/rooms?free_only=perhaps
{"free_only": ["Invalid value."]}
An action can also read typed parameters: a struct
whose on(..) names the action is read before the action runs, like
for a standard operation.
The body
A #[body] argument is the JSON body, read into its type with serde. A
body that does not fit the type is a 400 (Invalid body: …). With
#[serde(deny_unknown_fields)], as on Delay, an unknown key is
refused too.
The #[query] and #[body] arguments are part of the
OpenAPI document.
What it answers
An action returns Result<T, ApiError>, where T is anything that
serializes to JSON: a number, a Vec, a struct of yours, an output.
To answer an object as a read of the resource would, in the user’s
mode, use serialize_one:
#![allow(unused)]
fn main() {
resource::serialize_one::<JourneyResource>(ctx, (), moved, &QueryParams::default()).await
}
Its arguments are the context, the mode (() for a resource without
modes), the model’s row, and the query string that chooses the fields.
QueryParams::default() gives the default fields; passing the action’s
params lets the client choose them with ?fields=….
The status
An action answers 200. An action that creates something says so with
status:
#![allow(unused)]
fn main() {
#[action(POST, status = 201)]
}
The status must be a 2xx, and not 204, since an action always answers a
body. The Images behaviour’s add_image and the Logo
behaviour’s set_logo answer 201, as a real Django application’s did.
Who may run it
An action is allowed like any other operation: by its name in the
rules. In the example above, rooms is open to
everyone, because the anyone rule names it. delay is named by no
rule that lists actions, so only the users whose rule allows everything
(here, the superusers and the staff) may run it.
A rule that names an action that does not exist does not compile.
An action over the list
Some actions answer about the rows the list would show: a map of them,
their counts, a summary. Such an action should follow the same filters,
search and ordering as the list, so that ?status=closed means the
same thing on both.
rind::api::resource::list_query::<R>(ctx, mode, params) gives that
query. It is the mode’s query, with the filters, the behaviours’
filters, the search, and the ordering the request asks for, but without
the page. A filter that cannot be read is a 400, as on the list.
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[action(GET, cached)]
pub async fn geojson(ctx: &Ctx, params: &QueryParams) -> Result<FeatureCollection, ApiError> {
let query = rind::api::resource::list_query::<StationResource>(ctx, (), params)?;
let select = query
.select((Station::id(), Station::name(), Station::status(), Station::position()))
.into_select();
let rows: Vec<(i64, String, String, Option<Point>)> = ctx.db.rows(&select).await?;
Ok(FeatureCollection::new(
rows.into_iter()
.map(|(id, name, status, position)| {
Feature::new(id, position).with("name", name).with("status", status)
})
.collect(),
))
}
}
GET /stations/geojson?status=closed
This maps the closed stations: every one of them, in the list’s order.
Kept by the cache
By default, the cache does not keep the answers of an
action, and ETags does not tag them. A GET action whose answer can
be kept says so with cached:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
/// How many stations there are.
#[action(GET, cached)]
pub async fn count(ctx: &Ctx) -> Result<i64, ApiError> {
Ok(ctx.db.count(&Query::<Station>::new()).await?)
}
}
A cached action is kept as a list is kept: per user (or per rule),
made stale by any write to the resource’s tables, and answered with a
304 to a client that already has it.
Say cached only of an action that reads nothing but the database,
and only through those tables. The sample’s clock action, which sends
the server’s time, is not cached: the cache cannot see the clock
change. cached on a POST or a PATCH does not compile. The Flags
behaviour’s get_flags is cached.
A list action and an object action with the same name
A list action and an object action may share a name. In the sample,
/stations/count counts every station, and /stations/{id}/count
counts the stations of that station’s city. They are two functions;
the second one takes its URL name from name:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[action(GET, cached)]
pub async fn count(ctx: &Ctx) -> Result<i64, ApiError> { … }
/// How many stations its city has, itself included.
#[action(GET, cached, name = "count")]
pub async fn city_count(ctx: &Ctx, station: Station) -> Result<i64, ApiError> { … }
}
Whether the URL has an id says which function runs. A rule that names
count allows both, and both read the typed parameters declared
on(count). In the OpenAPI document, the list action’s operation id is
stations_count, and the object action’s is stations_count_object.
A real Django application had such a pair: POST /producers/action
(create a producer, look up a company number) and
POST /producers/{id}/action.
Where the work goes
An action is HTTP: it reads a request and writes an answer. The work it
does belongs to the domain, in an ops crate, as a function that knows
nothing about HTTP. That function can then be called from anywhere (a
job, a command, a test) and tested alone:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-ops/src/lib.rs
pub async fn cancel(db: &Db, reservation: i64) -> Result<Reservation, Refused> { … }
// sample/crates/booking/booking-api/src/reservations/views.rs
#[action(POST)]
pub async fn cancel(
ctx: &Ctx,
mode: ReservationMode,
reservation: Reservation,
) -> Result<ReservationOut, ApiError> {
let cancelled = booking_ops::cancel(&ctx.db, reservation.id)
.await
.map_err(refused)?;
let params = QueryParams::default();
resource::serialize_one::<ReservationResource>(ctx, mode, cancelled, ¶ms).await
}
}
refused is the API crate’s function that turns the domain’s refusal
into an ApiError. See Organising an application.
Coming from Django: a DRF
@actionoften holds the business logic itself. rind does not stop you, but the sample keeps actions thin, the way a Django project would move logic into aservices.py.
Reference
#[action(..)]
| Key | Meaning |
|---|---|
GET, POST or PATCH | The HTTP method. Required. |
name = "…" | The action’s name (its URL, its rules), when it is not the function’s. |
cached | On a GET only: the cache keeps its answers and ETags tags them. |
status = N | The status of its answer: a 2xx other than 204. 200 by default. |
Arguments
| Argument | Meaning |
|---|---|
ctx | &Ctx, the request. |
mode | The resource’s mode. |
params | &QueryParams, the query string. |
body (without #[body]) | The raw JSON body, serde_json::Value; Null without a body. |
#[query], #[query(name = "…")], #[query(default = …)] | One query parameter, typed. Not Option with default. |
#[body] | The JSON body, typed. |
| one other argument | The object: a detail action, /<path>/{id}/<name>. |
A name with a leading _ (_ctx) means the same as without it. An
action has no self, and is always an async fn.
Routes
| Action | Route | Operation id |
|---|---|---|
| with an object | /<path>/{id}/<name> | <path>_<name>, or <path>_<name>_object when a list action has the same name |
| without | /<path>/<name> | <path>_<name> |
OpenAPI
An OpenAPI document describes an API: its routes, their parameters, the JSON they take and send, and who may call them. Clients, code generators and tools such as Swagger UI read it.
In a Django project, the document usually comes from drf-spectacular,
which reads the views and serializers and guesses what it cannot read.
The guesses are often wrong, and the project corrects them with
@extend_schema. In rind, the document is written by the same derives
that serve the API. It cannot say something else than what the API does,
and there is nothing to guess.
Getting the document
The document belongs to the application, the value returned by
app(). Every resource that an
api crate’s api() mounts is in it:
#![allow(unused)]
fn main() {
let document: serde_json::Value = sample::app().openapi();
}
The command line writes it to a file:
rind openapi --out openapi.json # or: cargo run -p sample -- openapi
rind does not serve the document on a route by itself. To serve it, add
one route of your own that answers app().openapi(), as described in
Routes that are not resources.
The sample freezes its document in a snapshot test
(sample/tests/openapi.rs). A change of the API then shows up as a
change of the snapshot, which someone reviews.
What the document says
Each part of a resource adds its part of the document:
| From | The document gets |
|---|---|
| the resource | its routes, as they are served: no POST without an input, no DELETE unless the resource has delete, one route per action |
| its rules | who may call each operation (x-allowed), and whether it needs credentials (security) |
| the serializer | the schema of the output, each field with its type; nested outputs by reference |
| the input | the schema of the body: required fields, maxLength, minimum, maximum, enum, nullable |
| the filterset | one parameter per filter, and one per alias |
| search, ordering, pages | search, ordering with the names it accepts, page, page_size, fields, omit, include |
an action’s #[query] arguments | the parameters of the action’s route |
| typed parameters | the resource’s, its behaviours’ and its serializers’, on the operations their on(..) names |
| the export formats | format and export on every read, and the formats’ media types |
An operation that no rule allows is left out of the document, since nobody can call it.
Each field of an output has a type that describes itself, through the
JsonSchema trait. rind implements it for the usual types, and the
Serializer derive implements it for every output. A type of your own
used in an output must implement it too: one function that returns its
schema. Without it, the code does not compile, so the document is never
silently vague about a field.
Routes that are not resources (a webhook, a health check) are not in
the document by themselves. .describe(..) adds them: see
Routes that are not resources.
Descriptions come from the doc comments
You do not write descriptions twice. Every doc comment (///) goes
where the document has a place for it:
| A doc comment on | Describes |
|---|---|
| a resource struct | its tag (in tags, at the top of the document) |
| an output struct | its schema |
| an output’s field | its property (before the “Always sent.” that the field selection adds) |
| an input’s field | the body’s property |
| a filter’s field | its query parameter, and its aliases |
| a typed parameter’s field | its query parameter |
an #[action] function | its operation: the first line is the summary, the whole comment the description |
| a model’s field | an output or input field of that column that has no comment of its own |
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/filters.rs
/// Stations offering every one of these services.
#[filter(path = Station::services(), lookup = contains)]
pub services: Option<Vec<String>>,
}
This filter’s parameter in the document says “Stations offering every one of these services.”, followed by “Comma-separated.” because its type is a list.
A field is best documented once, on the model. Every serializer and every input of that field then says the same. A comment on the serializer’s or the input’s field replaces the model’s.
The lines are kept as they are written, because descriptions in OpenAPI
are CommonMark. Rustdoc’s links become their text ([`Writes`]
becomes `Writes`), since a client does not have the crate. A link
to a web address is kept.
Sometimes a doc comment is written for the readers of the code, not for
the users of the API. Then #[field(description = "…")],
#[input(description = "…")], #[filter(description = "…")] and
#[parameter(description = "…")] replace it, and description = ""
gives no description at all.
The actions that rind’s behaviours add (add_flag,
add_image…) carry their own descriptions.
When you start from an existing database, rind inspect
writes each column’s database comment (COMMENT ON COLUMN, Django’s
db_comment) as the model field’s doc comment, so it reaches the
document too.
What is not described yet
- The body and the answer of an action: the document says that an action takes a JSON body, and answers JSON, without their schema.
- The fields that a mode hides.
Reference
Where to get it
| Code or command | Gives |
|---|---|
app().openapi() | The whole document, as a serde_json::Value. |
app().document() | The same before it is written, to add to it. |
rind openapi [--out FILE] | The document as a file, or on standard output. |
| `.describe( | document |
Extensions and conventions
| In the document | Meaning |
|---|---|
x-allowed | On each operation: who may call it (anyone, authenticated, staff, superuser, group(..)). |
security: [{"bearer": []}] | On an operation no anyone rule allows: it needs credentials. |
operationId | <path>_<operation>: stations_list, stations_count; stations_count_object for an object action that shares its name with a list action. |
tags | One per resource, its path, described by the resource’s doc comment. |
Exports: xlsx, CSV
Users often want a list as a spreadsheet: “give me the stations in
Excel”. rind can answer any list, or any single object, as an xlsx
workbook or a CSV file, with the same filters, search and ordering as
the JSON list.
In Django REST framework, this is the job of a renderer such as
drf-excel’s XLSXRenderer or djangorestframework-csv’s
CSVRenderer, chosen with ?format= or the Accept header. rind works
the same way from the client’s side. On the server’s side, an export
serializer says which columns a person sees, separately from the JSON
fields.
Turning exports on
The formats are plugins of the application. The sample installs both:
#![allow(unused)]
fn main() {
// sample/src/lib.rs
.with(
rind::export::Xlsx::new()
.style("count", rind::export::Style::new().number_format("0").bold()),
)
.with(rind::api::export::Csv::excel()) // `;` and a byte-order mark: Excel in French
}
Xlsx needs the xlsx feature of the rind crate. Csv is always
there. Csv::new() writes the standard CSV, with commas.
Csv::excel() writes ; and a UTF-8 byte-order mark, which is what
Excel opens correctly in a French locale.
Once a format is installed, every resource can be exported. Nothing else is needed for a first export.
Asking for an export
A client asks for a format with ?format=:
GET /stations?format=xlsx&ordering=code&fields=code,name,region_details
GET /stations/1?format=csv
Or with the Accept header, when there is no ?format=:
GET /stations
Accept: application/xlsx
Accept may name application/xlsx (what a real Django application’s
front end sent), the registered
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, or
text/csv.
The answer is a file to download:
Content-Disposition: attachment; filename="stations-2026-11-16.xlsx"
A list’s file is named after the resource and the day. A single object’s
file is named after the resource and the id (stations-1.csv).
Which rows are exported
The rows are the list’s: its filters, its search, its ordering, and only
the fields the request selects (fields, omit, include). The export
of /stations?status=closed holds the closed stations, as the JSON list
would.
Every row is exported, not only the first page, up to the resource’s
largest page size (50,000 by default; see
Pages). A list longer than that is a 400 that says
so, unless the request gives a page_size: then the export holds that
page only.
The cache does not keep an export, and ETags leaves it
alone.
Choosing the columns: an export serializer
Without an export serializer, an export has one column per field of the answer, in the output’s order, labelled by the field’s name. That is enough for a quick look, but a person reading a spreadsheet wants labels in their language, widths, a date as a date, and sometimes one column per value (a column per service).
An export serializer says this. It is a struct that derives Export,
written from the output it exports (of = StationOut). Each field is
one column, or a group of columns:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/exports.rs
use rind::Export;
use rind::api::export::{Cell, Column, Columns};
use super::serializers::StationOut;
#[derive(Export)]
#[export(of = StationOut, sheet = "Stations", name = "stations")]
pub struct StationXlsx {
#[column(label = "Code", width = 8)]
pub code: Column,
#[column(label = "Nom", width = 24)]
pub name: Column,
#[column(label = "Ville")]
pub city: Column,
/// Through a nested output: a column only when it is asked for.
#[column(label = "Région", from = region_details.name)]
pub region: Column,
#[column(label = "Ouverte le")]
pub opened: Column,
#[column(label = "Quais", style = "count")]
pub platforms: Column,
#[column(label = "Photo")]
pub photo: Column,
/// A function of the typed output.
#[column(label = "Position", with = position, needs(position))]
pub position: Column,
/// A column per service, made from the rows.
#[columns(with = services, needs(services))]
pub services: Columns,
}
fn position(station: &StationOut) -> Option<String> {
let point = station.position.flatten()?;
Some(format!("{:.4}, {:.4}", point.lat, point.lng))
}
fn services(station: &StationOut) -> Vec<(String, String, Cell)> {
station
.services
.iter()
.flatten()
.map(|s| (format!("service_{s}"), s.to_uppercase(), Cell::from("x")))
.collect()
}
}
The resource lists its export serializers:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/views.rs
#[resource(model = Station, /* … */ exports(StationXlsx, StationShortXlsx))]
pub struct StationResource;
}
The same export serializer is used for every format: xlsx and CSV get the same columns.
Where a column’s value comes from
There are three kinds of columns:
- A field of the answer. By default, a column reads the field of
the same name (
codereadscode).from = a.breads another field, or a field inside a nested output:from = region_details.namereads the region’s name. - A function.
with = fcallsf(&StationOut)on each row. It returns any value that converts into a cell (see below). - A group of columns.
#[columns(with = f)]makes columns from the rows.freturns(key, label, value)triples. There is one column per key, in the order the keys first appear. This is how you get a column per service, or a price per period.
The names in from and needs are checked against the output when the
application compiles: a misspelt field is a compile error.
A column is left out when its field is not selected
The client still chooses the fields with ?fields=. A column whose
field the request does not select is left out of the sheet:
- A
fromcolumn, or a column withoutfrom, needs the first field of its path. The “Région” column is there only when the request selectsregion_details. - A
withcolumn, or a group of columns, needs the fields named inneeds(..). Withoutneeds, it is always there.
Cells
A value read from the answer becomes a typed cell:
- a number is a number;
- a date (
2026-11-16) is a date, and a date and time is a date and time; - a file (
{url, name}) is a link; - a list of values is one text,
a, b; nullis an empty cell.
A with function may return a text, a number, a boolean, a date, an
Option of one, Cell::link(url, text), or Cell::Formula(..) (a
formula without its =).
Several exports for one resource
A resource can list several export serializers. The first one is the
default. A client chooses another by its name:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/stations/exports.rs
/// A short one: `?export=short`.
#[derive(Export)]
#[export(of = StationOut, sheet = "Stations", name = "short")]
pub struct StationShortXlsx {
#[column(label = "Code")]
pub code: Column,
#[column(label = "Nom")]
pub name: Column,
}
}
GET /stations?format=xlsx&export=short
An unknown export name is a 400 (No export named …).
Styles
The xlsx format has named styles. A column names its cells’ style with
style = "…" and its header’s style with header_style = "…". The
styles themselves are defined once, on the Xlsx plugin:
#![allow(unused)]
fn main() {
use rind::export::Style;
rind::export::Xlsx::new()
.style("count", Style::new().number_format("0").bold())
.style("header", Style::new().bold().background(0x02B5B1).color(0xFFFFFF))
.date_formats("dd/mm/yyyy", "dd/mm/yyyy hh:mm")
}
A header without its own style uses the style named header. By
default, it is bold, on a light grey background, with a border.
Defining header again, as above, changes every header.
date_formats sets how dates and date-times are shown. The default is
yyyy-mm-dd and yyyy-mm-dd hh:mm:ss.
In every workbook, the header row is frozen and has filters. The workbook is written row by row, so a large export does not hold the whole sheet twice in memory.
CSV has no styles: the style names are ignored there.
A format of your own
A format is a type that implements rind::api::export::Format. It
gives its name (the value of ?format=), the media types Accept may
name, its Content-Type, its file extension, and a write function
that turns a Sheet (columns and rows of cells) into bytes. A plugin
installs it with Setup::format.
The OpenAPI document then gives every read operation the format and
export parameters, and lists the formats’ media types among its
answers.
Reference
#[export(..)]
| Key | Meaning |
|---|---|
of = Out | The output it exports. Required. |
name = "…" | Its name for ?export=. By default, the struct’s name. |
sheet = "…" | The sheet’s name. By default, the struct’s name. Excel keeps 31 characters, and replaces []:*?/\. |
style = "…" | The default style of its columns. |
header_style = "…" | The default style of its headers. |
#[column(..)] and #[columns(..)]
A field of an export serializer is a Column with #[column(..)], or
Columns with #[columns(..)].
| Key | Meaning |
|---|---|
label = "…" | The header. By default, the field’s name. |
key = "…" | The column’s key. By default, the field’s name. |
from = a.b | The answer’s value at that path, by the output’s names. By default, the field of the same name. Not with with. |
with = f | f(&Out), any value Into<Cell>. On #[columns]: required, and f returns Vec<(key, label, Cell)>. |
needs(a, b) | The column is left out when one of these fields is not selected. A from column needs its first field anyway. |
width = N | The width, in characters. |
style = "…", header_style = "…" | The styles of its cells and of its header. |
Style
Style::new(), then any of: .bold(), .italic(), .size(points),
.color(0xRRGGBB), .background(0xRRGGBB), .align(Align::…),
.wrap(), .border(), .number_format("0.00").
Formats
| Format | ?format= | Accept | Feature |
|---|---|---|---|
rind::export::Xlsx | xlsx | application/xlsx, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet | xlsx |
rind::api::export::Csv | csv | text/csv | always |
Query parameters
| Parameter | Meaning |
|---|---|
format | The format’s name. |
export | The export serializer’s name; the first by default. |
Neither name may be used by a filter or a typed parameter.
Plugins
An application of some size soon wants more than its models and its resources: metrics, a cache, a log of who called what, files, mail, jobs. No application needs all of them, and many need none. In rind, each of these pieces is a plugin: a value that the application asks for, and that adds what it needs to the application when it is installed.
A plugin you do not ask for costs nothing. Its code is behind a Cargo feature, so it is not compiled and its dependencies are not downloaded. And at run time, an application without plugins runs no hooks and no observers at all.
Coming from Django: a plugin plays the part of three things in Django. Like an app in
INSTALLED_APPS, it can bring its own models, migrations, URLs and management commands. Like a middleware inMIDDLEWARE, it can run code around every request. And like a receiver ofpost_saveor ofconnection.execute_wrapper, it can be told of every statement and of every committed write. The difference is that a plugin is one Rust value, given in one place, and it can only add what the plugin API lets it add.
Enabling a plugin
Enabling a plugin takes two steps.
First, turn on its feature of the rind crate in your Cargo.toml. The
railway, rind’s sample application, asks for most of them:
# sample/Cargo.toml
[dependencies]
rind = { workspace = true, features = ["metrics", "usage", "cache-redis", "storage-s3", "images", "health", "mail-smtp", "mail-mailgun", "xlsx", "jobs"] }
Then install the plugin in the function that builds your application,
with .with(..):
#![allow(unused)]
fn main() {
// sample/src/lib.rs (shortened)
pub fn app() -> rind::Application {
bare_app()
.with(rind::metrics::Metrics::new())
.with(rind::health::Health::new())
.with(
rind::cache::Cache::from_env()
.expect("RIND_CACHE_URL")
.resource::<network_api::stations::StationResource>(std::time::Duration::from_secs(60)),
)
.with(
rind::storage::Storage::from_env()
.expect("RIND_STORAGE")
.sizes(rind::images::Sizes::new()),
)
// … mail, exports, signing in, jobs …
.with(rind::usage::Usage::new().body::<booking_api::reservations::ReservationResource>())
}
}
bare_app() is the same application without any plugin: its models, its
resources, and how users sign in. The railway keeps both functions, so
that a test can start from the bare application and add only the plugin
it tests (see Testing with plugins).
Many plugins read their settings from the environment with a
from_env() constructor, as the cache and the storage do above. Each
chapter lists the variables its plugin reads.
The plugins rind provides
| Plugin | Feature of rind | Chapter |
|---|---|---|
/status and /ready | health | Health |
| metrics for Prometheus | metrics | Metrics |
a cache, its answers, ETag and 304 | cache, cache-redis | Cache |
| the usage log | usage | Usage log |
| CORS headers | none (needs the axum or actix adapter) | CORS |
| mail: SMTP, Mailgun, templates, events | mail, mail-smtp, mail-mailgun | |
| jobs: scheduled, queued, on PostgreSQL | jobs | Jobs |
| lists as xlsx; CSV | xlsx; CSV needs none | Exports |
| files on a disk or in S3 | storage, storage-s3 | Files |
| images: their size, galleries, logos, resized copies | images | Images |
| tracking, flags, markdown | behaviours, markdown | Behaviours |
| signing in: tokens, passwords, codes | the rind-auth crate | Signing in |
Logging is not a plugin. rind always writes its events through
tracing, and the application chooses who reads them (see
Logging).
The rest of this chapter is for people who write a plugin of their own, or who want to know how the plugins above work.
Writing a plugin
A plugin is a type that implements the Plugin trait. The trait has one
method, install, which is called once, when the application is built
(by .with(..)):
#![allow(unused)]
fn main() {
pub trait Plugin: Sized {
fn install(self, setup: &mut Setup<'_>);
}
}
install receives a Setup. The Setup is the only way a plugin can
change the application, and it only offers what a plugin may add. Here is
a complete plugin, from the railway’s tests. It adds a service, a hook,
an observer and two routes:
#![allow(unused)]
fn main() {
// sample/tests/plugins.rs
use std::sync::Arc;
use rind::api::{Answer, Plugin, Route, Setup};
struct Greeting(&'static str);
struct Test(Arc<Counter>);
impl Plugin for Test {
fn install(self, setup: &mut Setup<'_>) {
setup
.service(Greeting("hello"))
.around(Tag(self.0.clone()))
.observe(Arc::new(Watch(self.0.clone())))
.route(Route::get("/ping", |call| async move {
let greeting = call.state.services.get::<Greeting>().map_or("", |g| g.0);
Answer::value(200, &serde_json::json!({ "pong": greeting }))
}))
.route(Route::get("/echo/*", |call| async move {
Answer::value(200, &serde_json::json!({ "rest": call.rest }))
}));
}
}
}
Tag and Watch are shown in the next sections. The application
installs it like any other plugin:
#![allow(unused)]
fn main() {
let app = sample::app().with(Test(counter.clone()));
}
GET /ping
{"pong": "hello"}
The methods of Setup are listed in the reference. The
most common ones are:
service(value): a value that every request can reach, found by its type. A request finds it withctx.service::<Greeting>(), a route withcall.state.services.get::<Greeting>(). There is one service per type.around(hook): a hook that runs around every call of a resource.observe(observer): an observer told of every statement and of every committed write.route(route): a route that is not a resource, such as/metrics.
The application can share a value of its own in the same way, without a
plugin: .service(value) on the Application, found with
ctx.service::<T>().
Running code around every call
A hook is the plugin’s middleware. It sees every call of every resource, and it decides when to call the rest of the chain.
Both web frameworks (axum and actix-web) read an HTTP request into
rind’s own Request. They hand it to one function that authenticates
the request, runs the hooks, serves the resource, and returns an
Answer. The framework then writes the answer back. A hook is therefore
written once, in rind’s own terms, and works with both frameworks. It is
not compiled again for each resource.
A hook implements Around:
#![allow(unused)]
fn main() {
// sample/tests/plugins.rs (shortened)
use rind::api::{Answer, Around, BoxFuture, Call, Next};
struct Tag;
impl Around for Tag {
fn around<'a>(&'a self, call: &'a Call<'a>, next: Next<'a>) -> BoxFuture<'a, Answer> {
Box::pin(async move {
let mut answer = next.run(call).await;
answer.set_header("x-resource", call.path()); // "stations"
answer.set_header("x-operation", call.operation.name()); // "list"
answer
})
}
}
}
next.run(call) runs the hooks that come after this one, then the
resource. With this hook, a list of the stations is answered with two
more headers:
GET /stations
HTTP/1.1 200 OK
x-resource: stations
x-operation: list
A hook can do three kinds of things:
- answer without calling
next: the cache does this when it has the answer already; - change the answer that
nextreturned: add a header, such as anETag; - look at the call and time it: metrics and the usage log do this.
The hooks run in the order the plugins were given to the application. The first one given is the outermost: it runs first, and it sees the answer last. Order matters when a hook answers by itself. For example, when the cache answers from its store, the hooks given after it do not run for that call.
The Call a hook receives describes the call in rind’s words: which
resource, which operation, which object, who asks. Its fields and methods
are listed in the reference.
A hook only sees the calls of resources. Routes that are not resources
(a plugin’s /metrics, or routes added by hand with Api::axum or
Api::actix) do not go through the hooks.
Coming from Django: a Django middleware sees every HTTP request, including the admin and static files. A rind hook sees resource calls only, and it sees them already parsed: you do not need to match the URL to know which resource is called.
Being told of every statement
An observer is told of the work of the database, whoever asked for it:
a request, a job, or a command. It implements Observe:
#![allow(unused)]
fn main() {
// rind::db::observe
pub trait Observe: Send + Sync + 'static {
fn statement(&self, statement: &Statement<'_>) {}
fn committed(&self, database: &str, tables: &[&'static str]) {}
}
}
Both methods have a default body, so an observer implements only what it needs. The railway’s test observer counts statements and remembers the tables that were written:
#![allow(unused)]
fn main() {
// sample/tests/plugins.rs
use rind::db::observe::{Observe, Statement};
struct Watch(Arc<Counter>);
impl Observe for Watch {
fn statement(&self, _: &Statement<'_>) {
self.0.statements.fetch_add(1, Ordering::SeqCst);
}
fn committed(&self, _: &str, tables: &[&'static str]) {
self.0.committed.lock().unwrap().extend_from_slice(tables);
}
}
}
statement is called after each statement that a Db runs. The
Statement says its kind (select, insert, update, delete, or
raw), its table, the database, how long it took, how many rows it read
or changed, and whether it failed.
committed is called when a write is kept, with the tables it changed:
- inside a transaction, when the transaction commits, not before;
- never when the transaction is rolled back;
- at once for a write outside a transaction.
So a PATCH /stations/1 that succeeds tells the observer
["network_station"], and a PATCH refused with a 400 tells it nothing.
Both methods run on the task that ran the statement. They must be quick, and hand anything slow to a task of their own (the cache spawns one).
Hand-written SQL. rind does not read SQL, so a statement written by hand is reported with no table. When such code writes a table, it says so, so that the observers (the cache in particular) know:
#![allow(unused)]
fn main() {
db.wrote("network_station");
}
Inside a transaction, this is told when the transaction commits.
Coming from Django:
committedis close totransaction.on_commitcombined withpost_save, but it is per table, not per object, and it also sees bulk updates and deletions.
Options on a resource
Some plugins are set per resource: the cache keeps some resources and not others, and the usage log keeps the body of some calls. There are two places to say it.
In the application, when the plugin is built:
#![allow(unused)]
fn main() {
rind::cache::Cache::from_env()
.expect("RIND_CACHE_URL")
.resource::<StationResource>(Duration::from_secs(60))
}
Or on the resource itself, with options(..):
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-api/src/trains/views.rs
#[derive(Resource)]
#[resource(
model = Train,
path = "trains",
out = TrainOut,
filters = TrainFilters,
input = TrainIn,
delete,
options(cache_ttl = 30, cache_by_mode)
)]
pub struct TrainResource;
}
The Resource derive keeps the options as they are written, without
knowing what they mean. A value can be an integer, a string or a
boolean, and a bare name (cache_by_mode) means true. The plugin
reads them at run time, with call.option("cache_ttl").
When the application and the resource both set the same thing, the application wins.
The derive does not check the option names: a misspelt option is ignored without an error. The options rind’s plugins read are:
| Option | Plugin | Value |
|---|---|---|
cache_ttl | cache | seconds, an integer |
cache_by_mode | cache | a boolean |
usage | usage log | "skip", "skip_reads", "body" or "no_body" |
Testing with plugins
The railway tests each plugin in sample/tests/plugins.rs, together with
a plugin of the test’s own (the Test plugin above). A test that wants
an application without plugins, or with only one, starts from
bare_app():
#![allow(unused)]
fn main() {
let app = sample::bare_app().with(rind::cache::ETags);
}
Reference
Setup
setup. | What it adds |
|---|---|
service(value) | a value the requests share, found by its type: ctx.service::<Storage>() |
service_shared(arc) | the same, for a value the plugin keeps a handle on |
find::<T>() | (reads) a service given before, by another plugin or by the application |
around(hook), around_shared(arc) | a hook around every call of a resource |
observe(observer) | an observer of every statement, and of what each committed write changed |
models(domain) | models of its own: tables and migrations, applied with the application’s |
api(api) | resources of its own |
route(route) | a route that is not a resource (/metrics), served by both web frameworks |
command(name, about, run) | a command of the application’s command line (cache-clear) |
health(name, check) | a readiness check, run by /ready |
wrap_auth(f) | replaces how requests sign in, given the authenticator the application had: what rind-auth does |
format(format) | a format lists can be exported in (?format=xlsx): see Exports |
describe(f) | what its routes add to the OpenAPI document |
Call
call. | What it is |
|---|---|
path() | the resource’s path, the same for every object: stations |
operation | List, Retrieve, Create, Update { partial }, Destroy, or Action { name, method, cached, status } |
operation.name() | the name the permission rules use: list, partial_update, an action’s name |
operation.writes() | may the call change something? (a GET action does not) |
operation.may_be_kept() | may its answer be kept: a list, a retrieve, a cached GET action |
id | the object of a retrieve, an update, a deletion, or a detail action |
params | the query parameters |
request | the method, the full path, the query string, the headers, the client’s address (peer), the body |
header(name) | a header of the request (name in lower case) |
user() | who asks, once authenticated |
ctx | the context the call is served in, or the error if the credentials are wrong; ctx() gives it as an Option |
option(name) | an option of the resource (above) |
export_format() | the export format the request asks for (xlsx, CSV), if any |
served | the resource: its model’s table, the tables its answers read, its rules |
state | the application’s state: its databases, its services |
Answer
An Answer has a status, headers (names in lower case) and a body
of bytes. Answer::new(status), Answer::json(status, bytes),
Answer::value(status, &json) and Answer::error(&api_error) build one;
header(name) reads a header and set_header(name, value) sets or
replaces one.
Route
Route::get(path, handler) and Route::post(path, handler) build a
route. A path that ends with /* (/media/*) matches everything below
it, and the handler finds what matched in call.rest. The handler
receives a RouteCall with the application’s state, the request, and
rest. A route does not go through the hooks and is not authenticated.
Logging
When something goes wrong in production, you want to know which request
failed, which statements it ran, and how long they took. rind writes all
of this as events of tracing, the standard
logging library of async Rust. You do not need to enable anything: the
events are always written. When nothing reads them, they cost almost
nothing.
Coming from Django: this replaces the
LOGGINGsetting and thedjango.requestanddjango.db.backendsloggers. In rind, the target of an event plays the part of a logger’s name (rind::sqlinstead ofdjango.db.backends), and theRUST_LOGvariable plays the part of theLOGGINGdictionary.
Seeing the logs
An application that uses rind’s command line (rind::cli::main, as the
railway does) already has a writer: the command line sets one up before
running any command. Two environment variables control it:
RUST_LOGsays what is written. It isinfoby default. Set it toinfo,rind::sql=debugto also see every statement.RIND_LOG=jsonwrites one JSON object per line, which is what a log collector reads. Without it, the events are written as text.
The events go to the standard error. For example, to serve the railway with every statement, as JSON:
$ RIND_LOG=json RUST_LOG=info,rind::sql=debug cargo run -p sample -- serve
A list of the stations then writes:
{"level":"DEBUG","fields":{"message":"statement","kind":"select","table":"network_station","ms":1.45,"rows":2},
"target":"rind::sql","span":{"method":"GET","operation":"list","resource":"stations","name":"request"}, …}
{"level":"INFO","fields":{"message":"answered","status":200,"ms":3.09},"target":"rind::request", …}
Each statement is written inside the span of its request: a span is a
piece of context that tracing attaches to every event written while it
is open. So each statement says which request ran it (here, the list of
stations by GET).
What rind writes
Each call of a resource is a span, named request, under the target
rind::request. Its fields are the method, the resource, the operation,
the object’s id, and the user once authenticated. When the call is
answered, an answered event gives the status and the time in
milliseconds.
Each statement is an event under the target rind::sql:
- at
debug, every statement: its kind, its table, its time and its rows; and acommittedevent with the tables a write changed; - at
warn, a statement slower thanRIND_SLOW_QUERY_MSmilliseconds (500 by default), with its SQL; - at
trace, the SQL of every statement.
A request that fails on the server’s side (a database error, a bug) is
an error event under the target rind_api::error. The client gets a
500 with {"detail": "Internal server error."}, without the cause; the
cause is in the log.
The plugins write what they could not do, at warn or error, under a
target of their own: rind::cache (Redis unreachable), rind::usage
(the usage log is full, or a batch could not be written),
rind::storage (a file the database names is missing from the storage),
rind::health (a readiness check failed), rind::mail, rind::job,
rind::images, and rind::auth.
The parameters of a statement are never logged. They are the users’
data: names, addresses, passwords. Only the SQL text, with its
placeholders ($1), is written, and only at trace.
Using your own writer
An application that wants another writer (OpenTelemetry, a file, a
different format) sets it up in main before calling rind::cli::main.
The command line sees that a writer exists already, and leaves it in
place:
fn main() -> std::process::ExitCode {
// Set up your own `tracing` subscriber here.
rind::cli::main(sample::app())
}
A program that logs with the older log crate
can receive rind’s events too: turn on the log feature of tracing in
your Cargo.toml, and tracing also writes each event as a log
record when no tracing writer is set up.
Reference
| Target | Level | What is written |
|---|---|---|
rind::request | info | a span per resource call (method, resource, operation, id, user), and answered at its end, with the status and the time |
rind::sql | debug | each statement: its kind, its table, its time, its rows; a failed statement (statement failed, with the error); committed with the tables a write changed |
rind::sql | warn | a statement slower than RIND_SLOW_QUERY_MS (500 by default), with its SQL |
rind::sql | trace | the SQL of each statement |
rind_api::error | error | a request that failed on the server’s side (the client gets a 500 without the cause) |
rind::usage, rind::cache, rind::storage, rind::health, … | warn, error | what a plugin could not do: a full usage log, an unreachable Redis, a file the database names and the storage does not have, a failed readiness check |
| Variable | Default | Effect |
|---|---|---|
RUST_LOG | info | what is written, as tracing-subscriber’s EnvFilter reads it |
RIND_LOG | text | json: one JSON object per line |
RIND_SLOW_QUERY_MS | 500 | the time past which a statement is logged at warn |
The writer is set up by rind::cli::logging(), which rind::cli::main
calls before any command. You can call it yourself in a program that
does not use the command line.
CORS
You need CORS when a front end is served from another origin than its
API: for example, an admin interface at https://admin.example that
calls https://api.example. An origin is a scheme, a host and a port.
By default, a browser does not let a page call an API of another origin.
It lets the call through only when the API says, in its answers, that
this origin is allowed. This protocol is called CORS (Cross-Origin
Resource Sharing).
If your front end and your API are served from the same origin, you do not need CORS at all, and rind sends no CORS header unless you ask for it.
Coming from Django: this is what
django-cors-headersdoes, with itsCORS_ALLOWED_ORIGINS,CORS_ALLOW_HEADERS,CORS_EXPOSE_HEADERS,CORS_ALLOW_CREDENTIALSandCORS_PREFLIGHT_MAX_AGEsettings. In rind it is a plugin,rind::api::cors::Cors, set from the environment or in code.
Turning it on
CORS needs no Cargo feature: it is part of the web framework adapters
(the axum and actix features of rind, which a served application
has already). Install the plugin in your app() function:
#![allow(unused)]
fn main() {
use rind::api::cors::Cors;
rind::Application::new("The railway", env!("CARGO_PKG_VERSION"))
// … models, APIs …
.with(Cors::from_env().expect("RIND_CORS_*"))
}
Then say which origins may call the API, in the environment:
RIND_CORS_ORIGINS=https://admin.railway.example
That is all a typical front end needs. Several origins are separated by
commas, and * allows every origin. Each origin is a scheme and a host,
with an optional port, and no path: https://admin.example, not
https://admin.example/.
When RIND_CORS_ORIGINS is not set, from_env still succeeds, and CORS
stays off. So you can install the plugin in every application, and turn
CORS on only where it is needed.
You can also give the settings in code:
#![allow(unused)]
fn main() {
use rind::api::cors::Cors;
app.with(Cors::origins(["https://admin.railway.example"]).allow_headers(["x-route-url"]))
// or every origin, `*`:
app.with(Cors::any())
}
What the browser asks, and what rind answers
Before a call that is not a simple read, the browser sends a preflight:
an OPTIONS request to the same URL, which says where the page comes
from and what it wants to send.
OPTIONS /stations
Origin: https://admin.railway.example
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization,content-type
rind answers with what is allowed (the exact spelling of the lists depends on the web framework):
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://admin.railway.example
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE,OPTIONS
Access-Control-Allow-Headers: accept,authorization,content-type,user-agent,x-requested-with
Access-Control-Max-Age: 86400
Then the browser sends the real request, with its Origin, and reads
Access-Control-Allow-Origin on the answer. A page from an origin that
is not listed gets no Access-Control-Allow-Origin, and the browser
refuses to give it the answer.
The methods allowed are always those rind serves: GET, POST, PUT,
PATCH, DELETE and OPTIONS.
Headers the browser may send, and headers it may read
By default, a browser lets a page send accept, authorization,
content-type, user-agent and x-requested-with: what a client of a
JSON API with a token sends. If your front end sends a header of its
own, add it with RIND_CORS_ALLOW_HEADERS or .allow_headers([..]).
A browser also hides most answer headers from the page. rind lets the
page read the headers it sets for clients: content-disposition (the
name of a downloaded file), etag and last-modified (see
Cache), x-rind-cache, and x-db-position (see
Databases). Add others with RIND_CORS_EXPOSE_HEADERS or
.expose_headers([..]).
Header names are compared in lower case, and a name given twice is kept once.
Cookies and credentials
By default, the browser is told not to send cookies or HTTP
authentication with a cross-origin call. rind’s tokens travel in the
Authorization header, so they do not need it. If your front end
authenticates with cookies, set RIND_CORS_CREDENTIALS=true, or
.credentials(true).
Credentials cannot go with every origin (*): browsers refuse that
combination. rind refuses it first: Cors::from_env() returns an error,
and .with(..) panics when the application is built. List the origins
instead.
Where it acts
CORS is applied around the whole application, before routing, as
django-cors-headers does. This has two effects:
- A preflight is answered on any path: a resource, an action, a plugin’s
route (
/status), even a path the application does not serve. - Every answer carries the headers, errors included: a
401, a404, an adapter’s own404or405. Without this, a browser would hide the error from the page, and the front end could not show it.
The cache needs nothing special: the CORS headers are added
after it, and Origin is added to the answer’s Vary.
How it is applied depends on the web framework:
-
axum:
Application::routerwraps every route in tower-http’sCorsLayer. If you useApplication::routesinstead, to merge rind’s routes into a router of your own, the layer covers rind’s routes only: the paths it does not serve belong to your router. -
actix-web: a middleware belongs to the
App, not to a route, so you wrap theAppwithapp.actix_cors():#![allow(unused)] fn main() { App::new() .wrap(app.actix_cors()) .app_data(web::Data::new(app.state(db.clone()))) .configure(|cfg| app.configure(cfg)) }Without CORS settings,
actix_cors()does nothing.
rind’s own serve command does this for you, with both frameworks.
Reference
| Variable | Meaning | Default |
|---|---|---|
RIND_CORS_ORIGINS | the origins, comma-separated (https://admin.example, no path), or * | none: CORS is off |
RIND_CORS_ALLOW_HEADERS | request headers allowed besides the defaults | accept, authorization, content-type, user-agent, x-requested-with |
RIND_CORS_EXPOSE_HEADERS | answer headers a client may read besides the defaults | content-disposition, etag, last-modified, x-rind-cache, x-db-position |
RIND_CORS_CREDENTIALS | true (or 1, yes, on): cookies and HTTP authentication are sent along | off: rind’s tokens are a header |
RIND_CORS_MAX_AGE | seconds a browser keeps a preflight’s answer | 86400 |
Cors::from_env() returns an error for credentials with *, for an
origin that is not http://… or https://… or that ends with /, and
for a RIND_CORS_MAX_AGE that is not a number.
| In code | Meaning |
|---|---|
Cors::origins([..]) | these origins, exactly |
Cors::any() | every origin (*) |
Cors::default() | off |
.allow_headers([..]) | request headers allowed besides the defaults |
.expose_headers([..]) | answer headers exposed besides the defaults |
.credentials(bool) | credentials sent along; only with listed origins |
.max_age(seconds) | how long a preflight is kept |
.check() | the same checks as from_env, as a Result |
.is_on() | whether any origin is allowed |
.layer() (axum), .actix() (actix-web) | the framework’s own CORS middleware for these settings |
The defaults are the constants ALLOW_HEADERS, EXPOSE_HEADERS and
METHODS of rind::api::cors.
Health
When your API runs under Kubernetes, behind a load balancer, or under
any supervisor, that supervisor needs to ask two questions. Is the
process alive, or should it be restarted? And is it ready to serve, or
should requests go elsewhere for now? The health plugin answers both,
with two routes:
GET /status, the liveness probe: it answers as long as the process answers;GET /ready, the readiness probe: it checks the servers the application depends on (its databases, Redis, the storage…) and answers200only when all of them answer.
Coming from Django: Django has no built-in health check. This is what packages such as
django-health-checkprovide, with its checks for the database, the cache and the storage. In rind, the plugins declare their own checks, so you do not list them.
Turning it on
Turn on the health feature of rind in your Cargo.toml:
rind = { version = "…", features = ["health"] }
Then install the plugin in app():
#![allow(unused)]
fn main() {
// sample/src/lib.rs
.with(rind::health::Health::new())
}
It reads no environment variable.
Asking if the process is alive
GET /status
{"status": "OK"}
/status runs no check and touches no database. It answers 200 as
long as the process can answer at all. A supervisor that gets no answer
restarts the process.
Asking if the application is ready
/ready runs every check at the same time, each with a timeout of
2 seconds. It answers 200 when every check passes, and 503 when any
check fails. In both cases, the body says how each check went, and how
long it took in milliseconds:
GET /ready
{
"status": "FAIL",
"checks": {
"database:default": { "ok": true, "ms": 0.4, "detail": null },
"database:default:replica1": { "ok": true, "ms": 0.6, "detail": "lag 0.2 s" },
"cache": { "ok": false, "ms": 2000.1, "error": "no answer within 2000 ms" },
"storage": { "ok": true, "ms": 0.1, "detail": null }
}
}
Here the cache’s Redis did not answer within the timeout, so the whole
answer is 503, with "status": "FAIL". When everything passes,
status is "OK". The answer carries Cache-Control: no-store, so
that no proxy keeps it.
You do not have to declare the checks of rind’s servers. /ready runs:
- each database’s servers. The primary must answer
SELECT 1. Each replica must answer, and it tells its lag (how far behind the primary it is). A late replica does not fail the check: reads already avoid a replica that may not have a recent write (see Databases). - the checks of the plugins installed, for the servers they depend
on:
cache(Redis answersPING; a cache in memory always passes),storage(the folder or the bucket answers),mail(the mail transport), andjobs(how many jobs are due, and how old the oldest one is). - the application’s own checks (next section).
Adding a check of your own
An application often depends on other servers: an upstream API, a search engine. Add a check for each, either on the plugin:
#![allow(unused)]
fn main() {
.with(rind::health::Health::new().check("upstream", |_state| async {
reach_upstream().await.map(|_| None).map_err(|e| e.to_string())
}))
}
or on the application, from anywhere it is put together, even in a crate that does not know about the health plugin:
#![allow(unused)]
fn main() {
.health("upstream", |_state| async { Ok(Some("v2".to_owned())) })
}
A check is an async function that receives the application’s state (its databases and services). It returns:
Ok(None)when it passes, with nothing to show;Ok(Some(detail))when it passes, with a detail worth showing (a version, a lag);Err(reason)when it fails, with why.
A plugin declares its own checks in the same way, with
Setup::health(name, check) (see Plugins).
What the routes do not do
Neither route needs credentials: a supervisor has no token. Neither
route is a resource, so neither goes through the plugins’ hooks, and
neither appears in the usage log or in the
metrics. The successes are not logged; a failed check is
logged as a warning, under the target rind::health (see
Logging).
Reference
| Route | Answers | For |
|---|---|---|
GET /status | 200 {"status": "OK"} as long as the process answers | a liveness probe |
GET /ready | 200 when every check passes, 503 when any fails, with each check’s result | a readiness probe |
Health:: | Meaning |
|---|---|
new() | the two routes, at /status and /ready, with a timeout of 2 s |
.paths(status, ready) | other paths for the two routes: .paths("/healthz", "/readyz") |
.timeout(duration) | how long a check may take before it fails |
.check(name, check) | a check of the application’s own |
The names of the checks rind declares are database:<name> for a
primary, database:<name>:replica<n> for a replica, cache, storage,
mail and jobs.
Metrics
Logs tell you what happened to one request. Metrics tell you how the
whole application behaves over time: how many requests each resource
gets, how long they take, how many fail, how many statements they run,
how busy the connection pools are. The metrics plugin counts all of
this and serves it at /metrics, in the format
Prometheus reads. From there, Grafana or any
tool that reads Prometheus can draw it and raise alerts.
Coming from Django: this is what
django-prometheusdoes, with its middleware and its database wrapper. In rind it is one plugin: it counts the resource calls with a hook, and the statements with an observer (see Plugins). It also counts the statements of jobs and commands, not only those of requests.
Turning it on
Turn on the metrics feature of rind in your Cargo.toml:
rind = { version = "…", features = ["metrics"] }
Then install the plugin in app():
#![allow(unused)]
fn main() {
// sample/src/lib.rs
.with(rind::metrics::Metrics::new())
}
It reads no environment variable. Point Prometheus at the application’s
/metrics.
What you get
After a few requests to the railway, /metrics answers:
GET /metrics
rind_requests_total{resource="stations",operation="list",method="GET",status="200"} 1
rind_requests_total{resource="stations",operation="partial_update",method="PATCH",status="200"} 1
rind_writes_committed_total{database="default",table="network_station"} 1
…
The answer is in the OpenMetrics text format
(application/openmetrics-text).
The series fall into three groups.
The resource calls. rind_requests_total counts the calls, by
resource, operation, method and status. rind_request_duration_seconds
is a histogram of their times, by resource, operation and method. The
resource label is the resource’s path (stations), and the
operation label is the name the permission rules use (list,
partial_update, or an action’s name).
A label is always a resource’s path, never a request’s path: there is one
series per route, not one per object. GET /stations/1 and
GET /stations/2 are both counted as resource="stations", operation="retrieve". This keeps the number of series small, which
Prometheus needs.
The statements. rind_statements_total counts them, by database,
kind (select, insert, update, delete, raw), table, and outcome
(ok or error). rind_statement_duration_seconds is a histogram of
their times. rind_rows_total counts the rows read by a select, or
changed by a write. rind_writes_committed_total counts the writes that
were kept, per table: a transaction that changes a table several times
counts once for that table, and a rolled-back write does not count.
The connection pools. rind_db_connections says, for each server of
each database, how many connections are open, how many are idle, and
how many may be open at most. It is read each time /metrics is asked.
The durations are in seconds, in buckets from 1 ms to about 16 s.
Keeping /metrics private
/metrics is a route like the others: anyone who can reach the
application can read it. It needs no credentials, and it is not in the
OpenAPI document. Keep it private behind your proxy (a proxy that does
not forward it), or move it to another path:
#![allow(unused)]
fn main() {
.with(rind::metrics::Metrics::new().path("/internal/metrics"))
}
Adding series of your own
An application can add its own series to the same registry, so that they
are served at the same /metrics. The series types come from the
prometheus-client crate, which
your application then depends on, in the same version as rind (0.24).
Metrics is cheap to clone, and its clones share one registry. So you
can register a series before installing the plugin:
#![allow(unused)]
fn main() {
use prometheus_client::metrics::counter::Counter;
let bookings = Counter::<u64>::default();
let metrics = rind::metrics::Metrics::new();
metrics.register("bookings", "Seats booked", bookings.clone());
let app = bare_app().with(metrics);
// Later, where a seat is booked:
bookings.inc();
}
The name is prefixed with rind_, like rind’s own series: this counter
is served as rind_bookings_total.
The plugin is also a service, so code that runs inside a request can find it:
#![allow(unused)]
fn main() {
let metrics = ctx.service::<rind::metrics::Metrics>().unwrap();
}
Register each series once, when the application starts, not in each request.
What is not counted
The routes that are not resources do not go through the plugin’s hook:
/metrics itself, /status and /ready, a plugin’s routes, and routes
you added by hand with Api::axum or Api::actix. To count those, use
your web framework’s own middleware.
Reference
| Series | Labels |
|---|---|
rind_requests_total | resource, operation, method, status |
rind_request_duration_seconds | resource, operation, method |
rind_statements_total | database, kind (select, insert, update, delete, raw), table, outcome (ok, error) |
rind_statement_duration_seconds | database, kind, table |
rind_rows_total | database, kind, table: rows read, or changed |
rind_writes_committed_total | database, table: writes kept, a transaction counted once per table |
rind_db_connections | database, server (0 the primary, then the replicas), state (open, idle, max) |
Hand-written SQL has an empty table label, since rind does not read
SQL.
Metrics:: | Meaning |
|---|---|
new() | the series above, served at /metrics |
.path(path) | serves them at path instead |
.register(name, help, metric) | adds a series of the application’s own (its name prefixed with rind_) |
.encode() | the series as text, as /metrics answers them |
Cache
Some answers are expensive to build and change rarely: a list of 500
rows with their nested objects, a count over a large table. The cache
plugin keeps such answers and sends them again without reading the
database. In a real application, a list of 500 rows (594 KB) took
320 ms to read, and 1 ms to send from the cache.
The plugin has two parts:
- a store, for your code: you keep values in it and read them back,
as with Django’s
cache.getandcache.set; - the answers of resources: the lists and retrieves of the resources you name are kept, and made stale automatically when a table they read is written.
Coming from Django: the store is Django’s cache framework (
django.core.cache), with a memory backend and a Redis backend. The answers of resources replacecache_pageand the per-view cache, with one big difference: you do not have to invalidate anything by hand. rind knows which tables an answer was read from, and it sees every write the application commits.
Turning it on
Turn on the cache feature of rind in your Cargo.toml, or
cache-redis for a cache in Redis:
rind = { version = "…", features = ["cache-redis"] }
Then install the plugin in app(), and name the resources whose answers
it keeps:
#![allow(unused)]
fn main() {
// sample/src/lib.rs
.with(
rind::cache::Cache::from_env()
.expect("RIND_CACHE_URL")
.resource::<network_api::stations::StationResource>(std::time::Duration::from_secs(60)),
)
}
Cache::from_env() reads RIND_CACHE_URL:
- not set, empty, or
memory: the cache is in the process’s memory; redis://host:port/db: the cache is in Redis, shared by every process of the application. This needs thecache-redisfeature.
Any other value is an error.
With this setting, the railway keeps its stations’ answers for a minute:
GET /stations
HTTP/1.1 200 OK
etag: "3f2a…"
last-modified: Fri, 27 Nov 2026 10:00:00 GMT
cache-control: no-cache, must-revalidate
vary: Authorization
x-rind-cache: miss
The first request reads the database (x-rind-cache: miss). The next
one, by the same user, within the minute, is sent from the cache
(x-rind-cache: hit) unless a station was written in between.
Keeping values from your code
The plugin is a service, so code that runs in a request (an action, a
hook, a loader) finds it with ctx.service:
#![allow(unused)]
fn main() {
let cache = ctx.service::<rind::cache::Cache>().unwrap();
let counts = cache
.get_or_set("seat-counts", Duration::from_secs(600), async || count_seats(ctx).await)
.await?;
}
get_or_set returns the value kept under "seat-counts" if there is
one. Otherwise it runs the function, keeps its result for 10 minutes,
and returns it. If the function fails, nothing is kept and the error is
returned. The value is kept as JSON, so its type must implement
Serialize and Deserialize.
The other methods are get, set and remove (for bytes), and their
JSON forms get_json and set_json.
A cache never fails a request. When the store fails (Redis is down,
for example), it answers as an empty store: get finds nothing, and
set keeps nothing. The failure is logged as a warning under the target
rind::cache, and /ready reports it (see Health).
The store can be in the process’s memory (Cache::memory(), up to
10,000 values), or in Redis (Cache::redis(url)). A store in memory is
right for one process and for tests. A store in Redis is shared by every
process of the application, so a value kept by one is found by the
others.
Keeping the answers of resources
The cache keeps the lists and the retrieves of the resources it is told
about, and the cached actions of those resources. It sends them again
without reading the database.
There are two ways to tell it about a resource. In the application, as
above, with .resource::<R>(ttl). Or on the resource itself, with
options(..) (see Plugins):
#![allow(unused)]
fn main() {
// sample/crates/fleet/fleet-api/src/trains/views.rs
#[resource(
model = Train,
path = "trains",
// …
options(cache_ttl = 30, cache_by_mode)
)]
pub struct TrainResource;
}
cache_ttl is the time to live, in seconds. When the application and
the resource both say something, the application wins.
Only answers with status 200 are kept. An export (?format=xlsx,
?format=csv) is never kept.
Who shares an entry
By default, an entry is for the user who asked, and for nobody else. Two users never share an entry, and anonymous users share one.
This is safe, but it means each user fills the cache for themselves.
Some resources answer the same thing to every user that the same rule
lets in: every signed-in user sees the same trains, for example. Such a
resource can say so, with .resource_by_mode::<R>(ttl) in the
application, or with options(cache_by_mode) on the resource. Its
entries are then kept per rule (per mode, see
Permissions), and shared by every user of that rule.
Be careful: this is rarely true. Two users of one mode often see different rows (each one sees their own reservations, for example). Use it only when the answers depend on nothing but the rule.
What makes an entry stale
A write to a table the answer was read from makes the entry stale.
The tables an answer reads are the resource’s model’s table, and those
of the outputs it nests: the Serializer derive lists them
(Serializer::tables).
The cache learns of writes through its statement observer (see Plugins). So it sees every write the application commits, whoever wrote it: the resource itself, another resource, a hook, a job of the process. A write that is rolled back changes nothing.
The answer to a write is sent only once the entries it made stale are stale. So the client’s next read gets the new rows, never the old ones.
Note: the derive lists the model’s table and the nested outputs’ tables only. A field computed by a loader (
#[computed(..)]) or by an annotation (#[annotated(..)]) may read other tables, and a write to those does not make the entry stale. Give such a resource a short time to live, or make the entries stale yourself withclear_table(below).
How it works. Each table has a generation in the store: a counter, raised on each write to the table. The key of an entry holds the generations of the tables it read. When a write raises a generation, the key that an answer would now have is a new one, so every entry that read the table becomes unreachable, in every process that shares the store. The cache does not have to search for the old entries: they simply expire.
What the cache cannot see
The cache does not see a write made by another program, or by SQL that rind did not run. The time to live bounds how long such an answer stays stale. You can also tell the cache yourself:
cache.clear_table(database, table)says that a table changed, as a write would;cache.clear(), or the commandcache-clear, makes every answer stale.
$ cargo run -p sample -- cache-clear
The cache's answers are stale.
Code that writes a table with hand-written SQL can also call
db.wrote("table"): the observers, the cache among them, are then told
on commit as for any other write.
Replicas
When the application reads on replicas (see
Databases), an answer read on a replica just after a
write to one of its tables may be old: the replica may not have the
write yet. If the cache kept that answer, it would put the old rows back
for everyone. So an answer read on a replica within 5 seconds of a write
to one of its tables is sent, but not kept. Change the delay with
Cache::replica_lag(duration).
The key of an entry
The key of an entry is made of:
- the resource, and the operation (a list and an action of the same path have different keys);
- the object, for a retrieve;
- the query parameters, in a fixed order:
?page=1&ordering=nameand?ordering=name&page=1share one entry; - who asks: the user, or the rule with
cache_by_mode; - the generations of the tables it read.
Actions
A GET action that says cached (#[action(GET, cached)], see
Actions) is kept as a list is, under its
own name: the get_flags action of the Flags
behaviour, for example. No other action is ever kept.
Asking for a fresh answer
A client sometimes wants an answer read from the database, not the cache’s. A request asks for it in one of two ways:
- the header
Cache-Control: no-cache(orPragma: no-cache), which a browser sends on a hard reload; - the parameter
no_cache, ornocache, with any value (?no_cache=1). This is easier to add to a link, or to a client’s parameters, than a header.
GET /stations?no_cache=1
The answer read takes the old one’s place in the cache, so the next
request gets it from the cache: the first answer says
x-rind-cache: refresh, and the next one hit.
The parameter is not part of the key. No filter may use the name
no_cache or nocache: the FilterSet derive refuses it with a
compile error. Asking for a fresh answer needs no permission: without a
cache, every request reads the database anyway.
The OpenAPI document lists no_cache on every read the cache may keep.
Sending a 304 when nothing changed
A kept answer carries these headers:
ETag: a hash of the body;Last-Modified: when the answer was read;Cache-Control: no-cache, must-revalidate: the client must ask again each time, but may send what it has;Vary: Authorization: the answer depends on who asks;x-rind-cache:hit,missorrefresh.
A client that sends the ETag back, in If-None-Match, gets a 304 Not Modified with no body when the answer has not changed:
GET /stations
If-None-Match: "3f2a…"
HTTP/1.1 304 Not Modified
So a front end can ask every time, and is answered at once when nothing changed. Browsers do this by themselves.
ETag without a cache
rind::cache::ETags is a second, smaller plugin. It gives every list,
every retrieve and every cached action an ETag, Cache-Control and
Vary, and answers 304 to a client that sends the ETag back. It
keeps nothing: the transfer is spared, not the work, since the answer is
still built to compute its hash. It sends no Last-Modified and no
x-rind-cache.
#![allow(unused)]
fn main() {
.with(rind::cache::ETags)
}
Where to put the cache among the plugins
The plugins’ hooks run in the order the plugins were given, the first outermost (see Plugins). When the cache answers from its store, the hooks given after it do not run for that call. Give the plugins that must see every call, such as the metrics and the usage log, before the cache.
Reference
| Variable | Meaning | Default |
|---|---|---|
RIND_CACHE_URL | memory, or redis://host:port/db (needs cache-redis) | memory |
Cache:: | Meaning |
|---|---|
from_env() | memory, or Redis, as RIND_CACHE_URL says |
memory() | in the process’s memory, up to 10,000 values |
redis(url) | in Redis (feature cache-redis) |
with_store(store) | in a store of your own: a type that implements rind::cache::Store |
.resource::<R>(ttl) | keeps the answers of R for ttl, per user |
.resource_by_mode::<R>(ttl) | keeps the answers of R for ttl, per rule |
.config::<R>(Config { ttl, by_mode }) | the same two, as a value |
.prefix(prefix) | the keys of the store start with prefix (rind: by default): for several applications in one Redis |
.replica_lag(duration) | how late a replica can be (5 s by default) |
| Method | Meaning |
|---|---|
get(key), set(key, bytes, ttl), remove(key) | a value of the application’s |
get_json(key), set_json(key, &value, ttl) | the same, as JSON |
get_or_set(key, ttl, f) | the value of key, or the one f makes, kept for ttl |
clear_table(database, table) | makes the answers that read table stale |
clear() | makes every kept answer stale |
| Resource option | Meaning |
|---|---|
cache_ttl = 60 | keeps the answers for 60 seconds |
cache_by_mode | one entry per rule, not per user |
| Command | Meaning |
|---|---|
cache-clear | makes every answer the cache keeps stale |
| Header sent | Values |
|---|---|
x-rind-cache | hit, miss, refresh |
The parameters that ask for a fresh answer are the constant
rind::cache::FRESH_PARAMS: no_cache and nocache.
Usage log
Sometimes you need to know who did what, and when: who deleted this
reservation, which client calls this resource a thousand times an hour,
which user has not signed in for months. The usage plugin writes one
entry per resource call, in a table of the database, where you can query
it with SQL.
An entry says:
- what was called: the method, the URL, the resource, the operation, the object, the query parameters;
- by whom: the user, the client’s addresses, its user agent, the referrer;
- when it was called, how long it took, and what status it answered;
- for the resources that ask for it, the body of the request.
Coming from Django: Django has no usage log of its own. This is what an audit or request-logging package provides (
django-request,drf-api-tracking’sLoggingMixin), or a middleware written by hand that saves a row per request. Unlike most of them, rind’s plugin never slows a request down: it writes in the background, in batches.
Turning it on
Turn on the usage feature of rind in your Cargo.toml:
rind = { version = "…", features = ["usage"] }
Then install the plugin in app():
#![allow(unused)]
fn main() {
// sample/src/lib.rs
.with(rind::usage::Usage::new().body::<booking_api::reservations::ReservationResource>())
}
The railway logs every call, and keeps the body of the calls to the reservations. The plugin reads no environment variable.
The plugin brings its own table, rind_usage, with its migration. Run
migrate once after installing it:
$ cargo run -p sample -- migrate
From then on, each call adds a row. For example, after a client changed a reservation:
SELECT timestamp, method, url, operation, status, user_id FROM rind_usage ORDER BY id DESC LIMIT 1;
timestamp | method | url | operation | status | user_id
------------------------+--------+----------------------+----------------+--------+---------
2026-11-27 10:00:00+00 | PATCH | /reservations/12 | partial_update | 200 | 3
Choosing what is logged
For each resource, the plugin uses one of four levels:
| Level | What is logged |
|---|---|
NoBody | every call, without its body (the default) |
Body | every call, with its body |
SkipReads | the writes only, not the lists, retrieves and GET actions |
Skip | nothing |
You choose the level in the application, when the plugin is built:
#![allow(unused)]
fn main() {
use rind::usage::{Level, Usage};
Usage::new()
.body::<ReservationResource>() // Body
.skip_reads::<StationResource>() // SkipReads
.skip::<RegionResource>() // Skip
.default_level(Level::NoBody) // the resources that say nothing
}
Or on the resource itself, with options(usage = "…") (see
Plugins). The values are "skip",
"skip_reads", "body" and "no_body":
#![allow(unused)]
fn main() {
#[resource(model = Region, path = "regions", out = RegionOut, /* … */ options(usage = "skip"))]
pub struct RegionResource;
}
When the application and the resource both say something, the application wins.
Bodies, and their secrets
A body is kept without its secrets. The fields named password, token
and secret are removed, at any depth, whatever their case. Add your
own with Usage::secret:
#![allow(unused)]
fn main() {
Usage::new().body::<ReservationResource>().secret("iban")
}
A body larger than 16 KiB is not kept: only its size is, as
{"truncated": 20480}. A body that is not JSON (a form with files) is
not kept either: only its size is, as {"not_json": 104857}.
The client’s address
The address logged is the client’s, as the server sees it. Behind a
proxy, that is the proxy’s address. The real client’s address is then
in the X-Forwarded-For header, which the proxy sets. But any client can
send that header, so the plugin only reads it from peers you trust:
#![allow(unused)]
fn main() {
// from these proxies only:
Usage::new().trusted_proxies(vec!["10.0.0.5".parse().unwrap()])
// from any peer, when every request comes through a proxy that sets it:
Usage::new().behind_proxy()
}
The entry’s ips then lists the addresses of X-Forwarded-For, then
the peer’s.
Written without slowing the requests
A request does not write its own entry. It puts the entry in a channel,
and a task writes the entries in batches: every second, or every 500
entries, whichever comes first. Change both with Usage::batches.
The channel has a bounded size (10,000 entries by default). When it is
full, because the database is slow or down, new entries are dropped and
counted: a request is never slowed by its own log. The plugin logs a
warning under the target rind::usage for the first entry dropped, and
then every 1,000. usage.dropped() gives the count. A batch that cannot
be written is lost, and logged as an error.
usage.flush().await waits until every entry logged so far is written:
use it in a test, or before a process stops. The plugin is a service, so
you find it with ctx.service::<rind::usage::Usage>(), or keep a clone
of it before installing it (its clones share one channel).
Where the entries go
By default, the entries go into the plugin’s own table, rind_usage.
The plugin adds a domain of the same name to the application: its
migration is applied with the application’s, by migrate (see
Migrations).
The table grows forever unless you prune it. The plugin adds a command for that, which deletes the entries older than a number of days (90 by default):
$ cargo run -p sample -- usage-prune --days 90
1234 entries deleted
Run it from a scheduled job or from cron.
A sink of your own
An application that has a usage table already (from a Django application it replaces, for example), or that wants its entries elsewhere, gives a sink of its own: a type that writes a batch of entries.
#![allow(unused)]
fn main() {
use rind::api::BoxFuture;
use rind::db::Db;
use rind::usage::{Entry, Sink, Usage};
struct Logs;
impl Sink for Logs {
fn write<'a>(&'a self, db: &'a Db, entries: &'a [Entry]) -> BoxFuture<'a, Result<(), String>> {
Box::pin(async move { /* insert into logs_usage, or push to Redis */ Ok(()) })
}
}
.with(Usage::new().sink(Logs))
}
With a sink of your own, the plugin’s table is not created, and the
usage-prune command is not added.
What is not logged
The routes that are not resources are not logged: /status, /ready,
/metrics, a plugin’s routes, and routes added by hand.
The usage log is a hook (see Plugins). A hook given before it that answers by itself stops the call before it reaches the usage log: this is what the cache does when it answers from its store. To log the calls the cache answers too, give the usage plugin before the cache.
Reference
Usage:: | Meaning |
|---|---|
new() | every call logged, without its body, into rind_usage |
.level::<R>(level) | what is logged of R |
.body::<R>(), .skip_reads::<R>(), .skip::<R>() | the same, for each level |
.default_level(level) | what is logged of the resources that say nothing (NoBody by default) |
.secret(field) | a field never kept from a body, at any depth |
.trusted_proxies(vec![…]) | X-Forwarded-For is read from these peers only |
.behind_proxy() | X-Forwarded-For is read from any peer |
.batches(batch, interval, capacity) | entries written by batch (500), at least every interval (1 s); past capacity waiting (10,000), they are dropped |
.sink(sink) | writes the entries with sink, not into rind_usage |
.dropped(), .written() | how many entries were dropped, and written |
.flush().await | waits until the entries logged so far are written |
Column of rind_usage | Meaning |
|---|---|
timestamp | when the call started |
method | GET, POST… |
url | the path and its query string |
resource | the resource’s path (stations) |
operation | list, retrieve, create, update, partial_update, destroy, or an action’s name |
object | the object’s id, for a call on one object |
params | the query parameters, as an object of lists |
status | the status answered |
duration | in microseconds |
user_id | the user, when signed in |
ips | the client’s addresses |
user_agent, referrer | the request’s User-Agent and Referer |
data | the body, when the resource’s level is Body |
| Command | Meaning |
|---|---|
usage-prune [--days N] | deletes the entries older than N days (90 by default) |
The rows of rind_usage are the model rind::usage::UsageRow, and the
default sink is rind::usage::TableSink. rind::usage::prune(db, days)
does what the command does.
Most applications send mail: a confirmation after a booking, a sign-in
code, a password reset. The mail plugin sends a message through a
transport (the console, SMTP, Mailgun…), renders it from templates, and
records what became of it: delivered, opened, failed.
Coming from Django: this is
django.core.mail(send_mail,EmailMessage,EMAIL_BACKEND) and, for the delivery events, whatdjango-anymailadds. Django’s console, file-based and in-memory backends are here too, as theConsole,FileandMemorytransports.
Setting it up
Turn on the Cargo feature. mail gives the development transports;
mail-smtp adds SMTP, and mail-mailgun adds Mailgun:
# Cargo.toml of the application
rind = { version = "…", features = ["mail-smtp"] }
Then give the plugin to the application, in app():
#![allow(unused)]
fn main() {
// sample/src/lib.rs
pub fn app() -> rind::Application {
bare_app()
// …
.with(
rind::mail::Mailer::from_env()
.expect("RIND_MAIL_URL")
.from("The railway <noreply@railway.example>")
.templates_dir(concat!(env!("CARGO_MANIFEST_DIR"), "/templates/mail"))
.expect("the mail templates"),
)
}
}
Mailer::from_env() reads three environment variables:
| Variable | What it says |
|---|---|
RIND_MAIL_URL | the transport: console: (the default), smtp://…, mailgun://…… See Choosing a transport |
RIND_MAIL_FROM | the default sender, when the code does not give one with .from(..) |
RIND_MAIL_REDIRECT | an address that receives every message instead of its real recipients: see Sending everything to yourself |
With nothing set, every message is written to the log. This is what you want while you develop: you can read the sign-in codes in the terminal.
Sending a message
A request handler (here, a resource’s saved hook) finds the mailer
among the application’s services, builds a message from a template, and
sends it:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
let Some(mailer) = ctx.service::<rind::mail::Mailer>() else {
return Ok(());
};
let message = mailer
.message(
"reservation_confirmed",
serde_json::json!({ "code": code, "journey": journey, "username": username }),
)?
.to(&email)
.tag("reservation")
.reference(&format!("reservation:{id}"));
mailer.send(&ctx.db, message).await?;
}
mailer.message(name, context) renders the template name with the
values of context, and gives a Message with its subject, its text
and its HTML. You then add the recipients and the rest.
send waits until the transport has taken the message. It takes a Db
because it records the message in the table rind_mail (see
What became of a message).
What a message holds
A Message is built with methods that each add one thing:
.from(..): the sender,"Name <address>"or a bare address. When a message has none, the mailer’s sender is used..to(..),.cc(..),.bcc(..): one recipient per call; call them again for more..reply_to(..),.subject(..),.text(..),.html(..)..attach(name, content_type, bytes): a file joined to the message..header(name, value): a header of your own, such asList-Unsubscribe..tag(..): a tag for the transport’s statistics (Mailgun groups its numbers by tag)..track(true): ask for open and click tracking, when the transport does it..reference(..): your application’s own key for the message, such asreservation:42. Every event about the message gives it back, so you can find which reservation a bounce is about.
You can also build a message without a template:
Message::new().to("bob@example.org").subject("Hello").text("…").
When sending fails
A message without any recipient, or without a sender (neither its own
nor the mailer’s), is refused before it reaches the transport. The
transports that build a MIME message (File, Smtp) also refuse an
address they cannot read. Console and Memory do not check the
addresses, and Mailgun checks them itself.
The error, a MailError, says what to do next:
MailError::Temporary: the transport may take it later. Try again.MailError::Permanent: the transport will not take it.MailError::Invalid: the message itself is wrong (no recipient, a bad address, a template that does not render).
Returned from a handler with ?, a MailError becomes a 500 answer.
Templates
A template is two or three files in the templates folder, which share a name:
templates/mail/reservation_confirmed.subject Your reservation {{ code }}
templates/mail/reservation_confirmed.txt Hello {{ username }}, …
templates/mail/reservation_confirmed.html <p>Hello {{ username }}, …</p>
<name>.subjectis the subject. Only its first line is used, so the newline at the end of the file does not matter.<name>.txtis the text. It is required.<name>.htmlis the HTML version. It is optional: without it, the mail is text only.
The templates use minijinja, which has Jinja2’s syntax, close to
Django’s template language: {{ code }}, {% if %}…{% endif %},
{% for %}, filters. Values are escaped in the HTML file, and not in the
text and the subject.
The folder is read once, when the application starts. You can also give a template in code, which is handy in tests:
#![allow(unused)]
fn main() {
Mailer::from_env()?
.template("welcome", "Welcome, {{ name }}", "Hello {{ name }}!", None)
}
The last argument is the HTML, Some("…"), or None for none.
Templates of a plugin
A plugin that sends mail of its own (rind-auth sends sign-in codes and
password resets) ships default texts. It renders them with
mailer.render_or(name, defaults, context): when the application has a
template of that name, that template is used; otherwise the plugin’s
defaults are. To change the text of a plugin’s mail, put a template of
the same name in your folder. rind-auth’s are named auth_code,
auth_pwreset and auth_activate.
Choosing a transport
A transport is what carries the message. RIND_MAIL_URL picks it:
RIND_MAIL_URL | Transport | What it does |
|---|---|---|
console: (the default) | Console | writes each message to the log (target rind::mail), body included. For development only |
file:///var/mail/out | File | writes each message as an .eml file in the folder, which is created if needed |
memory: | Memory | keeps the messages in memory |
smtp://user:pass@host:587?tls=required | Smtp (feature mail-smtp) | sends through an SMTP server, with STARTTLS |
smtps://user:pass@host:465 | Smtp | the same, with TLS from the start |
smtp://host:25 | Smtp | no TLS: for a relay on the same machine |
mailgun://<api key>@<domain>?region=eu&webhook_key=… | Mailgun (feature mail-mailgun) | sends through Mailgun’s API, with tags, tracking, and its events |
A URL that needs a feature rind was built without is refused when the application starts, with a message that names the feature.
SMTP keeps a pool of connections. The password is not written to the logs. The error of a refused message says whether it is temporary or permanent, as the server’s answer does.
Mailgun sends each message to its API with its tags, its tracking
choice, and its reference (as the variable rind-reference, which
Mailgun gives back in every event). region=eu uses Mailgun’s European
servers. webhook_key is the webhook signing key: without it, the
events are refused. See Delivery events.
Testing with the Memory transport
In a test, give the mailer a Memory transport that you keep a handle
on, and read its outbox, as Django’s mail.outbox:
#![allow(unused)]
fn main() {
// sample/tests/mail.rs
let memory = rind::mail::Memory::new();
let app = sample::bare_app().with(
Mailer::new(memory.clone())
.from("The railway <noreply@railway.example>")
.templates_dir(TEMPLATES)
.unwrap(),
);
// … a request that sends mail …
assert_eq!(memory.outbox()[0].to, ["bob@railway.example"]);
}
memory.clear() empties the outbox. (RIND_MAIL_URL=memory: also
works, but the code then has no handle to read the outbox with.)
A transport of your own
A transport is one impl rind::mail::Transport, given to
Mailer::new(transport). It has a name and a send, and two optional
methods:
check, which/readycalls to see whether the transport answers;webhook, for a transport whose service posts events back.
A relay that your company already runs, or a provider rind does not know, is one of those.
Sending everything to yourself
On a staging server, you want real mail, but not to real people. Set
RIND_MAIL_REDIRECT=dev@example.org (or call .redirect(..) on the
mailer): every message then goes to that address only. The real
recipients are written at the start of the subject, [bob@example.org] Your reservation…, and in the header X-Rind-Original-To. Do not set
it in production.
What became of a message
Every message sent is a row of the table rind_mail, which the plugin
creates with its own migrations. The row has:
- the transport’s id for the message, and your reference;
- the sender, the recipients, the subject and the tags;
- its last status, when it changed, and a detail (an error, a link);
- the times it was delivered, opened and clicked.
The bodies are not kept, because they can hold sign-in codes.
mail-prune --days 90 deletes the rows older than that many days (90
when not given). Run it from a scheduled job or a cron.
If your application keeps its own record of what it sent (a
notification table, say), give the mailer a sink: .sink(MySink),
where MySink implements rind::mail::Sink (sent and event). The
table rind_mail is then not created. .no_log() records nothing at
all.
/ready asks the transport whether it answers: the SMTP server
answers, Mailgun knows the domain, the folder exists
(Health).
Delivery events
A transport like Mailgun tells you later what happened to a message. It
posts these events to a webhook of the mailer, at
/mail/events/<transport>: POST /mail/events/mailgun for Mailgun.
Give that address to Mailgun for the events you want: delivered,
opened, clicked, failed, complained, unsubscribed. (.events_path(..)
changes the /mail/events part.)
Each request is checked against the webhook signing key (an HMAC of its timestamp and token). A request whose signature does not match, or that is older than 15 minutes, is refused with a 406, which tells Mailgun not to retry it.
Each event changes the status of the message’s row:
| Mailgun’s event | Status |
|---|---|
| accepted | accepted |
| failed, temporary | deferred |
| delivered | delivered (and delivered_at) |
| opened | opened (and opened_at) |
| clicked | clicked (and clicked_at; the link is in detail) |
| failed, permanent; rejected | failed (the reason is in detail) |
| complained, unsubscribed | complained, unsubscribed |
Events can arrive out of order, so a status never goes back: a
delivered that arrives after opened leaves the row at opened. The
times (delivered_at…) are always recorded.
Sending after the write commits
mailer.send sends at once, inside the request. Two things can go
wrong with that. The request’s write may still fail after the mail went
out, and the client gets a confirmation for a booking that does not
exist. And a slow or broken mail server makes the request slow or broken.
With the jobs plugin, mailer.queue(ctx, message) queues
the message instead. The queued job is written in the request’s
transaction: a worker sends it only once the write has committed, and
tries again, up to three times, when the transport fails. The railway
confirms its reservations this way when it has the jobs plugin:
#![allow(unused)]
fn main() {
// sample/crates/booking/booking-api/src/reservations/views.rs
match ctx.service::<rind::jobs::Jobs>() {
Some(_) => {
mailer.queue(ctx, message).await?;
}
None => {
mailer.send(&ctx.db, message).await?;
}
}
}
The jobs plugin must know the job that sends mail: give it with
Jobs::new().mail(). Without the jobs plugin, queue returns an error.
Note: a queued message is kept whole, body included, in the jobs’ table
rind_job_rununtiljobs-prunedeletes it.
Not planned
Open and click tracking for SMTP (a tracking pixel, links through a redirect). Use Mailgun for that.
Reference
Mailer
| Method | What it does |
|---|---|
Mailer::from_env() | the transport of RIND_MAIL_URL, with RIND_MAIL_FROM and RIND_MAIL_REDIRECT |
Mailer::new(transport), Mailer::shared(Arc<dyn Transport>) | a mailer on a transport of your choice |
.from(sender) | the default sender |
.redirect(address) | every message to this address instead |
.templates_dir(folder) | every .subject, .txt and .html file of the folder; a template of the same name given before is replaced |
.template(name, subject, text, html) | one template, in code |
.sink(sink) | records into sink instead of rind_mail (which is then not created) |
.no_log() | records nothing |
.events_path(path) | where the webhooks are, /mail/events by default |
message(name, context) | a Message from a template |
render(name, context), render_or(name, defaults, context) | the subject, text and HTML of a template, as a Rendered |
has_template(name) | does the application have this template (its .txt)? |
send(db, message) | sends and records; gives a Sent with the transport’s id |
queue(ctx, message) | queues it with the jobs plugin; gives the run’s id |
What the plugin adds
| Table | rind_mail (domain rind_mail), unless .sink(..) or .no_log() |
| Command | mail-prune [--days n] |
| Route | POST /mail/events/<transport>, for a transport with a webhook |
| Health check | mail, in /ready |
| Service | the Mailer, for ctx.service::<Mailer>() |
| Job | rind.mail (SendMail), registered by Jobs::mail() |
Jobs
Some work does not belong in a request: an import every night, a sync
with another system, statistics, mail in bulk, a long export a user asked
for. The jobs plugin runs that work outside requests, either on a
schedule or when a request asks for it. It needs nothing but PostgreSQL:
the queue is a table, and the workers are your application’s own binary.
Coming from Django: this is what Celery (with Celery beat for the schedules) or django-q do. There is no broker to run: no Redis, no RabbitMQ. A job is queued in the same database transaction as the request’s write, so a job never runs for a write that was rolled back.
Setting it up
Turn on the Cargo feature jobs:
# Cargo.toml of the application
rind = { version = "…", features = ["jobs"] }
Then give the plugin to the application, with its jobs and their schedules. The railway marks its journeys arrived every minute, and sends its mail through the queue:
#![allow(unused)]
fn main() {
// sample/src/jobs.rs
pub fn jobs() -> rind::jobs::Jobs {
rind::jobs::Jobs::new()
// Queued mail (`Mailer::queue`): a reservation's confirmation.
.mail()
.every("* * * * *", MarkArrived)
.expect("a schedule")
.timezone("Europe/Paris")
.expect("a time zone")
}
// sample/src/lib.rs, in app()
.with(jobs::jobs())
}
The plugin needs no environment variable. Its tables, rind_job_run
and rind_job_state, come with its migrations.
Then start a worker, a second process beside the server:
cargo run -p sample -- jobs-work --concurrency 4
Writing a job
A job is a Rust value that implements Job. The value holds the job’s
arguments: it is stored as JSON in the queue, so it derives Serialize
and Deserialize. Its run method does the work.
#![allow(unused)]
fn main() {
// sample/src/jobs.rs
use rind::jobs::{Interrupt, Job, JobCtx, JobError};
use serde::{Deserialize, Serialize};
/// Journeys whose arrival time has passed are `arrived`: every minute.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct MarkArrived;
impl Job for MarkArrived {
const NAME: &'static str = "timetable.mark_arrived";
/// Two at once would only do the same work twice.
const EXCLUSIVE: bool = true;
const INTERRUPT: Interrupt = Interrupt::Safe;
async fn run(self, ctx: &JobCtx) -> Result<(), JobError> {
let changed = ctx
.db
.execute_sql(
"UPDATE timetable_journey SET status = 'arrived' \
WHERE status IN ('planned', 'running') AND arrives_at < now()",
&[],
)
.await?;
ctx.db.wrote("timetable_journey");
// How many runs found nothing to do: a state kept across runs.
let idle: u64 = ctx.state().await?.unwrap_or(0);
ctx.set_state(&if changed == 0 { idle + 1 } else { 0 })
.await?;
ctx.note(format!("{changed} journeys arrived"));
Ok(())
}
}
}
NAME is the job’s name in the queue, in the log and on the command
line. The other constants are optional; they say how the job runs:
EXCLUSIVE(falseby default): only one run of the job at a time, across every worker. Use it for a job that two runs at once would only repeat, or would get wrong.TIMEOUT(an hour by default): a run that takes longer is stopped and marked failed.RETRIES(0by default): how many times a failed run is tried again. The next attempts wait 1 minute, then 5, then 30.INTERRUPT(Safeby default): what a worker that stops does with a run in progress. See Stopping a worker.
A JobError is a message. Any error type converts into one, so ?
works on database errors and the like.
What a job is given
JobCtx is to a job what Ctx is to a request:
ctx.db, the database;ctx.service::<T>(), the application’s services, as a request has them (ctx.service::<Mailer>());ctx.note(..), a line for the run’s log, kept with the run;ctx.state::<T>()andctx.set_state(&value), a value kept from one run to the next (in the tablerind_job_state): the last id an import read, the time of the last sync;ctx.run, the run’s id, andctx.attempt, its attempt number, starting at 1.
Running a job on a schedule
.every(pattern, job) runs job on a cron schedule of five fields
(minute, hour, day of the month, month, day of the week). It also
registers the job:
#![allow(unused)]
fn main() {
Jobs::new()
.every("* * * * *", MarkArrived)? // every minute
.every("7 7,13,20 * * *", Sync { full: false })? // at 7:07, 13:07, 20:07
.timezone("Europe/Paris")?
}
The schedules follow the time zone given by .timezone(..) (UTC by
default), across daylight saving changes.
Each scheduled time gives exactly one run, even with several workers.
When no worker was running at a scheduled time (during a deployment,
say), the run is queued once, late, when a worker comes back. With
.catch_up(false), such a missed time is skipped instead.
Coming from Django: this replaces Celery beat’s
CELERY_BEAT_SCHEDULE. There is no separate beat process: the workers take turns to queue the scheduled runs.
Queuing a job from a request
A request can ask for work to be done later. Register the job with
.job::<J>(), then queue it:
#![allow(unused)]
fn main() {
// in app()
.with(rind::jobs::Jobs::new().job::<RenderLayout>())
// in a hook or an action
let jobs = ctx.service::<rind::jobs::Jobs>().unwrap();
let run = jobs.queue(&ctx.db, RenderLayout { id }).await?;
}
queue gives the run’s id. A job the plugin does not know (one never
given to .job::<J>() or .every(..)) is refused with an error.
The run is written through ctx.db, so it is part of the request’s
transaction. A write that is rolled back takes its job with it, and a
worker never sees a run before the request has committed.
jobs.state_of(db, run) says where a run is: queued, running,
done, failed or skipped. A front end can poll it to wait for the
work it asked for.
jobs.queue_at(db, job, when, priority) queues a run for a later time,
with a priority: a higher priority runs first.
To send mail after the write commits, use mailer.queue(ctx, message):
a worker sends it, and tries again three times if the transport fails
(Mail). It needs .mail() on the plugin.
Workers
A worker is your application started with the command jobs-work:
cargo run -p sample -- jobs-work --concurrency 4
It runs up to --concurrency runs at once (4 by default). Start as many
workers as you like, on as many machines: they share the queue safely.
--only a,b limits a worker to the jobs named, so that a heavy job can
have workers of its own.
How a worker takes a run
A worker takes the next run that is due, with the highest priority
first, then the oldest. It uses FOR UPDATE SKIP LOCKED, so two workers
never take the same run. It holds the run under a lease (an hour), and
writes how the run went when it ends.
A worker that dies (killed, out of memory) leaves its runs running.
When their lease ends, another worker takes them again.
Every 20 seconds, one worker at a time queues the scheduled runs that are
due. Each idle worker looks for work every second (.poll(..) changes
that).
Stopping a worker
On SIGTERM or Ctrl-C, a worker stops taking runs. What it does with the
runs in progress depends on each job’s INTERRUPT:
Interrupt::Safe: the run is stopped at once and queued again. A worker started later runs it from the start.Interrupt::AvoidandInterrupt::Never: the worker waits for the run to end, within its grace period (a minute;.grace(..)changes it). A run that is still going when the grace ends is queued again.
Set your orchestrator’s stop timeout (Kubernetes’
terminationGracePeriodSeconds) a little longer than the grace.
The log of the runs
The table rind_job_run is both the queue and the log: one row per run,
with its job, its arguments, its state (queued, running, done,
failed, skipped), its attempt, the worker that ran it, its times, its
error and its notes.
A run is skipped when it was scheduled while another run of the same
exclusive job was still going. A run queued by a request in the same
situation waits and is tried again later.
The plugin adds commands to read and drive it:
cargo run -p sample -- jobs-list # each job, its schedules, its usual times
cargo run -p sample -- jobs-runs --failed # the last failed runs
cargo run -p sample -- jobs-run timetable.mark_arrived null # run it now, here
jobs-run runs a job at once, in the process you started, and prints
how it went. It is for a person at a terminal, or for a Kubernetes
CronJob if you prefer those to a worker’s schedules. The run is recorded
in the log like the others.
/ready tells how many runs are due and the age of the oldest
(Health): a number that keeps growing means the workers are
not keeping up, or are not running.
Testing jobs
In a test, there is no worker. jobs.run_pending(&db, &services) runs
every run that is due, here, one after the other, and gives what each
came to. jobs.schedule(&db) queues what the schedules say is due.
#![allow(unused)]
fn main() {
// sample/tests/jobs.rs
let jobs = state.services.get::<Jobs>().unwrap().clone();
// … a request that queues a mail …
let ran = jobs.run_pending(&db, &state.services).await.unwrap();
assert_eq!(ran, [("rind.mail".to_owned(), Outcome::Done)]);
}
Reference
The constants of Job
| Constant | Default | Meaning |
|---|---|---|
NAME | (required) | its name in the queue and the log |
EXCLUSIVE | false | one run at a time across every worker (a PostgreSQL advisory lock, per schema) |
TIMEOUT | an hour | a run past it fails, and is not retried |
RETRIES | 0 | runs again after a failure, after 1, 5, then 30 minutes |
INTERRUPT | Safe | Safe: stopped and queued again when a worker stops; Avoid, Never: waited for, within the grace |
Jobs
| Method | What it does |
|---|---|
Jobs::new() | the plugin, without jobs |
.job::<J>() | a job the workers run, and that requests may queue |
.mail() | the job that sends the mail Mailer::queue queues |
.every(pattern, job) | job on a cron schedule of five fields; registers the job |
.timezone(name) | the schedules’ time zone, UTC by default |
.catch_up(false) | a scheduled time missed while no worker ran is skipped, not run late |
.poll(duration) | how often an idle worker looks for a run (1 s) |
.grace(duration) | how long a stopping worker waits for runs it should not interrupt (60 s) |
queue(db, job), queue_at(db, job, when, priority) | queues a run; gives its id |
state_of(db, run) | the state of a run |
run_pending(db, services) | runs what is due, here (for tests) |
schedule(db) | queues the scheduled runs that are due (for tests) |
work(db, services, concurrency, only), work_until(…, stop) | a worker, in your own process |
Commands
| Command | What it does |
|---|---|
jobs-work [--concurrency n] [--only a,b] | a worker, until SIGTERM or Ctrl-C |
jobs-run <name> [json] | runs one now, in this process, and prints how it went |
jobs-queue <name> [json] | queues one |
jobs-list | each job, its schedules, how many runs are done, their median and longest times, the last |
jobs-runs [--failed] [--name n] [--limit n] | the last runs (30 by default) |
jobs-prune [--days n] | deletes the finished runs older than that (90 days by default) |
The json of jobs-run and jobs-queue is the job’s arguments. When it
is left out, {} is used: a job that is a unit struct, such as
MarkArrived, needs null instead.
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.
Images
An image is a file with a little more: its width and height
are known, it is often shown at several sizes (a thumbnail, a cover),
and it often has a row of its own (a title, credits) linked to the
objects it illustrates. The images feature covers these three needs:
- its size, read on upload: the behaviour
Image(orDimensions) reads the width and height of each image sent and writes them in their columns; - galleries and logos: the behaviours
ImagesandLogogive a resource the actions that add, change and remove its images; - resized copies:
Sizes, on the storage, answers…/logo--cover_256.webpfrom…/logo.png, made the first time it is asked for.
Coming from Django: the first is
ImageFieldwithwidth_fieldandheight_field. The resized copies are whateasy-thumbnailsorsorl-thumbnaildo, except that the size is asked for in the URL rather than in a template tag.
A behaviour is a piece of a resource that several resources share (columns, what a write sets, actions). It is explained in Behaviours.
Setting it up
Turn on the Cargo feature images. It brings in storage and
behaviours, the image crate and libwebp:
# Cargo.toml of the application
rind = { version = "…", features = ["images"] }
The images are stored by the storage plugin, so the application needs
one (Files). For resized copies, give it Sizes:
#![allow(unused)]
fn main() {
// sample/src/lib.rs
.with(
rind::storage::Storage::from_env()
.expect("RIND_STORAGE")
.sizes(rind::images::Sizes::new()),
)
}
There is no environment variable of its own.
Reading an image’s size on upload
The simplest case is an image column on a model, with its width and
height beside it. The field group rind::images::image gives the three
columns (image, image_width, image_height), and the behaviour
Image fills the last two:
#![allow(unused)]
fn main() {
use rind::images::Image;
#[rind::with_fields(rind::images::image)] // image, image_width, image_height
#[derive(Debug, Clone, Model)]
#[model(table = "shop_product")]
pub struct Product { /* … */ }
#[derive(Resource)]
#[resource(model = Product, /* … */ behaviours(Image))]
pub struct ProductResource;
}
On every write that sends the file, Image reads the width and height
from it and sets them. A write that removes the file empties them. This
is what Django’s ImageField does with width_field and
height_field.
A file that is not a JPEG, PNG, GIF or WebP image is refused with a 400, and Django’s message:
{"image": ["Upload a valid image. The file you uploaded was either not an image or a corrupted image."]}
Some details:
- The type is read from the file’s content, not from its name. A JPEG
named
.pngis read as a JPEG. - The size is the one stored in the file, before any EXIF orientation is applied. This is what PIL reads, so it matches what Django recorded.
- The file is read from the request, not again from the storage. When a client sends the key of a file already stored (instead of a file), it is read from the storage; a key that is not there is refused with “This file is not in the storage.”
Columns of other names
When the columns have other names, or when you also want the image’s
type, name them with a Picture and use Dimensions<P>. The railway’s
images do this:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/images.rs
use rind::images::{Dimensions, Picture};
/// The columns `Dimensions` reads and writes.
pub struct ImageFile;
impl Picture for ImageFile {
const FILE: &'static str = "file";
const WIDTH: &'static str = "width";
const HEIGHT: &'static str = "height";
const TYPE: &'static str = "mimetype"; // optional: `image/png`
}
#[derive(Resource)]
#[resource(model = Image, path = "images", out = ImageOut, input = ImageIn, delete,
behaviours(Dimensions<ImageFile>))]
// …
pub struct ImageResource;
}
TYPE is optional; leave it out when the model does not keep the type.
(Image is simply Dimensions on the columns of the field group.)
rind::images::probe(&bytes) gives the width, height and type of an
image, or None, for code of your own.
Galleries and logos: images with a row of their own
Often an image is more than a column. It has a row of its own, with a
title, credits, an order, and objects point to it. In the railway, the
images are rows of network_image. A line has a logo (a foreign key to
an image) and a gallery (a many-to-many to images):
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
#[m2m(name = images, model = Image, through = "network_line_images", from = "line_id", to = "image_id")]
pub struct Line {
// …
#[fk(Image, on_delete = set_null, name = logo)]
pub logo_id: Option<i64>,
}
}
The images are a resource of their own (ImageResource, above). Two
behaviours then give the lines’ resource the actions that change its
images. Each is configured by a small type that says which tables and
columns to use:
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/lines.rs
use rind::images::{Gallery, Images, Logo, LogoField};
/// A line's gallery: `network_line_images`.
pub struct LineImages;
impl Gallery for LineImages {
type Images = ImageResource; // what makes and deletes an image
type Changes = ImageChanges; // what update_image reads
const LINK: &'static str = "network_line_images";
const FROM: &'static str = "line_id";
const TO: &'static str = "image_id";
}
/// A line's logo: `logo_id`.
pub struct LineLogo;
impl LogoField for LineLogo {
type Images = ImageResource;
type Changes = ImageChanges;
const COLUMN: &'static str = "logo_id";
}
#[derive(Resource)]
#[resource(
model = Line,
path = "lines",
out = LineOut,
input = LineIn,
delete,
behaviours(Flags, Images<LineImages>, Logo<LineLogo>)
)]
#[rule(superuser)]
#[rule(staff)]
#[rule(anyone, actions(list, retrieve, get_flags, get_image, get_logo))]
pub struct LineResource;
}
The resource now has these actions on each line (/lines/{id}/…):
| Action | Method | Body | What it does |
|---|---|---|---|
add_image | POST | the images’ input: a form with the file, or JSON | creates an image and adds it to the gallery; 201 |
update_image | PATCH | id, and what changes (Changes) | changes an image of the gallery |
remove_image | POST | pk | takes it out of the gallery and deletes it |
get_image | GET | ?image=<id> | answers the image |
set_logo | POST | the images’ input | creates an image and makes it the logo; 201 |
update_logo | PATCH | what changes (Changes) | changes the logo |
unset_logo | POST | the line has no logo any more; the image is kept | |
get_logo | GET | answers the logo |
They answer with the line, except the get_ actions, which answer with
the image. An image that is not in the gallery (or a line without a
logo) is a 404, {"detail": "Image not found"}. The rules name the
actions as they name any other: above, anyone may read the images and
only the staff may change them.
Sending a logo in a form:
POST /lines/7/set_logo
Content-Type: multipart/form-data; boundary=…
title=Le logo, file=logo.png (image/png, 400 × 200)
{"id": 7, "code": "IMG", "logo": 12, "images": [], "updated": "…", …}
GET /lines/7/get_logo
{"id": 12, "file": {"url": "/media/images/2c/03a1…/logo.png", "name": "logo.png", "size": …},
"width": 400, "height": 200, "mimetype": "image/png", "title": "Le logo", "credits": ""}
Coming from Django: a real Django application had these as view mixins (
ManageImagesAPIViewMixin,ManageLogoAPIViewMixin). The actions keep their names, methods and answers, so a front end written for it works unchanged.
How an image is created and changed
An image is created and changed by its own resource (Images), in the
action’s transaction. So its input says what a client sends (the file,
a title), its behaviours run (its Dimensions reads the size), and its
hooks run too. Its own rules are not asked: who may change the line may
change its images.
Changes is the input that update_image and update_logo read.
It usually has fewer fields than the input that creates an image: the
railway’s ImageChanges changes a title and credits, not the file. Or
it can be the images’ input itself. A field it does not have is ignored.
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/images.rs
#[derive(Debug, Input)]
#[input(model = Image)]
pub struct ImageChanges {
#[input(max_length = 200, allow_blank)]
pub title: Option<String>,
#[input(max_length = 500, allow_blank)]
pub credits: Option<String>,
}
}
Removing an image
remove_image deletes the image. What happens to the rows that still
point to it is what their foreign keys say. In the railway, a line whose
logo it was has no logo any more (on_delete = set_null). With keys that
do nothing (as Django creates them), the deletion is refused with a 400.
unset_logo only clears the line’s key: the image is kept. set_logo
on a line that already has a logo makes the new image the logo, and
keeps the old image too.
Going further: which hooks run
- An image change (
update_image,update_logo): the model’s behaviours, the images’ resource’s behaviours (itsDimensions) and the model’s hooks run. The images’ resource’s ownupdatingandsavedhooks do not run, because they take the images’ input, notChanges. - The logo is a write of the line:
set_logoandunset_logochange the line’s key through the model’s behaviours, as Django’sitem.save()would (soTrackingmovesupdated), and the model’s hooks are told. The line resource’s own hooks do not run, because they take its input.
Resized copies
A page shows an image at several sizes: a 48-pixel thumbnail in a list,
a 512-pixel cover on the detail page. Sending the original each time is
slow, and making every size on upload means guessing them in advance.
With Sizes, the storage makes a copy the first time it is asked for,
by its name:
#![allow(unused)]
fn main() {
rind::storage::Storage::from_env()?
.sizes(rind::images::Sizes::new())
}
The storage then answers, at its address (/media), resized copies of
its images. The name of a copy is the image’s name, then -- and an
operation, then the type wanted:
/media/images/2c/03a1…/logo.png the image
/media/images/2c/03a1…/logo--cover_256.webp cut to fill 256 × 256
/media/images/2c/03a1…/logo--contain_354_236_white.jpg fitted in 354 × 236, on white
/media/images/2c/03a1…/logo--resize_767.webp 767 wide
There are three operations:
resize_<w>[_<h>]scales the image to fit inw×h. With one side (resize_767), that side is exact and the other follows.contain_<w>[_<h>[_<color>]]fits the image, centred on aw×hbackground:transparentby default, orwhite,black,ff8800….cover_<w>[_<h>]fillsw×h; what overflows is cut, centred.
Several operations can follow each other: logo--cover_512--resize_256.webp.
The type is webp, png or jpg, whatever the original’s. A copy is
turned the way the camera said it was held (EXIF).
A front end builds a copy’s address from the file’s url: drop the
type, add the operation and the new type. Angular’s image loader, for
instance, does this with a small function. These names are those of the
image server a real Django application used: a front end written for it
works unchanged.
A name that is not a copy, a size that is not allowed, or an operation rind does not know is a 404.
Where the copies are kept
A copy is made the first time it is asked for, on a thread of its own,
and then stored: below _sizes/ in the same storage, or in another
storage with Sizes::new().copies(storage) (when the images’ storage is
read-only, for example). A key’s content never changes, so a copy’s does
not either: it is sent with a cache of a year. storage-orphans leaves
the copies out.
Limits
Without limits, anyone could fill the storage with every possible size.
So a side is at most Sizes::max (2,048 pixels by default), and
Sizes::only(&[48, 256, 512]) allows only these sides.
A file that claims a picture larger than 20,000 pixels a side, or that
needs more than 512 MiB to decode, is not read. WebP and JPEG copies are
written at quality 70 (.quality(q) changes it).
Serving the copies
The copies are answered by the application, on the path the storage
serves (.serve("/media"), or the default for a folder without
RIND_MEDIA_URL).
- Behind a CDN that resizes images itself, or an image server, give the
storage its public address (
RIND_MEDIA_URL) and leavesizesout. - A private S3 bucket gives signed addresses, which a client cannot
change to ask for a copy. To have copies of such a bucket’s images,
serve the bucket through the application (
.serve("/media")).
Reference
Behaviours
| Behaviour | Configured by | Columns | What it does |
|---|---|---|---|
Image | (the field group rind::images::image) | image, image_width, image_height | reads the size on upload |
Dimensions<P> | Picture: FILE, WIDTH, HEIGHT, TYPE (optional) | those named | reads the size, and the type, on upload |
Images<G> | Gallery: Images, Changes, LINK, FROM, TO | (a link table) | add_image, update_image, remove_image, get_image |
Logo<L> | LogoField: Images, Changes, COLUMN | the foreign key | set_logo, update_logo, unset_logo, get_logo |
update_image reads the image’s id from id (or pk), and
remove_image from pk (or id).
Copy names
| Operation | Aliases | |
|---|---|---|
resize_<w>[_<h>] | size, sz, s, scale, sc | scaled to fit in w × h; with one side (the other missing or 0), that side exact, the other following |
contain_<w>[_<h>[_<color>]] | ct | fitted, centred on a w × h background; h is w by default, w is 128 by default |
cover_<w>[_<h>] | co | fills w × h, the overflow cut, centred; h is w by default |
Colours: transparent (or tr), white, black, red, green,
blue, gray (or grey), or hexadecimal digits (f80, ff8800,
ff880080 with transparency). Types: webp, png, jpg or jpeg.
Sizes
| Method | Default | |
|---|---|---|
Sizes::new() | copies on request | |
.max(pixels) | 2,048 | the largest side |
.only(&[sides]) | any | only these sides |
.quality(q) | 70 | WebP and JPEG quality, 0 to 100 |
.copies(storage) | _sizes/ in the images’ storage | where the copies are kept |
Tested against a real application
These measures come from a real Django application with 337,518 images (72 GB, nearly all PNG). rind read every image that was not a PNG, and one PNG in twenty: 24,250 files, 11 GB, in 20 seconds.
- Their size: of the 24,049 files rind read, Django had recorded a
width and height for 7,186, and none was different. The other 16,863
had none in the database. 4 files were not read: two BMPs, a Photoshop
file named
.jpg(which PIL reads), and an HTML page. - Their type, read from the content: 713 images recorded as
image/pngwere JPEGs. - The copies its front end asks for (
contain_512,contain_256andcontain_48in WebP,contain_354_236_white,resize_767,resize_354in the image’s own type), for 40 PNGs and 40 JPEGs: all 480 had the size asked for. Each was made in 0.2 to 0.4 s, mostly to decode the original, then answered in 0.1 ms once stored.
Behaviours
Several models of an application often need the same thing: a
created and an updated date, a list of flags, a description in
markdown with its HTML. In Django you write that once, as an abstract
model (the columns and a save() override) and a view mixin (the
filters and the extra routes), and every model and viewset that needs it
inherits from them.
In rind, that shared piece is a behaviour. A behaviour is a type that you list on a model or on a resource, and that adds to it:
- what its writes set (
updatedon every change, the HTML from the markdown); - for a resource, filters of its own (
?flags=fast) and actions of its own (add_flag,get_flags).
Its columns come separately, from a field group that you add to the
model. The feature is behaviours (and markdown for Content).
Coming from Django: a behaviour does what an abstract model and its view mixin did together. It also does what you may have done with a
pre_savesignal: set a column of the row being written.
Why behaviours, and not signals
A Django signal is a function registered somewhere, that runs when a
model is saved. It is easy to add, and hard to follow: when you read the
model, nothing tells you that a signal will change the row, or in which
order the receivers run. A behaviour is listed on the model or the
resource itself, behaviours(Tracking, Content), so you see everything
that a write will do where the model is declared. They run in the order
listed, and the compiler checks that the model has the columns each one
needs.
A behaviour only changes the row being written. What must happen elsewhere when a row is written (other rows, other tables) is a model hook (The model’s hooks) or a resource’s hook (Inputs). Those are also declared on the model or the resource, by name.
A first example
The railway’s lines have the three behaviours that rind gives: when they
were created and changed (Tracking), flags (Flags), and a description
in markdown (Content):
#![allow(unused)]
fn main() {
// sample/crates/network/network-models/src/lib.rs
#[rind::with_fields(
rind::behaviours::tracking,
rind::behaviours::flags,
rind::behaviours::content
)]
#[derive(Debug, Clone, Model)]
// When a line was created and changed, and its description in HTML, are
// the model's: every write sets them, the API's and the code's
// (`line.save(&db)`).
#[model(
table = "network_line",
behaviours(rind::behaviours::Tracking, rind::behaviours::Content)
)]
#[index(name = "network_line_flags_idx", sql = "USING gin (flags)")]
pub struct Line {
pub id: i64,
#[column(max_length = 10, unique)]
pub code: String,
#[column(max_length = 200)]
pub name: String,
// …
}
}
#![allow(unused)]
fn main() {
// sample/crates/network/network-api/src/lines.rs
#[derive(Resource)]
#[resource(
model = Line,
path = "lines",
out = LineOut,
input = LineIn,
delete,
// `Tracking` and `Content` are the model's: they run on every write.
behaviours(Flags, Images<LineImages>, Logo<LineLogo>)
)]
#[rule(superuser)]
#[rule(staff)]
#[rule(anyone, actions(list, retrieve, get_flags, get_image, get_logo))]
pub struct LineResource;
}
There are three parts:
- The columns come from the field groups in
#[rind::with_fields(..)]:trackinggivescreatedandupdated,flagsgivesflags,contentgivescontent_srcandcontent_html(Groups of fields). - The model’s behaviours, in
#[model(behaviours(..))], run on every write of the model, whether it comes from the API or from code (line.save(&db)). - The resource’s behaviours, in
#[resource(behaviours(..))], run on the resource’s writes, and add its filters and actions. A behaviour that needs the request, or adds routes (Flags,Images), can only be the resource’s.
What it does:
POST /lines
{"code": "L1", "name": "Atlantique", "content_src": "From *Paris*"}
{"id": 3, "code": "L1", "name": "Atlantique", "flags": [],
"content_src": "From *Paris*", "content_html": "<p>From <em>Paris</em></p>\n",
"created": "2026-11-27T09:12:03Z", "updated": "2026-11-27T09:12:03Z"}
A later PATCH moves updated and leaves created. A PATCH that
changes content_src writes content_html again; one that does not
change it leaves it.
The compiler checks the columns
A behaviour lists the columns it needs. A resource or a model whose model lacks one does not compile:
error[E0080]: the behaviour `Flags` needs columns the model does not have
Behaviours take types
behaviours(..) takes types, so a behaviour can be generic, configured
by another type: Compiled<Pandoc>, Images<LineImages>.
The behaviours rind gives
Tracking: when an object was created and changed
Tracking sets created and updated to now on a creation, and
updated to now on every change. The columns come from the field group
rind::behaviours::tracking.
Put it on the model, as the railway does, so that writes from code set
the dates too. On the model, a creation always sets both dates, whatever
the object held, as Django’s auto_now_add and auto_now do. The
model’s raw writes (insert_raw, save_raw, update_raw) do not run
it, for an import that keeps its own dates.
On a resource only, Tracking sets created and updated on a
creation unless the write already sets them.
Flags: labels added and removed one by one
Flags are short strings an object carries (night, fast), in a column
flags (a varchar[], from the field group rind::behaviours::flags).
Flags, on a resource, gives it a filter and three actions.
The filter: ?flags=a,b keeps the objects that have every one of
these flags.
GET /lines?flags=fast,night
On a large table, put a GIN index on flags for this filter, as the
railway does: #[index(name = "…_flags_idx", sql = "USING gin (flags)")].
add_flag and remove_flag (POST /lines/{id}/add_flag) take
one flag or several:
POST /lines/3/add_flag
{"flags": ["night", "fast"]}
{"flags": ["night", "fast"]}
add_flagputs the flags sent at the end, only those the object does not have yet, and once each. So the flags keep the order they were added in.remove_flagtakes them out, and leaves the others where they were. Removing a flag the object does not have is not an error.- Both answer with the object’s flags.
- A body with neither
flag(a string) norflags(a list of strings) is a 400. So is a flag that is empty or longer than 30 characters.
get_flags (GET /lines/get_flags) counts how many objects have
each flag, the most frequent first, then by name:
[{"flag": "fast", "count": 12}, {"flag": "night", "count": 3}]
It counts only the objects the request may see (the query of the
request’s mode). The cache keeps its
answer, and add_flag and remove_flag make it stale, since they write
the table.
Coming from Django: this is what a
FlagsAPIViewMixindid in a real Django application, with the same action names and answers. Two things differ: removing a missing flag was a 500 there, andget_flagscounted the whole table, whoever asked.
Compiled and Content: a column computed from another
Compiled<C> writes a column computed from another one, on every write
that sets the source. A write that sets the source to null empties the
target. A write that does not touch the source leaves the target alone.
Content is Compiled with markdown: it renders content_src into
content_html (the field group rind::behaviours::content, the feature
markdown). The railway puts it on the model.
The markdown is rendered with comrak: CommonMark, with GitHub’s tables,
strikethrough, autolinks and footnotes, and typographic quotes, dashes
and ellipses, as pandoc writes them (' becomes ’, -- becomes –).
Raw HTML in the source is not kept, so a <script> in a description is
not sent to browsers. rind::behaviours::Markdown::html(source) renders
a text the same way, for code of your own.
Going further: a rendering of your own
An application that needs another rendering (pandoc itself, shortcuts of
its own) writes its own Compile, and uses Compiled<…> with it:
#![allow(unused)]
fn main() {
use rind::behaviours::{Compile, Compiled};
pub struct Pandoc;
impl Compile for Pandoc {
const SOURCE: &'static str = "content_src";
const TARGET: &'static str = "content_html";
fn compile(source: &str) -> String {
run_pandoc(source) // your own function
}
}
#[resource(…, behaviours(Compiled<Pandoc>))]
}
Compiled<C> works on a model too: #[model(behaviours(Compiled<Pandoc>))].
Images
Image, Dimensions<P>, Images<G> and Logo<L> read an image’s size
on upload, and give a resource a gallery’s and a logo’s actions. They are
described in Images.
In what order they run
On a write through a resource:
- the model’s behaviours, in the order of
#[model(behaviours(..))]; - then the resource’s behaviours, in the order of
#[resource(behaviours(..))]; - then the resource’s own hooks (Inputs).
So a hook sees what the behaviours set. The model’s own writes
(insert, save, update) run only the first step (Writing an
object).
A behaviour works on the write, not on the input. It reads and sets the
columns of the Insert or the Update by their names
(insert.literal("content_src"), insert.sets("created")), so it works
with any input the resource has.
A behaviour’s actions and rules
A behaviour’s actions are the resource’s actions. The resource’s rules
name them like any other action: above, actions(get_flags) lets anyone
count the flags, while only the staff can add them. The rules are checked
when compiling: a rule that names an action the resource does not have
does not compile. The OpenAPI document lists a behaviour’s actions with
the resource’s (OpenAPI).
Writing a behaviour
On a resource
A behaviour of a resource implements Behaviour<R> for every resource
R. Here is one that writes a slug from the name, on a creation:
#![allow(unused)]
fn main() {
use rind::api::{ApiError, Behaviour, Ctx, Resource};
use rind::query::{Insert, Prefix, Value};
pub struct Slugged;
impl<R: Resource> Behaviour<R> for Slugged {
const COLUMNS: &'static [&'static str] = &["name", "slug"];
type Parameters = ();
async fn creating(_ctx: &Ctx, insert: Insert<R::Model>) -> Result<Insert<R::Model>, ApiError> {
let Some(Value::Text(name)) = insert.literal("name") else { return Ok(insert) };
let slug = slugify(name); // your own function
Ok(insert.value(Prefix::root::<R::Model>().col::<String>("slug"), slug))
}
}
}
COLUMNSare the columns the model must have; the compiler checks them.creatingruns before an insert andupdatingbefore an update (it also receives the object as it is). Each has a default that does nothing.type Parametersis what the behaviour reads from the query string:()for nothing, or a struct derivingParameters.filter(query, params)receives it, already read, on a list, and returns the query filtered. The resource lists these parameters with its own, in the OpenAPI document too.FlagsreadsFlagsParams(flags, on a list).actions()gives the behaviour’s actions. A behaviour with actions also names them all inconst ACTIONS(Flagshas&["add_flag", "remove_flag", "get_flags"]). The resource’s rules are checked against these names when compiling (Permissions). A debug build stops, when it makes the routes, on an action the list forgot.
On a model
A behaviour of a model implements rind::query::ModelBehaviour<M>. It
has COLUMNS, inserting(insert) and updating(update). These are not
async and take no request: a model’s behaviour is about the data
only, so that it can run on every write, including those of a job or a
command. A behaviour that needs the request, or adds routes, is a
resource’s. Tracking and Compiled implement both traits, so they can
be put on either.
Reference
| Behaviour | Columns (field group) | On | What it does |
|---|---|---|---|
Tracking | created, updated (tracking) | model, resource | sets both on a creation, updated on a change |
Flags | flags (flags) | resource | the filter ?flags=a,b (objects that have both); the actions add_flag and remove_flag ({"flag": "a"} or {"flags": […]}, answered {"flags": […]}); get_flags, how many of the objects the request may see have each, [{"flag": "a", "count": 12}, …] |
Compiled<C> | C::SOURCE, C::TARGET | model, resource | on a write that sets the source, the target is C::compile(source) |
Content | content_src, content_html (content) | model, resource | Compiled with markdown (feature markdown) |
Image, Dimensions<P>, Images<G>, Logo<L> | an image’s file, width and height; a link table; a foreign key | resource | Images: the size read on upload, a gallery’s and a logo’s actions |
The Behaviour<R> trait
| Item | Default | |
|---|---|---|
const COLUMNS | &[] | the columns the model must have |
const ACTIONS | &[] | the names of its actions |
type Parameters | (required) | what it reads from the query string, () for nothing |
creating(ctx, insert) | returns the insert | before an insert |
updating(ctx, current, update) | returns the update | before an update of current |
filter(query, params) | returns the query | on a list |
actions() | none | its actions |
Markdown checked against pandoc
On the markdown sources of a real Django application, which pandoc
rendered, rind’s HTML is the same for 2,121 of 2,156 producers, 609 of
612 products, 2 of 2 families and 23 of 24 storages. The differences:
quotes whose side is ambiguous (" La Porée "), and a list written
without a blank line before it, which CommonMark reads as a list and
pandoc’s markdown does not.
Glossary
The words this book uses with a precise meaning, in alphabetical order.
Action. The name a rule uses for what a request does: list,
retrieve, create, update, partial_update, destroy, or the name
of an action of the resource’s own (#[action], DRF’s @action). A
detail action works on one object (/loans/{id}/give_back), a list
action on the resource (/stations/count). See Actions.
Alias, prefix. Names a client can put in fields that stand for
other fields of a serializer. See Serializers.
Annotated field. A serializer field computed by the database, as an
SQL expression, in the same query as the list (Django’s annotate).
app(). The function of the application crate that returns the
Application: its domains, its plugins, how users sign in. It plays the
part of INSTALLED_APPS and of the root urls.py.
Authenticator. The value that implements Authenticate: it turns
the Authorization header into an identity, nobody, or a 401. See
Authentication.
Behaviour. A type listed on a model or a resource
(behaviours(Tracking)) that adds what its writes set, and possibly
filters and actions. It replaces Django’s abstract models, view mixins
and pre_save signals. See Behaviours.
Context (Ctx). What every piece of resource code receives about
the request: the database (ctx.db), the user (ctx.user), the action
(ctx.action()), the typed parameters, the services.
Domain. One subject of the application, like a Django app: authors
and books, or loans. A domain is several crates, one per layer:
<domain>-models, <domain>-api… Domains are ordered: a domain’s
models may point to the domains before it. See Organising an
application.
Field group. A named set of columns added to models with
#[with_fields(..)]: rind_auth::user_base adds the password and
last_login.
Filterset. A struct of filters for one model’s list
(#[derive(FilterSet)]), as django-filter’s FilterSet. See
Filters.
Foreign table. A table no model describes, known to rind only by its keys, so that a deletion can still follow them.
Fresh schema. A PostgreSQL schema created for one test, with the
application’s migrations applied (rind::testing::fresh_schema).
Hook. Code that runs inside a write’s transaction: a method of
Writes (creating, updating, saved, deleting). Django’s
perform_create and save() overrides. See Inputs.
Plugins have hooks of another kind, around every call (Around): see
Plugins.
Identity. What rind knows of the user of a request: an id, the
is_staff and is_superuser flags, the slugs of their groups, and data
of the application’s own.
Input. The struct that says what a client may write on a model, and
how it is checked (#[derive(Input)]): the writing half of a DRF
ModelSerializer. See Inputs.
Layer. One of models, shared, ops, api: the crates a domain
is cut into. A crate depends only on the layers below it. ops holds
what the domain does without HTTP (Django’s services.py); shared the
serializers and filters other domains reuse.
Loader. An async function that computes a serializer field for the
keys of a whole page at once (#[computed(loader = …)]): one call per
page, never one per row.
Lookup. How a filter compares its column with the value: eq, gt,
icontains, contains, under…
Mandatory, on request. A mandatory field is always sent, whatever
the client asks. An on request field is sent only when the client asks
for it (fields or include).
Mode. A value a rule gives to a request, which decides the rows the
request works on (a query) and the fields it hides. It is rind’s
get_queryset. An object outside the mode’s rows answers 404. See
Permissions.
Nested field. A serializer field holding a related object, or a list of them, loaded once per page.
Output, serializer. The struct that says what an object looks like in
an answer (#[derive(Serializer)]): the reading half of a DRF
ModelSerializer. See Serializers.
Page envelope. The shape of a list answer: {"parameters", "nav", "results"}.
Path. A typed function that names a column or a relation of a model:
Book::title(), Book::author().name(). Paths replace the strings of
Django’s querysets ("author__name"), and the compiler checks them.
Plugin. A value installed with .with(..) in app(), usually behind
a Cargo feature. It can add services, hooks, routes, models, commands
and checks. See Plugins.
Resource. A model served over HTTP, with its list, detail, writes and
actions (#[derive(Resource)]): DRF’s ModelViewSet. See
Resources.
Rule. #[rule(..)] on a resource: it gives a kind of user (anyone,
signed in, staff, a group…) some actions, and optionally a mode. The
rules are read in order, and the first that accepts the request decides.
See Permissions.
Scope. A function of a model that returns a query:
Loan::of(user), Station::open(). Where Django has manager methods.
Modes use scopes as their queries.
Scoped model. A model with #[model(scoped)]: it has no default
query, so every use must say which rows it reads.
Service. A value shared by all requests (a mailer, a cache), found
by its type: ctx.service::<T>().
State file. NNNN_name.state.json, beside each migration: the
schema of the domain after it, which rind make compares the models
with.
Typed parameters. A struct of query parameters that are not filters
(#[derive(Parameters)]), read once and found with
ctx.parameters::<P>(). See Parameters.