Skip to content

Messages

The JSON envelope, the #[subscribe_message] signature, the typed payload a message decodes, and the layers each message runs.

Every frame in and out of a gateway rides one shape:

{ "event": "history", "data": [{ "author": "ada", "text": "hi" }] }

event is a string, data is whatever JSON the handler asks for. That’s it — no separate ack channel, no second protocol for errors, no per-event wire format to negotiate. One envelope handles fire-and-forget, request/response, server pushes, and error replies.

The envelope is a JSON object, and only an object: an array is never read by position, so ["message", {…}] is no message. A frame that is no envelope is answered on the error event, saying where it failed, or what kind of value it was and what was expected, and never what it held:

{ "event": "error", "data": { "error": "invalid envelope at `event`: missing", "code": "INVALID_ARGUMENT" } }
{ "event": "error", "data": { "error": "invalid envelope: invalid type: a sequence, expected an object with `event` and `data`", "code": "INVALID_ARGUMENT" } }

A message past max_message_bytes closes the socket 1009 Message Too Big, at the protocol layer, before anything reads it. A binary frame carries no envelope, and a text frame that layer let through at the boundary is not read: each is answered on the error event under the class HTTP names for the same refusal, as RFC 6455’s close codes 1003 and 1009 name it:

{ "event": "error", "data": { "error": "binary frames are not supported", "code": "UNSUPPORTED_MEDIA_TYPE" } }
{ "event": "error", "data": { "error": "message too large", "code": "CONTENT_TOO_LARGE" } }

Each is a message all the same: its ws.message line files outcome="error" under event="_OTHER", since no handler declared what it named. An event no handler serves is answered on the event it sent, unknown event under the NOT_FOUND class.

What a route’s 404 runs, each of these runs too: the unit stage and the app’s exception filters, around that answer and under the message’s deadline, so an audit interceptor reads the frame that goes out and a catch-all shapes it. Nothing there is a handler’s, so no guard, no handler-stage interceptor and no unit of work run, nor what the gateway binds for its messages. A layer reads _OTHER as the event, never the client’s word.

#[subscribe_message("event")] binds a method to that event name in the envelope:

crates/features/src/chat/ws/gateway.rs
#[messages]
impl ChatGateway {
#[subscribe_message("message")]
async fn on_message(&self, msg: SendMessageDto) -> ChatMessageDto {
self.svc.record(msg)
}
}

The macro reads five things from the signature:

  • The event name — the literal in #[subscribe_message(...)].
  • The payload type — the one argument that is neither &WsClient, a Scoped<T> nor an Ambient<T>. Deserialized from envelope.data with serde.
  • The request-scoped providers — each Scoped<T> argument, resolved from the message’s own scope (below).
  • What a guard attached — each Ambient<T> argument, read from what the upgrade’s guards and the message’s own attached, as a route reads it; a #[public] message reading the principal a guard of its chain produces refuses a caller that guard did not identify UNAUTHENTICATED.
  • The return type — drives the reply, per the return contract.

A &WsClient parameter is the per-connection handle; it can appear in any position alongside the payload. The macro tells the four apart by their shape — a reference, a type named Scoped, a type named Ambient, anything else — since it reads tokens, not types; a Scoped or an Ambient of another crate does not compile.

A message is a request of its own: an #[injectable(scope = request)] provider is built once per message and shared by everything that message runs, and a handler takes it as a parameter:

crates/features/src/chat/ws/gateway.rs
use nest_rs::core::Scoped;
#[subscribe_message("seq")]
async fn seq(&self, seq: Scoped<RequestSeq>) -> u64 {
seq.value()
}

Scoped<T> is part of the boot’s access contract, as an #[inject] field is: a T no module the gateway’s module imports offers fails the boot, naming it. With no request-scoped provider anywhere in the app, every message shares one scope, which has nothing to build.

A message under its gateway’s #[use_guards], the app’s pool or a guard of its own needs no posture: the guards decide, as on a route. #[public] opens one on purpose, and #[authorize(Action, Entity)] gates it and judges each row it answers — Message posture.

Whatever you put in data arrives in your handler typed, and held to the rules its type declares. The macro decodes it through the edge’s own reader under the hood:

crates/features/src/chat/ws/gateway.rs
#[input]
struct SendMessageDto {
text: String,
}
#[subscribe_message("message")]
async fn on_message(&self, msg: SendMessageDto) { /* ... */ }

The payload carries what the client decides, and nothing the server already knows: who sent the message is the caller the upgrade authenticated, read as an Ambient<Claims> parameter, never an author field the client could fill with someone else’s name. #[input] refuses a field the type does not declare, so such a payload is an error frame.

A malformed payload (wrong shape, missing fields) is treated as a dispatch error: the connection stays open, the client receives an error frame on the same event name (error frames), naming where the payload failed and never its value — invalid payload for `message` at `text`: missing. A payload type declaring validator rules is held to them as it decodes, and a custom transform binds a pipe on the payload argument, Piped<P> — either rejection is an error frame, and the handler body never runs.

crates/features/src/chat/ws/gateway.rs
#[subscribe_message("trim")]
async fn trim_handler(&self, Piped(name): Piped<Trim>) -> String {
name
}

A handler that takes no payload accepts null or a missing data key — the envelope defaults data to null on deserialize:

crates/features/src/chat/ws/gateway.rs
#[subscribe_message("history")]
async fn history(&self) -> Vec<ChatMessageDto> {
self.svc.history()
}
Terminal window
> {"event":"history","data":null}
< {"event":"history","data":[{"author":"ada","text":"hi"}]}

The handler’s return type picks the reply: () none, T one frame on the event, Result an error frame for an Err, whose type decides what the client reads — Replies and error frames.

A message runs through the same pipeline a route does, outermost first: the unit stage (#[interceptor(stage = unit)]), the guard stage — the app’s pool, the message’s #[use_guards], then the class gate its posture declares — the exception filters (the message’s, the gateway’s, the app’s), the handler stage (the app’s interceptors, the gateway’s, the message’s), and last the message itself: its data pipes, its payload’s own pipe, and the call.

Bound on the #[gateway] struct, a layer runs around every message of the gateway; bound beside a #[subscribe_message], around that one. Each runs once per message, whichever scopes list it:

crates/features/src/catalog/ws/gateway.rs
use std::sync::Arc;
use nest_rs::ws::{gateway, messages};
#[gateway(path = "/ws/catalog")]
#[use_guards(AuthnGuard)]
#[use_interceptors(Timing)]
#[use_exception_filters(OutOfStockFilter)]
pub struct CatalogGateway {
#[inject]
svc: Arc<CatalogService>,
}
#[messages]
impl CatalogGateway {
#[subscribe_message("buy")]
#[use_pipes(StripUnknownFields)]
async fn buy(&self, order: OrderDto) -> Result<ReceiptDto, OutOfStock> {
self.svc.buy(order).await
}
}

An exception filter reads the handler’s error by its type and answers the client in place of the frame the error would have answered — a Caught::Problem as { "error": …, "code": … }, or a reply it writes through WsView::respond. The message still failed, so whatever it wrote rolls back, and its span still says who failed. An interceptor reads the message through WsView — its connection, its event, its data — and the reply once the rest of the message ran; one may answer the message itself with WsView::respond and skip the rest.

The global pipes the app lists fold over every message’s data, after its guards and its gate; #[use_pipes] adds pipes for one gateway or one message, each once. A rejection is an error frame, as a payload’s own pipe’s is.

The connection hooks run no layer yet: #[use_interceptors] and #[use_exception_filters] beside #[on_connect] are named compile errors, as are a guard (the upgrade’s guards admitted the socket), a pipe (a hook has no payload), a #[meta] value (no layer would read it) and a posture (no gate stands before a hook, so it reads nothing a grant guards).

If you ever need to build or parse a frame by hand (a custom adapter, a test harness), nest_rs::ws::WsEnvelope is the canonical shape:

nest_rs::ws::WsEnvelope
use nest_rs::ws::WsEnvelope;
let frame = WsEnvelope::encode("ping", &"pong")?;
let parsed: WsEnvelope = serde_json::from_str(&frame)?;
assert_eq!(parsed.event, "ping");

A missing data key decodes to serde_json::Value::Null, so older clients sending bare {"event":"ping"} still hit handlers that take no payload. Only an object decodes: serde_json::from_str::<WsEnvelope> refuses an array as it refuses a string, rather than reading its items as the fields.

  • Rooms — server→client pushes via WsClient.
  • Server-side push — emit without holding a client.
  • Guards — reject envelopes before dispatch.