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.