Skip to Content

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.

floor::App is a backend: its routes, WebSockets, triggers, permissions, channels and migrations. You rarely build one by hand. The build step writes it from the crate's files, and floor::run runs it.

What the build step generates

floor::build::generate() in build.rs reads api/, on/ and jobs/, and writes $OUT_DIR/floor_app.rs. floor::app!() in src/lib.rs includes it. The file holds:

  • a module tree: pub mod api, pub mod on and pub mod jobs, one module per file;
  • permissions.rs as pub mod permissions and channels.rs as pub mod channels, when they exist;
  • each Rust migration in db/migrations/ as a private module;
  • pub fn app() -> floor::App.

app() does this, in order:

  1. App::new(env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"));
  2. app.permissions(permissions::permissions()), when permissions.rs exists;
  3. app.migrations(sqlx::migrate!("db/migrations")), when db/migrations/ exists, and app.rust_migration(…) for each Rust migration;
  4. one registration per handler, with its route's path or its trigger's name;
  5. app.channel::<channels::Lanes>("Lanes") for each floor::channel! in channels.rs.

Each attribute adds a hidden function next to its handler that calls the matching App method below. See Attributes for how files become paths and names.

App

pub struct App { /* private */ }

App::new

pub fn new(name: &'static str, version: &'static str) -> Self

An empty app. The generated app() passes the crate's name and version.

app.route

pub fn route<H, T>(&mut self, method: Method, path: &'static str, auth: Auth, h: H)
where
    H: Handler<T>,

A route on method and path (/api/visits/{id}), for whoever auth lets in, with the default limits. #[get], #[post], #[put], #[patch] and #[delete] call it.

app.route_with

pub fn route_with<H, T>(
    &mut self,
    method: Method,
    path: &'static str,
    auth: Auth,
    limits: Limits,
    h: H,
) where
    H: Handler<T>,

A route with its own body size or time limit. A route attribute with body or timeout calls it.

app.ws

pub fn ws<H: WsHandler>(&mut self, path: &'static str, auth: Auth, h: H)

A WebSocket on path for whoever auth lets in. #[ws(…)] calls it. The handler is an async fn(Cx, Socket) -> Result<()>.

app.mqtt

pub fn mqtt<H, A>(&mut self, filter: &'static str, h: H)
where
    H: TriggerHandler<A>,

MQTT messages matching filter inside the project's prefix: +/events means <project>/+/events. #[mqtt("…")] calls it.

app.every

pub fn every<H: TickHandler>(&mut self, name: &str, millis: u64, h: H)

A tick named name every millis milliseconds, one run at a time: a tick is skipped while the last one runs. #[every("…")] calls it.

app.cron

pub fn cron<H: TickHandler>(
    &mut self,
    name: &str,
    schedule: &str,
    timezone: Option<&str>,
    h: H,
)

A cron schedule (0 2 * * *), read in timezone (Asia/Karachi when None). Its runs come as jobs, so one that falls during a deploy runs on the new version. #[cron("…")] calls it.

app.device

pub fn device<H, A>(&mut self, events: &[&str], h: H)
where
    H: TriggerHandler<A>,

Device events: online, offline, health, config, command. An empty list means all of them. #[device(…)] calls it.

app.job

pub fn job<H, A>(&mut self, queue: &'static str, concurrency: u16, h: H)
where
    H: TriggerHandler<A>,

Jobs from one of the project's queues, up to concurrency at a time. #[job(queue = "…")] calls it.

app.background

pub fn background<H: BackgroundHandler>(&mut self, name: &str, h: H)

A long-running task named name, in the live version only: it starts once the backend is ready and stops when it's drained. Without a link to Floor, background tasks don't run. #[background] calls it.

app.permissions

pub fn permissions(&mut self, p: Permissions)

The app's permissions, from permissions.rs.

app.migrations

pub fn migrations(&mut self, m: sqlx::migrate::Migrator)

The SQL files of db/migrations (sqlx::migrate!).

app.rust_migration

pub fn rust_migration(
    &mut self,
    version: i64,
    description: &'static str,
    source: &'static str,
    up: floor::migrate::Up,
)

A Rust file of db/migrations: <version>_<name>.rs with pub async fn up. Its source is the file's text, for the migration's checksum.

app.migration_steps

pub fn migration_steps(&self) -> Option<&floor::migrate::Migrations>

What db/migrations holds, to run by hand in a test or a tool. Migrations::run(&self, db: &PgPool) applies what the database doesn't have yet.

app.channel

pub fn channel<C: Channel>(&mut self, _ident: &'static str)

A realtime channel declared in channels.rs. The build step registers each one, so its message type reaches the dashboard's client.

app.check

pub fn check(&self) -> Result<(), String>

Mistakes the build step can't see:

  • a can naming a permission permissions.rs doesn't have;
  • two types with the same name for the client;
  • a queue handled twice, or a queue whose name starts with floor.;
  • two cron handlers with the same name.

floor::run and TestApp::start call it, so these stop the backend at start and fail its tests.

app.triggers

pub fn triggers(&self) -> Vec<floor::link::TriggerSpec>

What this backend wants to hear: its MQTT filters, ticks, device events, queues and cron schedules. The backend sends these to Floor when it connects.

app.describe

pub fn describe(&self) -> serde_json::Value

The manifest: the name and version, routes with who may call them and their limits, WebSockets, channels, types, triggers, background tasks, permissions and migrations. --describe prints it.

app.typescript

pub fn typescript(&self) -> String

floor.gen.ts: the dashboard's typed client. See The dashboard's client.

app.openapi

pub fn openapi(&self) -> serde_json::Value

The backend as an OpenAPI 3.1 document, with each route's auth as x-floor-auth.

app.zod

pub fn zod(&self, client: &str) -> String

zod schemas for its types; client is where floor.gen.ts is, as an import path (./floor.gen).

Auth

pub enum Auth {
    Public,
    SignedIn,
    Roles(&'static [&'static str]),
    /// `resource:action` from `permissions.rs`.
    Can(&'static str),
    /// One of the project's devices, by its Floor device token; nobody else.
    Device,
}

Who may call a route or open a WebSocket. The attributes write it: public, signed_in, role/roles, can, device.

VariantLets inOtherwise
Publicanyone, with or without a token
SignedInany valid token for the project: a user's access token or a service client's401
Roles(…)a caller holding one of the roles401 without a token, 403 without the role
Can(p)a caller whose roles permissions.rs allows for p401 without a token, 403 without the permission
Devicethe project's devices, by the token Floor's device protocol gave them401 without a token, 403 for anyone else

A device token is refused (403) on every route that isn't Device or Public. On a Public route a token that isn't valid is ignored, and the handler runs with no caller; on any other route it is a 401.

Limits

pub struct Limits {
    pub body: Option<u64>,
    pub timeout_ms: Option<u64>,
}

A route's request limits (#[post(…, body = "10mb", timeout = "2m")]). Unset ones are the defaults.

Item
Limits::BODY: u64the largest request body by default: 1 MiB
Limits::TIMEOUT_MS: u64how long a handler may take by default: 60 s
fn body(&self) -> usizethe body limit in bytes
fn timeout(&self) -> Durationthe time limit

A body over the limit is a 413 before it's read. A handler past its time is stopped, and the caller gets a 504.

Permissions

pub struct Permissions { /* private */ }

resource:action mapped to the roles allowed. floor::permissions! builds one.

Method
Permissions::new(entries: &[(&str, &[&str])]) -> Selffrom ("visits:read", &["admin", "guard"]) pairs
fn has(&self, perm: &str) -> boolwhether perm is defined
fn allows(&self, roles: &[String], perm: &str) -> boolwhether any of roles holds perm
fn entries(&self) -> impl Iterator<Item = (&str, &[String])>every permission and its roles

floor::run

pub fn run(app: App) -> std::process::ExitCode

Runs the backend until Floor drains it or it's told to stop. Call it from src/main.rs:

fn main() -> std::process::ExitCode {
    floor::run(gate::app())
}

At start it connects to the database and to Floor, says what it wants to hear, serves HTTP and tells Floor it's ready. Background tasks start then. When a newer version takes over, or the process gets SIGTERM or Ctrl-C, it stops taking connections and signals its background tasks. It waits up to 30 seconds for what's in flight, then exits. If the link to Floor breaks, it connects again, and Floor sends again whatever wasn't acked.

GET /_floor/health answers ok once the backend serves. Deploys and floor dev wait for it.

Flags

FlagDoes
--describeprints the manifest (app.describe()) as JSON and exits
--migrateapplies db/migrations to DATABASE_URL, prints each one it applied, and exits. A deploy runs this as a step before the new version starts.
--ts <file>writes the TypeScript client and exits
--zod <file>writes zod schemas and exits
--zod-client <path>the import path of the TypeScript client in the zod file (default ./floor.gen)
--openapi <file>writes the OpenAPI document and exits

--ts, --zod and --openapi combine, and run app.check() first:

gate --ts web/src/floor.gen.ts --zod web/src/floor.zod.ts --openapi web/openapi.json

Environment variables

Variable
FLOOR_LINK, FLOOR_LINK_TOKENwhere Floor's engine is, and this backend's token. Without them the backend serves HTTP only: no triggers, no background tasks, signed-in routes refused, and every Floor call through Cx fails.
PORTHTTP on 127.0.0.1:$PORT; default 3000
FLOOR_HTTPHTTP on this address instead (0.0.0.0:3000)
DATABASE_URLthe project's database. Without it cx.db() panics.
FLOOR_DB_POOLthe database pool's size; default 4
FLOOR_MIGRATE1 applies db/migrations at start (floor dev sets it; a deploy migrates as a step of its own)
FLOOR_LOGthe log filter; default info,sqlx=warn
FLOOR_PROJECTthe project's slug when there is no link (default local); with a link, Floor names the project

On Floor and under floor dev, these are set for you.

On this page