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

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:

LayerHoldsMay depend on
modelsthe models, their scopes, their migrationsthe models of the domains before its own
sharedserializers and filters that other domains reusemodels
opswhat the domain does, without HTTPmodels, shared, other ops crates
apithe resourcesanything 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

RuleChecked 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
AttributeWhereMeans
#[fk(Target, reverse = name)]on a keya key to a model this crate can name; Target gets the relation name back
#[fk(table = "…")]on a keya key to a model of a higher domain, by its table
#[fk(table = "…", unfollowed)]on a keythe same, with no relation declared yet
#[fk(table = "…", external)]on a keya key to a table no model describes
#[reverse(name = …, model = …, fk = "…", forward = …)]on the target modeldeclares a relation held by a key of model, in both directions