Skip to Content

Triggers

Handle MQTT messages, device events, ticks, cron schedules, queue jobs and long-running tasks.

A trigger is anything that runs a handler other than an HTTP request: a message from a device, a device going offline, a tick, a nightly schedule, a job on a queue. Trigger handlers live in on/ and jobs/. floord delivers each trigger over the Floor link, and the handler's result acks it.

AttributeRuns onTakes
#[mqtt("+/events")]MQTT messages inside the projectMqtt<T> or MqttRaw
#[device(online, offline)]Device eventsDeviceEvent
#[every("30s")]A ticknothing but cx
#[cron("15 3 * * *")]A schedulenothing but cx
#[job(queue = "receipts")]Jobs on one of the project's queuesJob<T>
#[background]A task that runs while the version is liveStop

Where they go is up to you, but a trigger in api/ fails the build. The usual layout is on/ for events (on/mqtt/events.rs, on/presence.rs) and jobs/ for ticks, schedules and queue jobs.

Acks and delivery

A trigger handler returns Result<()>:

  • Ok(()) acks the trigger.
  • Err is logged and counted, and the trigger is acked with the error's message. An MQTT message or device event isn't sent again. A job fails, and its queue retries it.

Delivery is at least once. A backend that crashes or restarts before it acks gets the trigger again (or the next backend does). So a handler that changes data should notice something it has already seen. The gate keeps each plate event's id:

let seen: Option<String> = sqlx::query_scalar("select action from edge_events where event_id = $1")
    .bind(&e.event_id)
    .fetch_optional(&mut *tx)
    .await?;
if seen.is_some() {
    return Ok(());
}

While no version of the backend is live (during a restart, say), its triggers wait in floord, up to 10,000, the oldest dropped first.

A trigger has no caller. cx.user() and cx.org() are errors inside a trigger handler. Take the organization from your own data, as the gate does from the lane.

MQTT messages

// on/mqtt/events.rs
use floor::prelude::*;

#[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 "dev-1" for sac/dev-1/events
    // …
    Ok(())
}
  • The filter is inside the project's prefix. In project sac, +/events hears sac/+/events, and # hears sac/#. A filter that starts with / or $ doesn't compile. + is one level; # is the rest.
  • Mqtt<T> parses a JSON payload into T. It has topic (the full topic, sac/dev-1/events), device (the level after the project, by Floor's topic layout), body and retain. A payload that doesn't parse is an error ack that says why.
  • MqttRaw gives the payload as bytes, in payload, with the same topic, device and retain.
  • One handler per message: the first filter that matches the topic gets it. Keep filters from overlapping.

A device's messages arrive here only if the device publishes them. The topics a device uses are covered in Devices and MQTT.

Device events

// on/presence.rs
use floor::prelude::*;

#[device(online, offline)]
pub async fn presence(cx: Cx, ev: DeviceEvent) -> Result<()> {
    let Some(device) = ev.device else {
        return Ok(());
    };
    cx.kv_set_json(&format!("presence:{device}"), &serde_json::json!({ "state": ev.event }), None)
        .await
}
  • Events: online, offline, health, config (desired or reported config changed) and command (a command was sent, answered or timed out). #[device] with no list takes all of them.
  • DeviceEvent has event, device (the hardware id, when the event names one) and data, the event as Floor's realtime devices channel carries it.
  • Every matching handler runs, in turn.

The project's events: #[event]

The events a project's webhooks get also reach its backend: a WhatsApp message coming in, a message delivered or failed, an alert going off.

// on/whatsapp.rs: a guard texts "open gate-3" to the project's WhatsApp number.
use floor::prelude::*;

#[derive(Deserialize)]
pub struct Incoming {
    pub from: String,
    pub text: String,
}

#[event("message.received")]
pub async fn whatsapp(cx: Cx, e: Event<Incoming>) -> Result<()> {
    if let Some(gate) = e.body.text.strip_prefix("open ") {
        cx.command(gate, "open_gate", &serde_json::json!({ "by": e.body.from })).await?;
    }
    Ok(())
}
  • Types: message.received (a WhatsApp message came in: from, from_name, text, type, media, number, received_at), message.status (one of the project's messages was sent, delivered, read or failed), device.online, device.offline, device.command, alert.fired and alert.resolved.
  • Patterns: an exact type, a prefix such as "message.*", or "*". #[event] with none takes every type.
  • Event<T> has kind (the type) and body, the event's data parsed into T (serde_json::Value by default). It's the same data a webhook's body carries.
  • Every matching handler runs, in turn. Events arrive while a version is live; one that comes during a swap waits for the next version, like other triggers.
  • Device presence is simpler with #[device(online, offline)], which also gets health and config.

Ticks: #[every]

// jobs/sweep.rs: visits still inside after 12 hours are closed as expired.
use floor::prelude::*;

#[every("30s")]
pub async fn sweep(cx: Cx) -> Result<()> {
    sqlx::query(
        "update visits set status = 'expired'
         where status = 'inside' and entry_at < now() - interval '12 hours'",
    )
    .execute(cx.db())
    .await?;
    Ok(())
}
  • The interval is a number with ms, s, m or h, at least 100ms.
  • One run at a time. A tick that comes due while the last run is still going is skipped. Ticks are never queued or sent twice.
  • The name is the file and the function: jobs/sweep.rs's sweep is sweep.sweep, and jobs/ocr-sweep.rs's sweep is ocr_sweep.sweep. Tests and logs use it.

A tick that falls while no version is live doesn't run. For work that must happen, use #[cron].

Schedules: #[cron]

// jobs/prune.rs: plate event ids older than 30 days go, every night at 03:15.
use floor::prelude::*;

#[cron("15 3 * * *")]
pub async fn prune(cx: Cx) -> Result<()> {
    let n = sqlx::query("delete from edge_events where at < now() - interval '30 days'")
        .execute(cx.db())
        .await?
        .rows_affected();
    floor::tracing::info!(events = n, "pruned old edge events");
    Ok(())
}
  • The schedule has five fields (minute, hour, day, month, weekday), or is @hourly, @daily, @weekly, @monthly or @yearly.
  • The time zone is Asia/Karachi. Give another one with tz: #[cron("@daily", tz = "UTC")].
  • Runs are jobs. When a version goes live, Floor sets the project's cron entries to exactly its schedules, named floor.<name>, and removes the ones it dropped. Each run is a job on the queue floor.cron.<name>, delivered one at a time. A run that falls during a deploy or a restart waits and runs on the new version.
  • The name is the tick name (prune.prune), lowercased; it must be 53 characters or fewer.

Queue jobs: #[job]

// jobs/receipts.rs: a receipt for each paid visit, one job each.
use floor::prelude::*;

#[derive(Deserialize)]
pub struct Receipt {
    visit: i64,
}

#[job(queue = "receipts", concurrency = 2)]
pub async fn send(cx: Cx, job: Job<Receipt>) -> Result<()> {
    let exists: Option<i64> = sqlx::query_scalar("select id from visits where id = $1")
        .bind(job.body.visit)
        .fetch_optional(cx.db())
        .await?;
    if exists.is_none() {
        // An Err fails the job; the queue tries it again later.
        return Err(Error::not_found(format!("visit {} is gone", job.body.visit)));
    }
    // … send the receipt
    Ok(())
}

Add jobs from any handler:

cx.enqueue("receipts", &serde_json::json!({ "visit": visit })).await?;
cx.enqueue_after("receipts", &serde_json::json!({ "visit": visit }), Some(std::time::Duration::from_secs(60))).await?;
  • Job<T> has id, attempt (from 1) and body, the payload parsed into T.
  • concurrency is how many of the queue's jobs this backend runs at once: 1 to 64, default 1.
  • Ok completes the job. Err fails it, and the queue retries it with backoff until its attempts run out. A backend that drops fails its running jobs at once, so they're retried soon.
  • Queues need no setup: a queue exists once it has a job. Names are 1 to 64 characters of a-z, 0-9, ., _ and -. Names starting with floor. are Floor's own, and the backend refuses to start with a handler on one.
  • One handler per queue. Two handlers on the same queue stop the backend at start.
  • Payloads are JSON, up to 256 KiB. Put larger data in KV or blob storage and pass its key.

enqueue returns the job's id. See Cx for both calls.

Background tasks: #[background]

A background task is for work that holds something open: a connection to a camera's event stream, a loop that arbitrates between lanes. It starts when the version goes live and gets told to stop when a newer version takes over or the backend shuts down.

// on/arbiter.rs
use floor::prelude::*;

#[background]
pub async fn arbiter(cx: Cx, mut stop: Stop) -> Result<()> {
    loop {
        tokio::select! {
            _ = stop.stopped() => return Ok(()),
            _ = tokio::time::sleep(std::time::Duration::from_secs(1)) => {
                // … one round of work with cx
            }
        }
    }
}
  • Stop has stopped().await, which waits until it's time to stop, and is_stopped().
  • It runs once. If it returns, it isn't started again; an Err is logged.
  • It runs only when connected to Floor, in the live version. Tests don't start it.
  • tokio here is the crate's own dependency: add it to [dependencies] to use its timers.

Make one with the CLI

floor new mqtt events --filter "+/events"      # on/mqtt/events.rs
floor new job sweep --every 30s                # jobs/sweep.rs
floor new job prune --cron "15 3 * * *"        # jobs/prune.rs
floor new job receipts --queue receipts --concurrency 2

Each writes a handler that does nothing yet. See The dev loop.

Test them

TestApp runs a trigger's handler and returns what its ack would say:

t.mqtt("dev-1/events", &json!({ "event_id": "e1", "lane_id": 1, "plate": "LEB-4821" })).await.unwrap();
t.tick("sweep.sweep").await.unwrap();
t.cron("prune.prune").await.unwrap();
t.job("receipts", &json!({ "visit": 7 })).await.unwrap();
t.device("online", json!({ "type": "device.online", "device": "dev-1" })).await.unwrap();

See Testing.

On this page