Handlers
What a handler takes and returns: the extractors, the trigger inputs, the outputs, and #[derive(floor::Type)] with its options.
A handler is a pub async fn with cx: Cx first. What comes after depends on its attribute:
| Attribute | Signature |
|---|---|
#[get], #[post], #[put], #[patch], #[delete] | async fn(Cx, extractors…) -> impl IntoResponse, up to six extractors |
#[ws] | async fn(Cx, Socket) -> Result<()> |
#[mqtt] | async fn(Cx, Mqtt<T>) -> Result<()> or async fn(Cx, MqttRaw) -> Result<()> |
#[job] | async fn(Cx, Job<T>) -> Result<()> |
#[device] | async fn(Cx, DeviceEvent) -> Result<()> |
#[event] | async fn(Cx, Event<T>) -> Result<()> |
#[every], #[cron] | async fn(Cx) -> Result<()> |
#[background] | async fn(Cx, Stop) -> Result<()> |
A route's extractors run in order before the handler. The first that fails answers the request with its error, usually a 400.
Extractors
Json
pub struct Json<T>(pub T);The request body as JSON, for T: DeserializeOwned + floor::Type. An empty body is a 400 ("the
request needs a JSON body"); a body that doesn't fit T is a 400 that says why.
#[derive(Deserialize, Type)]
pub struct NewVehicle {
plate: String,
#[serde(default)]
allowed: bool,
}
#[post(can = "vehicles:write")]
pub async fn post(cx: Cx, Json(v): Json<NewVehicle>) -> Result<Created<Vehicle>> { … }Json is also an output; see below.
Query
pub struct Query<T>(pub T);The query string, for T: DeserializeOwned + floor::Type: Query<Page> from
?before=812&limit=20. A query that doesn't fit is a 400. Give fields #[serde(default)] to make
them optional. A repeated key fills a Vec field (?vehicle=1&vehicle=2 is
vehicle: Vec<i64>, and one ?vehicle=3 is [3]), the way the generated client sends arrays.
Query<Vec<(String, String)>> gives every pair in order.
#[derive(Deserialize, Type)]
pub struct Page {
#[serde(default)]
before: Option<i64>,
#[serde(default = "fifty")]
limit: i64,
}
#[get(can = "visits:read")]
pub async fn get(cx: Cx, Query(page): Query<Page>) -> Result<Json<Visits>> { … }Path
pub struct Path<T>(pub T);Path parameters, for T: DeserializeOwned + floor::Type: Path<i64> for one, Path<(i64, String)> for two in order, or a struct with a field per parameter name. Each parameter is tried
as a number first, then as a string, so Path<String> takes 42 too. One that doesn't fit is a
400 naming the parameter.
// api/gates/[lane]/open.rs: POST /api/gates/{lane}/open
#[post(can = "gates:open")]
pub async fn post(cx: Cx, Path(lane): Path<i64>) -> Result<Created<Opened>> { … }Body
pub struct Body(pub bytes::Bytes);The raw request body, up to the route's body limit (1 MiB by default).
RawQuery
pub struct RawQuery(pub String);The query string as it came, without the ?.
Multipart
pub struct Multipart {
pub parts: Vec<Part>,
}
pub struct Part {
pub name: String,
pub filename: Option<String>,
pub content_type: Option<String>,
pub data: bytes::Bytes,
}A multipart/form-data body: a browser's FormData, fields and files in order. Anything else is
a 400 that says to send a form.
| Method | Gives |
|---|---|
form.text("title") | A field's value, as text |
form.file("document") | The part named document that has a file name |
form.get("x") | The first part named x |
form.all("tag") | Every part named tag |
part.text() | A part's data as text |
Headers
pub struct Headers(pub http::HeaderMap);The request's headers.
#[post(public)]
pub async fn post(cx: Cx, Headers(h): Headers, Body(raw): Body) -> Result<NoContent> {
let sig = h.get("x-signature").and_then(|v| v.to_str().ok()).unwrap_or_default();
// check `sig` against `raw`
Ok(NoContent)
}Request
pub struct Request {
pub method: Method,
pub path: String,
pub query: String,
pub headers: HeaderMap,
/// Path parameters in order: `{id}` in `/api/visits/{id}`.
pub params: Vec<(String, String)>,
pub body: Bytes,
}A request as extractors see it: the whole body is read first. It isn't an extractor itself; it
is what FromRequest reads from.
FromRequest
pub trait FromRequest: Sized {
fn from_request(req: &Request) -> Result<Self>;
/// What the client sends for it.
fn input(_reg: &mut Registry) -> Input {
Input::Other
}
}Implement it to make an extractor of your own. Without input, the dashboard's client treats
it as nothing the caller sends on purpose, as it does Headers.
use floor::{FromRequest, Request};
pub struct Lang(pub String);
impl FromRequest for Lang {
fn from_request(req: &Request) -> Result<Self> {
let l = req.headers.get("accept-language").and_then(|v| v.to_str().ok()).unwrap_or("en");
Ok(Lang(if l.starts_with("ur") { "ur" } else { "en" }.into()))
}
}Trigger inputs
A trigger handler takes one input after cx. One that can't be read, such as an MQTT payload
that doesn't fit T, is an error for that trigger: the handler doesn't run, and the trigger is
acked with the error. See Errors.
Mqtt
pub struct Mqtt<T> {
/// The full topic, `sac/dev-1/events`.
pub topic: String,
/// The topic's level after the project: the device, by Floor's topic layout.
pub device: String,
pub body: T,
pub retain: bool,
}An MQTT message with a JSON body, for T: DeserializeOwned.
#[derive(Deserialize)]
pub struct PlateEvent {
pub event_id: String,
pub lane_id: i64,
pub plate: String,
}
#[mqtt("+/events")]
pub async fn events(cx: Cx, msg: Mqtt<PlateEvent>) -> Result<()> {
let e = msg.body;
// msg.device is "gate-3" for sac/gate-3/events
Ok(())
}MqttRaw
pub struct MqttRaw {
pub topic: String,
pub device: String,
pub payload: Bytes,
pub retain: bool,
}An MQTT message as bytes, for payloads that aren't JSON.
Job
pub struct Job<T> {
pub id: String,
/// This attempt's number, from 1.
pub attempt: u32,
pub body: T,
}A queue job with a JSON body, for T: DeserializeOwned.
#[job(queue = "receipts", concurrency = 2)]
pub async fn send(cx: Cx, job: Job<Receipt>) -> Result<()> {
cx.notify(
Notification::email(&job.body.email)
.template("visit-receipt")
.var("visit", job.body.visit)
.idempotency_key(format!("receipt-{}", job.id)),
)
.await?;
Ok(())
}DeviceEvent
pub struct DeviceEvent {
pub event: String,
/// The device's hardware id, when the event names one.
pub device: Option<String>,
/// What the realtime hub's `devices` channel carries.
pub data: serde_json::Value,
}A device event: online, offline, health, config or command.
#[device(online, offline)]
pub async fn presence(cx: Cx, ev: DeviceEvent) -> Result<()> {
let Some(device) = ev.device else { return Ok(()) };
sqlx::query("update lanes set online = $2 where device = $1")
.bind(&device)
.bind(ev.event == "online")
.execute(cx.db())
.await?;
Ok(())
}Event<T>
pub struct Event<T = serde_json::Value> {
/// Its type, e.g. `message.received`.
pub kind: String,
pub body: T,
}One of the project's events, for #[event]: body is the event's data (what a webhook's
data carries) parsed into T. Data that doesn't parse is an error ack that says why.
#[event("message.status")]
pub async fn delivery(cx: Cx, e: Event) -> Result<()> {
if e.body["status"] == "failed" {
floor::tracing::warn!("message {} failed", e.body["id"]);
}
Ok(())
}Stop
pub struct Stop(/* private */);
impl Stop {
pub fn is_stopped(&self) -> bool;
/// Waits until it's time to stop.
pub async fn stopped(&mut self);
}Tells a background task to stop: a newer version took over, or the backend is stopping. Return
soon after; the backend waits up to 30 seconds. This example uses tokio's select! and
interval, so it needs tokio as a dependency.
#[background]
pub async fn arbiter(cx: Cx, mut stop: Stop) -> Result<()> {
let mut every = tokio::time::interval(std::time::Duration::from_secs(5));
loop {
tokio::select! {
_ = every.tick() => settle_lanes(&cx).await?,
() = stop.stopped() => return Ok(()),
}
}
}FromTrigger
pub trait FromTrigger: Sized {
fn from_trigger(project: &str, t: &floor::link::Trigger) -> Result<Self>;
}The trait behind the trigger inputs.
Outputs
A route returns anything that implements IntoResponse, usually inside Result. An Err
becomes its status and {"error": "…"}; see Errors.
| Return | Status | Body |
|---|---|---|
Json<T> | 200 | T as JSON |
Created<T> | 201 | T as JSON |
NoContent, () | 204 | none |
String, &'static str | 200 | text, text/plain; charset=utf-8 |
Response | its own | its own |
Result<T> | T's, or the error's |
T in Json<T> and Created<T> must implement Serialize and floor::Type, so the dashboard's
client knows the shape.
Json
pub struct Json<T>(pub T);A JSON response with 200.
#[get(can = "visits:read")]
pub async fn get(cx: Cx, Path(id): Path<i64>) -> Result<Json<Visit>> {
let visit: Visit = sqlx::query_as("select … from visits where id = $1 and organization = $2")
.bind(id)
.bind(cx.org()?)
.fetch_optional(cx.db())
.await?
.or_not_found()?;
Ok(Json(visit))
}Created
pub struct Created<T>(pub T);A JSON response with 201 Created.
NoContent
pub struct NoContent;204, no body.
Response
pub struct Response {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Bytes,
}
impl Response {
pub fn new(status: u16, body: impl Into<Bytes>) -> Self;
pub fn header(self, name: &str, value: &str) -> Self;
}A response built by hand: a status, headers and a body. The dashboard's client doesn't know its shape.
#[get(can = "visits:read")]
pub async fn get(cx: Cx, Path(id): Path<i64>) -> Result<Response> {
let csv = visits_csv(&cx, id).await?;
Ok(Response::new(200, csv)
.header("content-type", "text/csv")
.header("content-disposition", "attachment; filename=\"visits.csv\""))
}IntoResponse
pub trait IntoResponse {
fn into_response(self) -> Response;
/// What the client gets, for the TypeScript client and OpenAPI.
fn output(_reg: &mut Registry) -> Output
where
Self: Sized,
{
Output::Unknown
}
}Implement it to return a type of your own.
#[derive(floor::Type)]
#[derive(Serialize, Deserialize, Type)]
pub struct Visit {
pub id: i64,
pub plate: String,
pub vehicle_id: Option<i64>,
pub status: String,
}Describes a type for the TypeScript client, OpenAPI and zod, the way serde writes it. Json<T>,
Query<T>, Path<T>, Created<T> and channel messages need it. Mqtt<T> and Job<T> don't.
Types it knows: bool, the integer and float types, String, str, char, uuid::Uuid,
serde_json::Value, (), Option<T>, Vec<T>, slices and arrays, HashSet<T>, BTreeSet<T>,
HashMap<String, V>, BTreeMap<String, V>, tuples of up to four, &T, Box<T>, Arc<T>, and
any type that derives Type. For anything else, such as a date type, say the shape with
#[floor(as = "…")].
serde attributes it follows:
| On | Attributes |
|---|---|
| the type | rename, rename_all, tag, content, untagged |
| a field | rename, skip, skip_serializing, skip_deserializing, default, skip_serializing_if |
| a variant | rename, skip, skip_serializing |
A field with default, skip_serializing_if, or an Option type is optional in the client:
name?: T | null for an Option. Other serde attributes are passed over.
#[floor(rename = "…")]
On a type. The name the client uses for it, without changing serde's output. Two types with the same name stop the backend at start and fail its tests; rename one.
#[derive(Serialize, Type)]
#[floor(rename = "GateVisit")]
pub struct Visit { … }#[floor(as = "…")]
On a field. Its shape in the client: string, number, integer, boolean or any. Use it
for a type the derive doesn't know, and for a field serde writes with custom code.
#[derive(Serialize, Type)]
pub struct Visit {
pub id: i64,
#[serde(with = "time::serde::rfc3339")]
#[floor(as = "string")]
pub entry_at: time::OffsetDateTime,
}What the derive refuses
Each is a compile error that says what to do:
- a generic type;
- a union;
#[serde(flatten)];#[serde(transparent)],#[serde(rename_all_fields = "…")],#[serde(remote = "…")];- a field with
with,serialize_withordeserialize_withand no#[floor(as = "…")]; - an internally tagged enum (
tagwithoutcontent) with a variant that has no named fields; - any other
#[floor(…)]key.
App
floor::App, what the build step generates from a backend's files, its methods, Auth, Limits, Permissions, and floor::run with its flags and environment variables.
Attributes
Every handler attribute and what it takes, where each may live, how file paths become routes and trigger names, and the errors mistakes give.