Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

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:

TokenUser
root-tokenroot, a superuser
staff-tokensam, of the railway’s staff
alice-token, bob-token, carol-tokenthree 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:

ResourceWho readsWho writesShows
/stationseveryonestafffilters 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)
/regionseveryonestaffan outline in GeoJSON, ?covers=, its area (Geography)
/lineseveryonestaffbehaviours: tracking, flags, markdown; a logo and a gallery (Images)
/imageseveryonestaffan image’s size read from its file; resized copies at /media/…--cover_256.webp
/trainssigned instaffnested lists, sums with a condition
/journeyseveryonestaffchecks between fields, actions with typed parameters and a body; the distance between two stations
/reservationstheir own, or all for staffsigned inpermission 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 /status and /ready (Health);
  • the cache, in memory, or in Redis when RIND_CACHE_URL names one;
  • the storage of files, in ./media or where RIND_STORAGE says (a folder, an S3 bucket), with resized copies of the images;
  • mail, written to the console, or sent where RIND_MAIL_URL says (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).

FileWhat it tests
api_actix.rs, api_axum.rsthe same HTTP cases (common/api_cases.rs) on both frameworks
db.rsthe query layer: relations (also between crates), trees, aggregates, loaders, unions, locks
model_writes.rsan object written by itself: insert, save, update, refresh, delete; the model’s behaviours
migrations.rsmaking and applying migrations as the models change
schema.rsthe models, the migrations and the database agree; the relations between crates hold
inspect.rsthe schema the migrations build, read back, is what the models describe
foreign_tables.rstables no model describes: what a deletion does to them, what dbcheck checks
databases.rsthe primary, a replica, reading after writing
geography.rspositions, outlines and distances with PostGIS
openapi.rsthe OpenAPI document, frozen in a snapshot
routes.rsroutes that are not resources, in a domain and in the application
cors.rsCORS preflights and headers, on both frameworks
auth.rssigning in with rind-auth: tokens, refresh, passwords, reset and sign-in codes by mail, limits
exports.rslists as xlsx and CSV
jobs.rsjobs: queued in a transaction, scheduled, retried, exclusive, timed out
mail.rsa reservation confirmed by mail, in memory, by SMTP (Mailpit, when RIND_TEST_SMTP_URL names it) and by a Mailgun the test plays
plugins.rsa 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