Skip to content

Rooms

The WsClient handle — join, leave, broadcast, scoped emit_to — and the room semantics behind them.

A room is a label attached to a connection. Connections that share a label receive the same broadcast. There is no per-room object, no configuration, no lifecycle — joining a room means appending a string to a HashSet<String> on your Conn; leaving means removing it. Broadcasting to a room walks the connection registry and filters by membership. That’s the whole model.

The handle you reach rooms through is WsClient: a per-connection struct a handler asks for by adding &WsClient to the signature.

Any #[subscribe_message], #[on_connect], or #[on_disconnect] handler can take &WsClient in any non-receiver position. The macro spots the reference (distinct from an owned payload) and passes the current connection’s handle:

crates/features/src/chat/ws/gateway.rs
use nest_rs::ws::{gateway, messages, WsClient};
#[gateway(path = "/ws")]
#[use_guards(AuthnGuard)]
pub struct ChatGateway;
#[messages]
impl ChatGateway {
#[on_connect]
async fn joined(&self, client: &WsClient) {
client.join("lobby");
}
#[subscribe_message("join")]
async fn join_room(&self, room: String, client: &WsClient) {
client.join(&room);
}
#[subscribe_message("leave")]
async fn leave_room(&self, room: String, client: &WsClient) {
client.leave(&room);
}
}

A connection can sit in any number of rooms at once; a room “exists” exactly as long as one connection holds it. Disconnect drops the membership atomically — no stale rows, no cleanup hook to write.

WsClient exposes four send methods, each scoping a different way:

MethodReaches
client.emit(event, &data)This connection only.
client.to(room, event, &data)Every connection in room.
client.broadcast(event, &data)Every live connection, including this one.
client.registry()The underlying WsServer — for advanced cases.

Every method but registry serializes data with serde and returns a Result: a boolean (one connection) or a count of outboxes that accepted the frame, Err when data does not serialize. A frame an outbox refuses is shed rather than awaited, with one warn on nest_rs::ws, so the dispatch loop never blocks on a slow client.

crates/features/src/chat/ws/gateway.rs
#[subscribe_message("say")]
async fn say(&self, msg: SendMessageDto, client: &WsClient) -> Result<(), WsError> {
client.broadcast("said", &msg).opaque()?;
client.to("lobby", "said", &msg).opaque()?;
Ok(())
}

broadcast reaches every connection on the gateway’s registry, any other gateway sharing it included; to scopes by room. client.to(room, ...) does not require the sender to be in room — a user can post into any room they know the name of, which is why authorization belongs in a guard and not in the membership table.

The chat gateway joins a room at connect, broadcasts peer-visible events and replies with a payload:

crates/features/src/chat/ws/gateway.rs (from the demo, abridged)
#[gateway(path = "/ws")]
#[use_guards(AuthnGuard, AuthzGuard)]
pub struct ChatGateway {
#[inject]
svc: Arc<ChatService>,
}
#[messages]
impl ChatGateway {
#[on_connect]
async fn joined(&self, client: &WsClient) {
client.join("lobby");
self.svc.connected();
}
#[on_disconnect]
async fn left(&self) {
self.svc.disconnected();
}
#[subscribe_message("message")]
#[authorize(Create, Posting)]
async fn on_message(
&self,
caller: Ambient<Claims>,
message: SendMessageDto,
) -> Result<(), WsError> {
self.svc.record(caller.into_inner().sub, message).opaque()?;
Ok(())
}
#[subscribe_message("history")]
async fn history(&self) -> Vec<ChatMessageDto> {
self.svc.history()
}
// …
#[subscribe_message("typing")]
#[authorize(Create, Posting)]
async fn typing(
&self,
caller: Ambient<Claims>,
message: SendMessageDto,
client: &WsClient,
) -> Result<(), WsError> {
let typing = ChatMessageDto {
author: caller.into_inner().sub,
text: message.text,
};
if let Err(e) = client.broadcast("typing", &typing) {
tracing::warn!(target: crate::chat::TARGET, error = %error_message(&e), "broadcast failed");
}
Ok(())
}
}

Each client sends its text alone, {"text":"hi"}. Drive it from two terminals at once, each holding a user’s token, and the picture comes through:

Terminal window
$ websocat ws://localhost:3004/ws # tab A, Ada
{"event":"message","data":{"author":"0192b6f0-7c1e-7a40-9d3e-5f1c2a8b4d61","text":"hi"}}
{"event":"typing","data":{"author":"0192b6f1-02aa-7f13-8c55-1d9e7b3c0a42","text":"..."}}
$ websocat ws://localhost:3004/ws # tab B, Bob
{"event":"typing","data":{"author":"0192b6f1-02aa-7f13-8c55-1d9e7b3c0a42","text":"..."}}
{"event":"message","data":{"author":"0192b6f0-7c1e-7a40-9d3e-5f1c2a8b4d61","text":"hi"}}

The author is the subject of the token the upgrade verified, read from the principal every message on the connection carries — never a name the payload states, so no client speaks as another. message is recorded by the service, which calls WsServer::broadcast("message", ...) from outside the handler — see Server-side push. typing broadcasts through the client handle directly because there is no state to record.

WsClient is great when a handler reacts to a single message. The moment something outside a handler needs to reach connected clients — a scheduled task, an HTTP route, a queue processor — there is no client to thread through. Inject WsServer instead and push without the per-connection handle.

That’s the next page.

  • WsClient — join, leave, emit, to, broadcast, id, registry.