Skip to main content

Crate smeltery_anvil

Crate smeltery_anvil 

Source
Expand description

§smeltery-anvil

Anvil, the real-time layer of the Smeltery framework: a WebSocket server inside the app that speaks the Pusher Channels protocol 7, events broadcast from handlers, jobs and Watchfire agents, and channel authorization. pusher-js, laravel-echo and the Pusher client libraries for other platforms connect to it with a custom host.

Apps use it through the facade, as smeltery::anvil:

use serde::Serialize;
use smeltery::anvil::prelude::*;

/// An event: its JSON is the data clients receive.
#[derive(Serialize, BroadcastEvent)]
#[broadcast(private = "orders.{order_id}")]
pub struct OrderShipped {
    pub order_id: i64,
    pub tracking: String,
}

/// `routes/channels.rs`: the public channels and who may join the private ones.
pub fn channels(c: &mut Channels) {
    c.public("news");
    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) };
        // The order's owner, from the database.
        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))
    });
}

/// A handler: send the event to every socket on its channel, except the one that made this request.
async fn ship(anvil: Anvil, socket: Option<SocketId>) -> smeltery::Result<&'static str> {
    anvil
        .send(&OrderShipped { order_id: 7, tracking: "1Z999".into() })
        .except(socket)
        .await?;
    Ok("shipped")
}

fn build(app: smeltery::AppBuilder) -> smeltery::AppBuilder {
    app.anvil(channels).routes(|r| {
        r.post("/orders/ship", ship);
    })
}

§What it does

  • The socket endpoint GET /app/<ANVIL_APP_KEY> answers the WebSocket upgrade itself, on the app’s own port (no extra process). A socket keeps its connection’s place in the server’s limits (SERVER_MAX_CONNECTIONS, SERVER_MAX_CONNECTIONS_PER_IP) and is closed with code 1001 when the app shuts down.
  • A separate socket process: smeltery anvil serves only the socket endpoint (and /up) on ANVIL_SERVER_HOST:ANVIL_SERVER_PORT (127.0.0.1:8080), with the server’s limits and shutdown; the web processes run with ANVIL_IN_SERVE=false and keep the auth endpoints. Events, revocations and presence reach it through the app’s shared PubSub driver.
  • Channels: public channels are declared with c.public(...); a public name that is not declared is refused. Private channels (private-<name>) need a signature from POST /broadcasting/auth, a web route with the session and the CSRF check, which runs the pattern’s callback for the signed-in user; clients with a bearer token (mobile apps, other backends) use POST /api/broadcasting/auth, checked by the app’s stateless guards. When the session or token that authorized a subscription ends, its socket is closed with 4200. Channel names starting with private-encrypted- are refused.
  • Presence channels (presence-<name>, c.presence(...)): the callback names the Member a user joins as; subscribers get the member list and member_added / member_removed once per user, across tabs and processes (the members live in memory, in the database or in Redis, following the app’s PubSub driver).
  • Client events: .whispers() on a private or presence channel lets its subscribers send client-… events to each other (never back to the sender, 10 a second per socket); elsewhere they are refused.
  • Events: #[derive(BroadcastEvent)] names the channels ({field} fills in a field’s value) and the event name (App\Events\<TypeName> by default, #[broadcast(as = "order.shipped")] for another); anvil.send(&event).await delivers it to this process’s sockets and, through the app’s PubSub, to its other processes. anvil.to(Channel::public("news")).event("posted").with(&data).await sends without an event type.
  • Signatures: HMAC-SHA256 under ANVIL_APP_SECRET, by default derived from APP_KEY; each signature is bound to one socket id, one channel and the user it was made for, and is usable for five minutes.
  • Limits: message size, frames per second, subscriptions per socket, sockets per process and per client address, handshakes per client address and minute, a bounded outbox per socket with a write timeout, a ping after silence and a maximum connection age.
  • Sparks listeners: every event delivered in a process also reaches the app’s Sparks components that listen to its channel (#[on("anvil:<channel>", "<event>")]), without JavaScript; see “Listening to broadcasts” in the Sparks section of the Smeltery README.
  • Testing: testing::AnvilSpy records what an app sends, testing::TestSocket connects to the hub without a network, testing::authorize calls the auth endpoint.

The full guide (settings, clients, deployment) is the “Broadcasting” section of the Smeltery README.

§License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Modules§

prelude
The items a routes/channels.rs and event files use: use smeltery::anvil::prelude::*;.
presence_migrations
The presence tables of the database store, for the app’s migration (presence_sockets: one row per socket in a channel; presence_users: one row per member).
testing
Test helpers: record what an app sends (AnvilSpy), connect a socket without a network (TestSocket) and ask the auth endpoint for a signature (authorize).

Structs§

Anvil
The app’s real-time hub: sends events to the sockets subscribed to their channels, in this process and (through the app’s PubSub) in its other processes. A cheap clone; a handler takes it as an argument (anvil: Anvil), jobs and agents get it with Anvil::of.
Channel
A channel an event goes to.
ChannelCtx
What a private channel’s callback knows: the channel, its parameters and who asks.
Channels
The app’s channels, declared in routes/channels.rs and installed with AnvilExt::anvil.
Delivered
What a send reached.
Member
A member of a presence channel: the user’s id (a string on the wire) and the display data every member of the channel receives (user_info).
Named
A named event to explicit channels; with gives its data.
PendingEvent
An event ready to send: await it (anvil.send(&event).await?), optionally after except.
PrivateChannel
A private or presence channel registration, returned by Channels::private and Channels::presence.
Settings
Anvil’s settings, read from .env by Settings::from_env.
SocketId
The socket a request came from: the X-Socket-ID header the client sends with its requests, to leave that socket out of the events the request causes (PendingEvent::except).
To
Events to explicit channels without an event type (Anvil::to).

Enums§

CloseCode
Close codes Anvil sends. pusher-js reconnects after codes below 4000 (with a back-off for 1002-1004), refuses to reconnect after 4001-4099, backs off after 4100-4199 and reconnects at once after 4200-4299: a temporary condition is never closed with a code that stops the client for good.

Traits§

AnvilExt
Installs Anvil on an AppBuilder: .anvil(routes::channels::register) in bootstrap/app.rs.
BroadcastEvent
An event that can be broadcast: its data is what it serializes to (serde attributes decide the fields, and #[serde(skip)] keeps one out), sent to channels under name.

Functions§

valid_channel
Whether name is a channel name: 1 to 164 bytes of A-Z a-z 0-9 _ - = @ , . ;.
valid_socket_id
Whether id has the shape of a socket id: two numbers of 1 to 10 digits joined by ..

Derive Macros§

BroadcastEvent
#[derive(BroadcastEvent)]: implements BroadcastEvent from #[broadcast(...)] (see the trait). Make a struct an Anvil event: implements smeltery::anvil::BroadcastEvent from #[broadcast(...)].