Smeltery
Get started

Anvil (broadcasting)

v0.1

Broadcasting

On this page

Anvil (smeltery::anvil) is a WebSocket server inside the app that speaks the Pusher Channels protocol 7, on the app's own port. Handlers, jobs and Watchfire agents send events to channels; clients subscribe to channels and receive them. pusher-js, laravel-echo and the Pusher client libraries for other platforms connect to it with a custom host.

Setup#

bootstrap/app.rs installs it with the app's channels:

rust
use smeltery::anvil::{ChannelCtx, Channels};
use smeltery::prelude::*;

/// `routes/channels.rs`: the public channels and who may join the private ones.
pub fn channels(c: &mut Channels) {
    c.public("news");
    c.public("scores.{game}");
    c.private("orders.{order}", |ctx: ChannelCtx| async move {
        let order: i64 = ctx.param("order")?;
        let Some(user_id) = ctx.user_id() else { return Ok(false) };
        // Look the order up and allow its owner only.
        let rows = ctx
            .db()?
            .query_with("SELECT user_id FROM orders WHERE id = ?", [order.into()])
            .await?;
        let owner: Option<i64> = rows.first().and_then(|row| row.try_get("", "user_id").ok());
        Ok(owner == Some(user_id))
    });
}

pub fn build(app: AppBuilder) -> AppBuilder {
    app.anvil(channels)
}

.anvil(channels) adds:

  • GET /app/<ANVIL_APP_KEY>: the socket endpoint, outside the web stack (no session, no cookies read). The app logs the path at start (anvil: socket endpoint); Anvil::app_key() returns the key.
  • POST /broadcasting/auth: a web route (session and CSRF, throttle:600,1) that signs private subscriptions.
  • POST /api/broadcasting/auth: the same for clients with a bearer token (an API route: no session, no cookie, no CSRF check; throttle:600,1); see Mobile apps and other clients. It answers 404 when the app has no stateless guard.
  • the Anvil service: a handler takes anvil: Anvil; jobs and agents use Anvil::of(&app) or ctx.service::<Anvil>().

An invalid or repeated channel pattern, an invalid ANVIL_* value, or ANVIL_MAX_CONNECTIONS not below SERVER_MAX_CONNECTIONS stops the app at boot.

↑↓ moveEnter openEsc close