Skip to Content

Floor from Cx

A tour of what a handler reaches through Cx: the caller, realtime, MQTT, devices, KV, queues, secrets, messages, files and AI.

Every handler gets cx: Cx first. It's the handle to the caller, the project's database and Floor's services. Every call goes over the Floor link to floord, which does it for this project only: a backend can't publish on another project's channels or read its keys. This page shows one short example of each. The full signatures are in Cx.

cx.Does
user(), org(), device(), can(p), require(p), project()The caller and the project
db()The project's database (The database)
publish(channel, &msg), publish_to(name, &msg)Realtime, to dashboards
mqtt_publish(topic, payload, retain)MQTT, inside the project's prefix
command(device, name, &args)A device command Floor tracks
device_info(hw), set_device_config(hw, set, &remove)A device's state and its desired config
kv_get, kv_set, kv_delete, kv_get_json, kv_set_jsonThe project's key-value store
enqueue(queue, &payload), enqueue_after(queue, &payload, delay)Queue jobs
secret(name)A project secret
notify(Notification::…)Email, WhatsApp or push
upload_url(Upload::…), download_url(key, expires), delete_blob(key)Files in blob storage
chat(Chat::…), ocr(image)Floor's AI module

When a call fails, Floor refused it or couldn't do it: the error is Error::Floor, and a route that returns it with ? answers 502.

The caller

let user = cx.user()?;            // 401 when nobody is signed in
let org = cx.org()?;              // 403 when the caller isn't in an organization
if cx.can("gates:open") { /* … */ }
cx.require("vehicles:write")?;    // 403 unless the caller's roles allow it
let hw = cx.device()?;            // on a #[post(device)] route: the device's hardware id
let slug = cx.project();          // "sac", or "sac-staging" in an environment

user() has sub, kind (user, service or device), org, roles, email and name. Trigger handlers have no caller, so user() and org() are errors there. See Realtime and permissions.

Realtime

Push a lane card to every dashboard listening on the lanes channel:

cx.publish(Lanes, &LaneCard { lane: 1, plate: "LEB-4821".into(), action: "open".into(), visit: 42 }).await?;

Lanes is declared in channels.rs with floor::channel!, which ties the channel to its message type. publish_to("alerts", &msg) publishes on app:alerts without a declared channel. Both return how many listeners got it. See Realtime and permissions.

MQTT

Publish to a device, inside the project's prefix (dev-1/config is sac/dev-1/config):

cx.mqtt_publish("dev-1/display", r#"{"text":"Welcome"}"#, false).await?;

The payload is bytes (&str, String or Vec<u8>). retain = true keeps it for devices that connect later. To hear devices, use #[mqtt]. Topics are covered in Devices and MQTT.

Device commands

Open a gate's barrier and let Floor track the answer:

let id = cx.command("dev-1", "open_gate", &serde_json::json!({ "lane": 1 })).await?;

Floor publishes the command to the device and records whether it answered or timed out. The device must be online. The result arrives as a command device event and on the dashboard's devices channel.

Device state and config

let info = cx.device_info("SL-GW-0142").await?;
if !info.online {
    floor::tracing::warn!(device = %info.hardware_id, last_seen = ?info.last_seen_at, "gateway is offline");
}

let mut set = serde_json::Map::new();
set.insert("dim".into(), serde_json::json!(40));
let config = cx.set_device_config("SL-GW-0142", set, &["schedule"]).await?;
  • device_info gives hardware_id, name, kind, status (pending, active, revoked), online, last_seen_at, firmware_version, health (what it last published on its health topic) and labels.
  • set_device_config changes some keys of the device's desired config and removes others; the rest stay. Floor saves it and publishes it retained on <device>/config, so the device gets it now or when it next connects. It returns the new version and desired config.

Devices joining

A product's own admin pages can let devices in, without the Floor console:

let waiting = cx.devices(Some("pending")).await?;
cx.approve_device(&waiting[0].hardware_id, Some(&waiting[0].key_fingerprint)).await?;
cx.revoke_device("gate-9").await?;
let made = cx.claim_codes(ClaimCodes::new(20).label("batch 3").auto_approve()).await?;

Approving with the fingerprint a person compared with the device refuses a key swapped in meanwhile. Revoking disconnects the device at once. Claim codes are in the answer only.

Cameras

let lease = cx.open_lease(&["gate-1-entry", "gate-1-exit"], "Ayesha").await?;
// The player POSTs its SDP offer to each lease.cameras[i].whep_url with lease.token.
cx.renew_lease(&lease.id).await?;   // every lease.renew_every_secs while someone watches
cx.end_lease(&lease.id).await?;

cx.cameras() lists the project's cameras with their status. An on-demand camera pushes only while a lease names it, so end leases when the viewer leaves; one that isn't renewed lapses.

People and roles

let g = cx.grant(Access::new("imran@example.com", "guard").name("Imran Ali").org("gulberg-residency")).await?;
if let Some(link) = &g.invite_url {
    cx.notify(Notification::email(&g.email).template("welcome").var("link", link)).await?;
}
cx.grant(Access::remove("old.guard@example.com")).await?;

A backend changes roles in its own project only, and never makes an operator. Someone Floor doesn't know is invited, and invite_url is where they set a password. cx.permissions() lists what the caller's roles allow.

KV

Small values that outlive a restart: settings, presence, a receipt's id.

cx.kv_set("receipt:42", job.id.into_bytes(), None).await?;
cx.kv_set_json("presence:dev-1", &serde_json::json!({ "state": "online" }), Some(Duration::from_secs(300))).await?;
let presence: Option<serde_json::Value> = cx.kv_get_json("presence:dev-1").await?;
cx.kv_delete("receipt:42").await?;

Values are bytes, smaller than 1 MiB. With a ttl, the key goes away after that long. A missing key is None, not an error. (Duration is std::time::Duration.)

Queues

let job_id = cx.enqueue("receipts", &serde_json::json!({ "visit": 42 })).await?;
cx.enqueue_after("receipts", &serde_json::json!({ "visit": 43 }), Some(Duration::from_secs(60))).await?;

A #[job(queue = "receipts")] handler runs them; see Triggers.

Secrets

let key: Option<String> = cx.secret("ANPR_API_KEY").await?;

It's None when the project doesn't have it. Secrets are set with floor secrets set <project> <name> (the value is read from stdin) and never shown again.

Messages

Send an email from a template, a WhatsApp message, or a push notification. Floor queues it and retries:

cx.notify(Notification::email("guard@example.com").template("visit-approved").var("plate", "LEB-4821")).await?;
cx.notify(Notification::whatsapp("+923001234567").text("Gate 3 is open").lang("en")).await?;
cx.notify(Notification::push(expo_token).text("A visitor is at the gate").data(serde_json::json!({ "visit": 42 }))).await?;
  • Start with email(to), whatsapp(phone) or push(token), then a template with vars, or subject, text and html.
  • lang("ur") picks a template's Urdu version.
  • idempotency_key(k): the same key again within 30 days sends nothing new and returns the first message.

It returns the message's id, channel and status (usually queued). See Messages.

Files

File bytes never go through the backend. It hands the caller a signed URL, and the caller talks to blob storage directly:

// api/visits/[id]/photo.rs  →  POST /api/visits/{id}/photo
use std::collections::BTreeMap;

use floor::prelude::*;

#[derive(Deserialize, Type)]
pub struct NewPhoto {
    size: u64,
}

#[derive(Serialize, Type)]
pub struct PhotoUpload {
    url: String,
    method: String,
    headers: BTreeMap<String, String>,
}

#[post(can = "visits:write")]
pub async fn post(cx: Cx, Path(visit): Path<i64>, Json(f): Json<NewPhoto>) -> Result<Json<PhotoUpload>> {
    let key = format!("visits/{visit}/plate.jpg");
    let s = cx.upload_url(Upload::new(key, f.size).content_type("image/jpeg")).await?;
    Ok(Json(PhotoUpload { url: s.url, method: s.method, headers: s.headers }))
}
  • upload_url signs one upload of exactly size bytes; the store refuses any other length, and the size counts toward the project's quota. The URL lasts 15 minutes unless .expires_in(…) says otherwise.
  • download_url(key, None) signs a download, valid for an hour by default.
  • delete_blob(key) deletes an object.
  • A SignedUrl has url, method, headers and expires_at: the caller sends method to url with those headers.

Keys are relative to the project's own prefix. SignedUrl (floor::services::SignedUrl) doesn't derive floor::Type, so a route returns a type of its own, as above. See Files.

AI

Ask a model through Floor, under the project's key, limits and usage log:

let answer = cx.chat(Chat::new(format!("Summarise these visits: {list}")).system("Be brief.")).await?;
let summary = answer.text;

let read = cx.ocr(jpeg_bytes).await?;
let plate = read.lines.first().map(|l| l.text.clone());
  • Chat starts with one user message; add turns with .user(…) and .assistant(…), and set .system(…), .model(…) and .max_tokens(…). Without a model, Floor's default answers. The answer has text, model and stop_reason.
  • ocr reads text in a JPEG or PNG. It gives text (lines joined with newlines) and lines, each with text, confidence and its box in pixels.

See AI.

Logs

floor::tracing::info!(lane, plate = %e.plate, "opened");

Logs go to floor dev's output while you edit, and to the system journal on a Floor server. FLOOR_LOG sets the filter (default info,sqlx=warn).

Outbound HTTP

There's no cx call for other services. Use any HTTP client as the crate's own dependency (reqwest, say). On a Floor server, a backend whose floor.toml lists outbound hosts may reach only those. See Sandbox and limits.

On this page