Skip to Content

Cx

Every method of Cx, the handle a handler reaches its caller, its database and Floor's services through, and the types those methods take and return.

Cx is the first argument of every handler. It holds the caller, the project's database and the connection to Floor. It is cheap to clone.

#[derive(Clone)]
pub struct Cx { /* private */ }

Methods that reach Floor are async and return floor::Result. When Floor refuses or fails the call, the error is Error::Floor, which a route answers with 502. A backend that runs without FLOOR_LINK and FLOOR_LINK_TOKEN gets that error from every one of them. See Errors.

In a trigger handler (MQTT, a tick, a cron run, a job, a device event, a background task) there is no caller: cx.user() is a 401 error and cx.can(…) is false.

The caller

cx.user

pub fn user(&self) -> Result<&User>

Who's calling: a signed-in user or a service client. Error::Unauthorized (401) when nobody is.

pub struct User {
    /// The user's id, or `client:<id>` for a service client.
    pub sub: String,
    /// `user`, `service` or `device`.
    pub kind: String,
    /// The organization's slug, when the user belongs to one.
    pub org: Option<String>,
    pub roles: Vec<String>,
    /// The device's hardware id, when a device is calling (`kind` is `device`).
    pub device: Option<String>,
    pub email: Option<String>,
    pub name: Option<String>,
    /// When the token runs out (Unix seconds).
    pub expires_at: i64,
}
let by = cx.user()?.sub.clone();

cx.org

pub fn org(&self) -> Result<&str>

The caller's organization. 401 when nobody is calling, 403 when the caller isn't in an organization. Scope queries by it so one customer never sees another's rows.

let visits: Vec<Visit> = sqlx::query_as("select … from visits where organization = $1")
    .bind(cx.org()?)
    .fetch_all(cx.db())
    .await?;

cx.device

pub fn device(&self) -> Result<&str>

The calling device's hardware id, on a route marked device. 401 when nobody is calling, 403 for anyone who isn't a device.

cx.can

pub fn can(&self, perm: &str) -> bool

Whether the caller's roles allow resource:action, as permissions.rs defines it. false when nobody is calling.

if cx.can("visits:remark") {
    // show the remarks too
}

cx.require

pub fn require(&self, perm: &str) -> Result<()>

Error::Forbidden (403, "you may not visits:remark") unless the caller's roles allow resource:action. Use it inside a handler when the check depends on the request; for a whole route, #[post(can = "…")] does the same before the handler runs.

if body.remark.is_some() {
    cx.require("visits:remark")?;
}

cx.project

pub fn project(&self) -> &str

The project's slug: sac, or sac-staging in an environment.

The database

cx.db

pub fn db(&self) -> &PgPool

The project's Postgres database as a sqlx PgPool, connected as the project's own role. Panics when the backend has no DATABASE_URL. sqlx errors convert into floor::Error with ?: no row is a 404, a unique violation is a 409.

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()?;

See The database.

Realtime and MQTT

cx.publish

pub async fn publish<C: Channel>(&self, _channel: C, message: &C::Message) -> Result<u32>

Publishes on a realtime channel declared with floor::channel!, on app:<name>. Returns how many listeners got it. The message type is checked against the channel's.

use crate::channels::Lanes;

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

cx.publish_to

pub async fn publish_to(&self, name: &str, message: &impl Serialize) -> Result<u32>

Publishes on app:<name> without a declared channel. Returns how many listeners got it. The dashboard's client has no type for an undeclared channel; prefer publish.

cx.mqtt_publish

pub async fn mqtt_publish(
    &self,
    topic: &str,
    payload: impl Into<Vec<u8>>,
    retain: bool,
) -> Result<()>

Publishes over MQTT inside the project's prefix: dev-1/config goes out on <project>/dev-1/config. With retain, the broker keeps the message for devices that connect later.

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

See Devices and MQTT.

Devices

cx.command

pub async fn command(&self, device: &str, name: &str, args: &impl Serialize) -> Result<String>

Sends a device a command; Floor tracks its ack. Returns the command's id. args is serialized as JSON.

let id = cx.command(&device, "open_gate", &json!({ "lane": lane, "by": by })).await?;

cx.device_info

pub async fn device_info(&self, hardware_id: &str) -> Result<DeviceInfo>

One of the project's devices by hardware id: whether it's online, its health, its firmware, its labels. See DeviceInfo.

let gate = cx.device_info("gate-3").await?;
if !gate.online {
    return Err(Error::conflict("gate 3 is offline"));
}

cx.set_device_config

pub async fn set_device_config(
    &self,
    hardware_id: &str,
    set: serde_json::Map<String, serde_json::Value>,
    remove: &[&str],
) -> Result<DeviceConfig>

Changes some of a device's desired config; the keys you don't name stay. Floor publishes the config retained on <device>/config, so the device gets it now or when it next connects. Returns the config after the change.

let mut set = serde_json::Map::new();
set.insert("open_seconds".into(), json!(8));
cx.set_device_config("gate-3", set, &["night_mode"]).await?;

cx.devices

pub async fn devices(&self, status: Option<&str>) -> Result<Vec<DeviceInfo>>

The project's devices, all of them or those with status: pending (claimed, waiting for an approval), active or revoked.

cx.approve_device

pub async fn approve_device(&self, hardware_id: &str, fingerprint: Option<&str>) -> Result<DeviceInfo>

Approves a pending device, so it can get tokens and connect. With fingerprint (the key_fingerprint a person compared with the device), only while the device still has that key: a key swapped in meanwhile is refused with 409.

cx.revoke_device

pub async fn revoke_device(&self, hardware_id: &str) -> Result<DeviceInfo>

Rejects a pending device or revokes an active one. It gets no new tokens and is disconnected from MQTT at once.

cx.claim_device, cx.device_token

pub async fn claim_device(&self, claim: &serde_json::Value) -> Result<Claimed>
pub async fn device_token(&self, request: &serde_json::Value, audience: Option<&str>) -> Result<DeviceToken>

For firmware that talks to the product's own API rather than to Floor: the backend passes the device's claim (hardware_id, public_key JWK, claim_code, …) and its token request ({ assertion, firmware_version }) on, unchanged, and hands the answer back.

  • The project is always the backend's own, whatever the device sent.
  • audience is the URL the device signs its assertion for when that's the product's (https://sac.example.com/api/devices/token); Floor's own token URL is always accepted.
  • Tokens only for the project's devices: an assertion from another project's device is refused.
  • Refusals are typed: Err(Error::Device(DeviceRefusal::Pending)) (waiting for an approval, 403), Revoked (403) or Unauthorized (401: a bad or expired assertion, or a device Floor doesn't know). ? answers the device with that status.
match cx.device_token(&body, Some(TOKEN_URL)).await {
    Ok(t) => Ok(Json(t)),
    Err(Error::Device(DeviceRefusal::Pending)) => Err(Error::forbidden("waiting for a guard to approve this gate")),
    Err(e) => Err(e),
}

New firmware should claim and get tokens from Floor directly (Devices and MQTT).

cx.claim_codes

pub async fn claim_codes(&self, codes: ClaimCodes) -> Result<CreatedClaimCodes>

New claim codes, for device labels. The codes are in the answer only: Floor keeps their hashes. See ClaimCodes.

let made = cx.claim_codes(ClaimCodes::new(50).label("batch 7").auto_approve()).await?;

Cameras

cx.cameras

pub async fn cameras(&self) -> Result<Vec<CameraInfo>>

The project's cameras, with their status and how many are watching.

cx.open_lease

pub async fn open_lease(&self, cameras: &[&str], viewer: &str) -> Result<Lease>

Opens a viewer lease on some of the project's cameras for viewer (a person's name, shown in the console). An on-demand camera pushes while a lease names it. Hand the lease's token and each camera's whep_url to the player; renew the lease every renew_every_secs, and end it when the viewer leaves.

let lease = cx.open_lease(&["gate-1-entry"], &cx.user()?.name.clone().unwrap_or_default()).await?;

cx.register_camera, cx.remove_camera

pub async fn register_camera(&self, camera: Camera) -> Result<CameraInfo>
pub async fn remove_camera(&self, name: &str) -> Result<()>

Registers a stream one of the project's devices pushes:

cx.register_camera(Camera::new("gate-2-entry", "nano-2", "cam1").label("Gate 2 entry").record(14)).await?;

Camera::new(name, device, stream) is on demand (it pushes while a lease names it); .always_on() pushes all the time, .record(days) keeps recordings. The device must be one of the project's; a name or stream already used is a 409.

cx.renew_lease, cx.end_lease

pub async fn renew_lease(&self, id: &str) -> Result<Lease>
pub async fn end_lease(&self, id: &str) -> Result<()>

A lease that isn't renewed lapses on its own.

KV

The project's durable key-value namespace. Keys are strings; values are bytes, or JSON with the _json methods.

cx.kv_get

pub async fn kv_get(&self, key: &str) -> Result<Option<Vec<u8>>>

The value under key, or None.

cx.kv_get_json

pub async fn kv_get_json<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>>

The value under key, parsed as JSON. A value that doesn't parse as T is a 500.

cx.kv_set

pub async fn kv_set(
    &self,
    key: &str,
    value: impl Into<Vec<u8>>,
    ttl: Option<Duration>,
) -> Result<()>

Sets a key. With ttl, it goes away after that long (at least a second).

cx.kv_set_json

pub async fn kv_set_json(
    &self,
    key: &str,
    value: &impl Serialize,
    ttl: Option<Duration>,
) -> Result<()>

Sets a key to value as JSON.

cx.kv_set_json("lane:3:last-plate", &"LEB-4821", Some(Duration::from_secs(600))).await?;
let last: Option<String> = cx.kv_get_json("lane:3:last-plate").await?;

cx.kv_delete

pub async fn kv_delete(&self, key: &str) -> Result<()>

Removes a key.

Queues

cx.enqueue

pub async fn enqueue(&self, queue: &str, payload: &impl Serialize) -> Result<String>

Adds a job to one of the project's queues; returns its id. A #[job(queue = "…")] handler takes it. Queue names starting with floor. are Floor's own.

cx.enqueue("receipts", &Receipt { visit: 812, email: "ali@example.com".into() }).await?;

cx.enqueue_after

pub async fn enqueue_after(
    &self,
    queue: &str,
    payload: &impl Serialize,
    delay: Option<Duration>,
) -> Result<String>

Adds a job that becomes ready after delay; returns its id.

People

cx.grant

pub async fn grant(&self, access: Access) -> Result<Granted>

Gives one of the project's own users a role, or takes it away (their account stays and their sessions end). Someone the project doesn't have yet gets an account and an invite: the answer's invite_url opens the product's own page (its first redirect URL) with #type=invite&token=…, where they set a password with auth.acceptInvite. It works once, so send it to them. It only ever touches this project's users; other projects' users and Floor's operators are apart. The role must be one of the project's roles. See Access and Sign-in.

let g = cx.grant(Access::new("ayesha@example.com", "warden").name("Ayesha Khan").org("stc")).await?;
if let Some(url) = &g.invite_url {
    cx.notify(Notification::email(&g.email).template("welcome").var("link", url)).await?;
}
cx.grant(Access::remove("old.guard@example.com")).await?;

cx.person

pub async fn person(&self, email: &str) -> Result<Option<Person>>

One of the project's users by email: user_id (their tokens' sub), name, status (invited until they set a password, active, or disabled), org and role. None when the project has no user with that address.

cx.disable_person, cx.enable_person

pub async fn disable_person(&self, email: &str) -> Result<Person>
pub async fn enable_person(&self, email: &str) -> Result<Person>

Disables one of the project's users (they can't sign in, and their sessions end) or lets them in again. Enabling someone still invited is a 409: they become active by using their invite link. An address the project has no user for is a 404.

cx.permissions

pub fn permissions(&self) -> Vec<&str>

What the caller's roles allow, from the backend's permissions.rs: for a /api/me answer the dashboard shows or hides things by. Permissions::of_role and for_roles answer the same for any role.

Secrets

cx.secret

pub async fn secret(&self, name: &str) -> Result<Option<String>>

One of the project's secrets, or None when it isn't set. Set them with floor secrets set.

let Some(key) = cx.secret("EXCISE_API_KEY").await? else {
    return Err(Error::Floor("EXCISE_API_KEY isn't set".into()));
};

Messages

cx.notify

pub async fn notify(&self, message: Notification) -> Result<Sent>

Sends an email, a WhatsApp message or a push notification through Floor, which queues it and retries. Returns the message as Floor took it, usually with status queued. See Notification and Messages.

cx.notify(
    Notification::email("ali@example.com")
        .template("visit-approved")
        .var("plate", "LEB-4821"),
)
.await?;
cx.notify(Notification::whatsapp("+923001234567").text("Gate 3 is open")).await?;

Files

The project's blob storage, through signed URLs the caller uses directly. The bytes don't pass through the backend. See Files.

cx.upload_url

pub async fn upload_url(&self, upload: Upload) -> Result<SignedUrl>

A URL the caller uploads one object to, straight to the project's blob storage. See Upload.

let url = cx
    .upload_url(Upload::new(format!("plates/{visit}.jpg"), size).content_type("image/jpeg"))
    .await?;
Ok(Json(url))

cx.download_url

pub async fn download_url(&self, key: &str, expires: Option<Duration>) -> Result<SignedUrl>

A URL to download key from, valid for expires. Floor's default is an hour.

cx.download_url_as

pub async fn download_url_as(&self, key: &str, filename: &str, expires: Option<Duration>) -> Result<SignedUrl>

The same, downloading under filename (Content-Disposition: attachment) rather than the key's name: insurance-LEB-4821.pdf for vehicles/42/0193…. Names outside ASCII are kept for browsers that understand them.

cx.delete_blob

pub async fn delete_blob(&self, key: &str) -> Result<()>

Deletes the object at key.

AI

See AI.

cx.chat

pub async fn chat(&self, chat: Chat) -> Result<ChatAnswer>

Asks a model through Floor's AI module, with the project's key, limits and usage log. See Chat.

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

cx.ocr

pub async fn ocr(&self, image: impl Into<Vec<u8>>) -> Result<Ocr>

The text in a JPEG or PNG, through Floor's OCR service.

let read = cx.ocr(jpeg).await?;
let plate = read.lines.iter().max_by(|a, b| a.confidence.total_cmp(&b.confidence));

Types

These live in floor::services. Notification, Upload and Chat are also at the crate root and in the prelude. They mirror Floor's own API with only the fields a backend needs; fields Floor adds to its answers are ignored.

Notification

pub struct Notification {
    /// `email`, `whatsapp` or `push`.
    pub channel: Option<String>,
    /// An address, a phone number (E.164) or a push token, as the channel needs.
    pub to: String,
    pub from: Option<String>,
    pub template: Option<String>,
    /// `en` or `ur`.
    pub lang: Option<String>,
    pub vars: Map<String, Value>,
    pub subject: Option<String>,
    pub text: Option<String>,
    pub html: Option<String>,
    /// The same key again (within 30 days) sends nothing new and returns the first message.
    pub idempotency_key: Option<String>,
    /// Push only: JSON for the app.
    pub data: Option<Value>,
}

A message to send. Start with email, whatsapp or push, then give a template or a text. Each builder method takes self and returns it.

MethodSets
Notification::email(to: impl Into<String>) -> Selfan email to an address
Notification::whatsapp(to: impl Into<String>) -> Selfa WhatsApp message to a phone number in E.164
Notification::push(to: impl Into<String>) -> Selfa push notification to a push token
.template(name: impl Into<String>)the template to send
.var(name: impl Into<String>, value: impl Serialize)one template variable
.lang(lang: impl Into<String>)the template's language, en or ur
.subject(s: impl Into<String>)an email's subject, without a template
.text(s: impl Into<String>)the text, without a template
.html(s: impl Into<String>)an email's HTML, without a template
.idempotency_key(k: impl Into<String>)a key that makes sending again a no-op for 30 days
.data(v: impl Serialize)JSON for the app, on a push

from has no builder method; set the field.

Notification::email("ali@example.com")
    .template("visit-approved")
    .lang("ur")
    .var("plate", "LEB-4821")
    .var("gate", 3)
    .idempotency_key(format!("visit-approved-{visit}"))

Sent

pub struct Sent {
    pub id: String,
    pub channel: String,
    /// `queued`, `sent`, `delivered`, … (usually `queued` at first).
    pub status: String,
}

A message Floor took: it is queued and sent, with retries, by Floor's messaging service.

Upload

pub struct Upload {
    pub key: String,
    pub size: Option<u64>,
    pub content_type: Option<String>,
    /// Seconds; Floor's default is 900.
    pub expires_in: Option<u64>,
}

An upload URL's terms. The upload must be exactly size bytes, which count toward the project's quota, and, with content_type, send that type.

MethodSets
Upload::new(key: impl Into<String>, size: u64) -> Selfthe key and the exact size
.content_type(t: impl Into<String>)the type the upload must send
.expires_in(d: std::time::Duration)how long the URL works (at least a second)

SignedUrl

pub struct SignedUrl {
    pub url: String,
    pub method: String,
    pub headers: BTreeMap<String, String>,
    /// RFC 3339.
    pub expires_at: String,
}

A presigned request to blob storage: send method to url with headers.

DeviceInfo

pub struct DeviceInfo {
    pub hardware_id: String,
    pub name: String,
    pub kind: String,
    /// `pending`, `active` or `revoked`.
    pub status: String,
    /// Its key's SHA-256, to compare with the device before approving it.
    pub key_fingerprint: String,
    /// Connected to Floor's broker now.
    pub online: bool,
    pub last_seen_at: Option<String>,
    pub firmware_version: Option<String>,
    /// What it last published on its `health` topic.
    pub health: Option<Value>,
    pub labels: Map<String, Value>,
}

One of the project's devices, as Floor knows it.

ClaimCodes

ClaimCodes::new(count)          // 1-500
    .label("batch 7")
    .auto_approve()             // devices that claim with one join as active
    .max_uses(1)                // uses per code; 1 by default
    .expires_in_days(30)

The answer, CreatedClaimCodes, has codes: Vec<String>.

CameraInfo

pub struct CameraInfo {
    pub name: String,
    pub label: String,
    /// The device that pushes it.
    pub device: String,
    /// `live`, `weak`, `starting`, `offline` or `idle`.
    pub status: String,
    pub on_demand: bool,
    pub record: bool,
    /// Viewers watching now.
    pub readers: i64,
}

Lease

pub struct Lease {
    pub id: String,
    pub viewer: String,
    pub cameras: Vec<LeaseCamera>,   // name, label, whep_url
    /// Bearer token for the players: read (WHEP) on these cameras only.
    pub token: String,
    pub token_expires_at: String,
    pub expires_at: Option<String>,
    pub renew_every_secs: u64,
}

Access

Access::new(email, role)        // give `role` in this project
    .name("Ayesha Khan")        // their name, for someone new
    .org("stc")                 // their organization, for someone new
Access::remove(email)           // no role in this project any more (their sessions end)

The answer, Granted, has user_id, email, role (in this project, now), status (invited until they set a password, then active) and invite_url (when the grant invited them).

DeviceConfig

pub struct DeviceConfig {
    pub device: String,
    pub version: i32,
    pub desired: Map<String, Value>,
    pub reported: Option<Map<String, Value>>,
}

A device's config after a change: what Floor wants it to have (desired, published retained) and what the device last reported.

Chat

pub struct Chat {
    /// Floor's default model when `None`.
    pub model: Option<String>,
    pub system: Option<String>,
    pub messages: Vec<ChatMessage>,
    pub max_tokens: Option<u32>,
    pub effort: Option<String>,
}

A model call through Floor.

MethodSets
Chat::new(prompt: impl Into<String>) -> Selfa chat with one user message
.user(content: impl Into<String>)adds a user message
.assistant(content: impl Into<String>)adds an assistant message
.system(s: impl Into<String>)the system prompt
.model(m: impl Into<String>)the model; Floor's default without it
.max_tokens(n: u32)the longest answer

effort has no builder method; set the field.

ChatMessage

pub struct ChatMessage {
    /// `user` or `assistant`.
    pub role: String,
    pub content: String,
}

ChatAnswer

pub struct ChatAnswer {
    pub text: String,
    /// The model that answered.
    pub model: String,
    pub stop_reason: Option<String>,
}

Ocr

pub struct Ocr {
    /// Lines joined with newlines.
    pub text: String,
    pub lines: Vec<OcrLine>,
}

Text found in an image.

OcrLine

pub struct OcrLine {
    pub text: String,
    pub confidence: f32,
    /// `[x0, y0, x1, y1]` in pixels.
    #[serde(rename = "box")]
    pub bbox: [u32; 4],
}

On this page