Skip to Content

WebSockets

Serve a WebSocket from a file in api/ with #[ws], checked like a route, and test it.

A file in api/ with #[ws(…)] serves its path as a WebSocket. Use it for a conversation with one caller: a guard's screen asking for counts, a device streaming readings back. To send the same message to many dashboards, a realtime channel is usually the better tool.

A socket

// api/live.rs  →  /api/live
use floor::prelude::*;
use serde_json::json;

async fn inside(cx: &Cx, org: &str) -> Result<i64> {
    Ok(sqlx::query_scalar("select count(*) from visits where organization = $1 and status = 'inside'")
        .bind(org)
        .fetch_one(cx.db())
        .await?)
}

#[ws(can = "visits:read")]
pub async fn live(cx: Cx, mut socket: Socket) -> Result<()> {
    let org = cx.org()?.to_owned();
    socket.send_json(&json!({ "inside": inside(&cx, &org).await? })).await?;
    while let Some(m) = socket.recv().await {
        match m {
            Message::Text(t) if t == "refresh" => {
                socket.send_json(&json!({ "inside": inside(&cx, &org).await? })).await?;
            }
            _ => socket.send_text("send \"refresh\"").await?,
        }
    }
    Ok(())
}

The handler is pub async fn(cx: Cx, socket: Socket) -> Result<()>. It runs for as long as the connection lasts. When it returns, the connection ends; call socket.close() first for a clean close.

Who may connect

#[ws] takes the same options as a route: public, signed_in, role = "…", roles = "…", can = "…" or device.

  • The check runs before the upgrade, so a refusal is a plain HTTP 401 or 403, and a path nothing serves is a 404.
  • The token comes as Authorization: Bearer …, or as ?access_token=…. Browsers can't set headers on a WebSocket, so a dashboard uses the query:
const ws = new WebSocket(`wss://gate.example.com/api/live?access_token=${token}`)
ws.onmessage = (e) => console.log(JSON.parse(e.data).inside)
ws.onopen = () => ws.send('refresh')
  • Inside the handler, cx.user(), cx.org() and cx.can(…) are the caller, as on a route.

The socket

MethodDoes
recv().awaitThe next message, Message::Text or Message::Binary. None once the caller closes or goes away
recv_json::<T>().awaitThe next message parsed as T: Some(Ok(t)), Some(Err(…)) when it doesn't parse, None when the caller has gone
send_text(t).awaitSends text
send_json(&v).awaitSends v as JSON text
send(Message::Binary(bytes)).awaitSends bytes
close().awaitCloses it; the caller sees a normal close
param("id")A path parameter: id for api/rooms/[id]/live.rs
query::<T>()The query string parsed as T, like a route's Query<T> (repeated keys fill a Vec)
query_string()The query string as it came. Neither has access_token: the token never reaches the handler
  • Pings are answered for you.
  • A socket has no body or time limit. #[ws] doesn't take body or timeout; it lasts as long as the caller stays.
  • A send to a caller who has gone is an error, so ? ends the handler.

Path parameters

A socket's file can have parameters like a route's. Read them with param:

// api/lanes/[lane]/watch.rs  →  /api/lanes/{lane}/watch
#[ws(can = "visits:read")]
pub async fn watch(cx: Cx, mut socket: Socket) -> Result<()> {
    let lane: i64 = socket
        .param("lane")
        .and_then(|l| l.parse().ok())
        .ok_or_else(|| Error::bad_request("lane is a number"))?;
    // …
    Ok(())
}

Query parameters

A browser opens a socket with everything in its URL, so options go in the query:

// /api/ws?lanes=1&lanes=4&previews=true
#[derive(Deserialize)]
pub struct Options {
    lanes: Vec<i64>,
    #[serde(default)]
    previews: bool,
}

#[ws(can = "visits:read")]
pub async fn ws(cx: Cx, mut socket: Socket) -> Result<()> {
    let o: Options = socket.query()?;
    // …
    Ok(())
}

Refusing before the upgrade

A handler that takes an Upgrade instead of a Socket runs before the 101. It can read the query and the caller, and refuse with an ordinary HTTP status:

#[ws(signed_in)]
pub async fn ws(cx: Cx, up: Upgrade) -> Result<()> {
    let o: Options = up.query()?;                 // a bad query is a 400
    if !o.lanes.iter().all(|l| cx.can(&format!("lanes:{l}"))) {
        return Err(Error::forbidden("not your lanes"));   // a 403, no socket
    }
    let mut socket = up.accept().await?;          // the 101, then the socket
    // …
    Ok(())
}

up.param, up.query and up.query_string work as they do on a socket. Returning before accept without an error answers 204. A Socket handler is the same as one that accepts first.

Test it

t.ws(path, token) opens a socket over an in-memory pipe. A refusal comes back as the response the caller would have got:

#[tokio::test]
async fn guards_watch_the_gate() {
    let t = TestApp::start(gate::app()).await;
    assert_eq!(t.ws("/api/live", None).await.err().map(|r| r.status), Some(401));

    let resident = t.sign_in(&["resident"]);
    assert_eq!(t.ws("/api/live", Some(&resident)).await.err().map(|r| r.status), Some(403));

    let guard = t.sign_in(&["guard"]);
    let mut ws = t.ws(&format!("/api/live?access_token={guard}"), None).await.expect("it opens");
    assert_eq!(ws.recv_json().await, Some(json!({ "inside": 0 })));
    ws.send_text("refresh").await;
    assert_eq!(ws.recv_json().await, Some(json!({ "inside": 0 })));
    ws.close().await;
    t.close().await;
}

The test socket has send_text, send_json, recv_text, recv_json (as serde_json::Value) and close. See Testing.

On this page