Smeltery
Get started

Anvil (broadcasting)

v0.1

Channels

On this page
  • Public channels are declared with c.public(pattern). Anyone with the app key can subscribe to them, so their events are public. A public name that matches no declared pattern is refused (pusher:subscription_error with status 403).
  • Private channels are private-<name>, declared with c.private(pattern, callback) (the pattern without the prefix: orders.{order} serves private-orders.7). Before it subscribes, the client posts socket_id and channel_name (form fields or JSON) to /broadcasting/auth with the session cookie and the CSRF token (X-CSRF-TOKEN, X-XSRF-TOKEN or _token). The callback decides; Ok(true) answers 200 with {"auth": "…"}, which the client sends with its subscription.
  • Patterns are dot-separated; {name} matches one segment of letters, digits and _ - = @ , ;. A channel name is 1 to 164 characters of letters, digits and _ - = @ , . ;.
  • Guests are refused before the callback runs; .guests() on a private registration lets them through (ctx.user_id() is None).
  • No matching pattern, a guest, Ok(false), and an error from the callback with a 4xx status (a parameter that does not parse, a record not found) all answer the same 403 {"error":"Forbidden"}, so the endpoint never tells which channels exist. An error with a 5xx status is logged and answered with that status. Every answer carries Cache-Control: no-store.
  • Channel names starting with private-encrypted- are refused.

ChannelCtx gives the callback:

Method Returns
ctx.param::<T>("order") the pattern parameter, parsed (a value that does not parse is a 403)
ctx.user_id() the signed-in user's id, None for a guest
ctx.user::<User>().await? the signed-in user (loaded once)
ctx.db()? the app's database
ctx.app(), ctx.channel(), ctx.socket_id() the app, the full channel name, the socket that subscribes

The signature in auth is HMAC-SHA256 under ANVIL_APP_SECRET (by default a secret derived from APP_KEY), over the socket id, the channel and who was authorized (the user id, a hash naming the session or the token's id, the time it was made and an expiry five minutes ahead). It works only for that socket and that channel, and only within those five minutes; the server checks it in constant time.

Presence channels#

A presence channel (presence-<name>) is a private channel whose members see each other: who is in a chat room, who is looking at a document. c.presence(pattern, callback) declares it; the callback returns the Member the user joins as, or None to refuse:

rust
use smeltery::anvil::{ChannelCtx, Channels, Member};
use smeltery::json;

pub fn channels(c: &mut Channels) {
    c.presence("rooms.{room}", |ctx: ChannelCtx| async move {
        let room: i64 = ctx.param("room")?;
        let Some(user_id) = ctx.user_id() else { return Ok(None) };
        // … check that the user may enter room `room` …
        let _ = room;
        Ok(Some(Member::new(user_id).info(json!({ "name": format!("User {user_id}") }))))
    })
    .whispers();
}
  • A member is a user id (a number becomes its decimal string; 1 to 128 bytes) and user_info, which every member of the channel receives: give display fields only (a name, an avatar URL), never an email address or anything private.
  • Authorizing works as for private channels (the same two endpoints, the same 403 rules, .guests()); the answer is 200 {"auth": "…", "channel_data": "{\"user_id\":\"7\",\"user_info\":{…}}"} and the client sends both with its subscription. The signature covers channel_data, so a client cannot change who it appears as. A callback that returns a member whose channel_data is larger than ANVIL_MAX_MEMBER_BYTES (1,024), or whose user id is empty or longer than 128 bytes, gets a 500 (logged) and no signature.
  • Subscribing answers pusher_internal:subscription_succeeded with the members: {"presence": {"ids": ["7", "9"], "hash": {"7": {…}, "9": {…}}, "count": 2}}. One user with several sockets is one member. When a user's first socket joins, the other members get pusher_internal:member_added with {"user_id", "user_info"}; when its last socket leaves (it unsubscribes, its connection closes or drops, it is closed by a revocation, its process shuts down), they get pusher_internal:member_removed with {"user_id"}.
  • Limits: a channel holds at most ANVIL_MAX_PRESENCE_MEMBERS (100) distinct users; a new user beyond that gets pusher:subscription_error with status 403 ("presence channel full"), while sockets of users already in it still join. A socket is in at most ANVIL_MAX_PRESENCE_CHANNELS (10) presence channels and may join 5 at once, then one a second (each join and leave writes to the member store and reaches every member); beyond either it gets status 429.
  • Across processes, the members live where the app's PubSub driver says: in the process's memory with local; with database, in the tables presence_sockets and presence_users (a migration calls smeltery::anvil::presence_migrations::up / down); with redis, in Redis (feature redis). Every serving process marks its members alive every 30 seconds and removes the members of a process unseen for 90 seconds (a crashed process), announcing member_removed; at shutdown a process removes its own. The same heartbeat checks its members against its sockets: a join or leave the database cut off halfway is finished, and members other processes removed while this one could not reach the database come back (with member_added). Apps with many presence members or many client events use PUBSUB_DRIVER=redis: with database, every join, leave and member event is a few rows. With database, the member limit is checked before the join, so joins of new users in several processes at the same moment can pass it together. A socket that joins while another process announces a member can receive that member_added after its member list, for a member already in the list.
  • anvil.members("presence-rooms.1").await? returns the members (every process's) to server code.
  • An event goes to a presence channel's members with Channel::presence("rooms.1") or #[broadcast(presence = "rooms.{room}")].

Client events#

A private or presence registration with .whispers() lets its subscribers send client events to each other (typing indicators, cursors): {"event": "client-typing", "channel": "private-chat.1", "data": …} from a socket subscribed to that channel. laravel-echo sends them with .whisper("typing", data) and receives them with .listenForWhisper("typing", …).

  • The other subscribers of the channel receive it, in every process, with data as it was sent; on a presence channel it also carries the sender's "user_id". The sender never receives its own.
  • A client event never reaches the app's code: it goes from socket to socket.
  • The name starts with client- and is at most 200 bytes; the frame is at most ANVIL_MAX_MESSAGE_SIZE.
  • A socket may send 10 client events a second, and a channel carries at most 100 a second in each process; more are dropped with pusher:error 4301. Keep channels with client events small: each event reaches every other subscriber.
  • On a public channel, a channel the socket is not subscribed to, or a pattern without .whispers(), a client event is answered with pusher:error 4009; the socket stays open.

↑↓ moveEnter openEsc close