Anvil (broadcasting)
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_errorwith status 403). - Private channels are
private-<name>, declared withc.private(pattern, callback)(the pattern without the prefix:orders.{order}servesprivate-orders.7). Before it subscribes, the client postssocket_idandchannel_name(form fields or JSON) to/broadcasting/authwith the session cookie and the CSRF token (X-CSRF-TOKEN,X-XSRF-TOKENor_token). The callback decides;Ok(true)answers200with{"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()isNone). - 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 same403 {"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 carriesCache-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:
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 is200 {"auth": "…", "channel_data": "{\"user_id\":\"7\",\"user_info\":{…}}"}and the client sends both with its subscription. The signature coverschannel_data, so a client cannot change who it appears as. A callback that returns a member whosechannel_datais larger thanANVIL_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_succeededwith 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 getpusher_internal:member_addedwith{"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 getpusher_internal:member_removedwith{"user_id"}. - Limits: a channel holds at most
ANVIL_MAX_PRESENCE_MEMBERS(100) distinct users; a new user beyond that getspusher:subscription_errorwith status 403 ("presence channel full"), while sockets of users already in it still join. A socket is in at mostANVIL_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; withdatabase, in the tablespresence_socketsandpresence_users(a migration callssmeltery::anvil::presence_migrations::up/down); withredis, in Redis (featureredis). Every serving process marks its members alive every 30 seconds and removes the members of a process unseen for 90 seconds (a crashed process), announcingmember_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 (withmember_added). Apps with many presence members or many client events usePUBSUB_DRIVER=redis: withdatabase, every join, leave and member event is a few rows. Withdatabase, 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 thatmember_addedafter 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
dataas 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 mostANVIL_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:error4301. 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 withpusher:error4009; the socket stays open.