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 anvilserves only the socket endpoint (and/up) onANVIL_SERVER_HOST:ANVIL_SERVER_PORT(127.0.0.1:8080), with the server’s limits and shutdown; the web processes run withANVIL_IN_SERVE=falseand 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 fromPOST /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) usePOST /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 withprivate-encrypted-are refused. - Presence channels (
presence-<name>,c.presence(...)): the callback names theMembera user joins as; subscribers get the member list andmember_added/member_removedonce 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 sendclient-…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).awaitdelivers 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).awaitsends without an event type. - Signatures: HMAC-SHA256 under
ANVIL_APP_SECRET, by default derived fromAPP_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::AnvilSpyrecords what an app sends,testing::TestSocketconnects to the hub without a network,testing::authorizecalls 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.rsand event files use:use smeltery::anvil::prelude::*;. - presence_
migrations - The presence tables of the
databasestore, 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 withAnvil::of. - Channel
- A channel an event goes to.
- Channel
Ctx - What a private channel’s callback knows: the channel, its parameters and who asks.
- Channels
- The app’s channels, declared in
routes/channels.rsand installed withAnvilExt::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;
withgives its data. - Pending
Event - An event ready to send: await it (
anvil.send(&event).await?), optionally afterexcept. - Private
Channel - A private or presence channel registration, returned by
Channels::privateandChannels::presence. - Settings
- Anvil’s settings, read from
.envbySettings::from_env. - Socket
Id - The socket a request came from: the
X-Socket-IDheader 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§
- Close
Code - 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§
- Anvil
Ext - Installs Anvil on an
AppBuilder:.anvil(routes::channels::register)inbootstrap/app.rs. - Broadcast
Event - An event that can be broadcast: its data is what it serializes to (
serdeattributes decide the fields, and#[serde(skip)]keeps one out), sent tochannelsundername.
Functions§
- valid_
channel - Whether
nameis a channel name: 1 to 164 bytes ofA-Z a-z 0-9 _ - = @ , . ;. - valid_
socket_ id - Whether
idhas the shape of a socket id: two numbers of 1 to 10 digits joined by..
Derive Macros§
- Broadcast
Event #[derive(BroadcastEvent)]: implementsBroadcastEventfrom#[broadcast(...)](see the trait). Make a struct an Anvil event: implementssmeltery::anvil::BroadcastEventfrom#[broadcast(...)].