Gateways
Declaring a gateway, the message envelope, guards, sessions and the connect and disconnect hooks.
examples/23-ws-gateway is the complete program for this page. Visitor, Speaker, Badge, Journal and Stamp in the snippets are types that example defines, and an execution is the unit of work one call runs in (Scopes).
Declaring a gateway
A gateway is a #[controller] with a #[handlers] impl. #[ulo_ws::gateway(..)] on the impl names the path and settings, and each #[ulo_ws::message("event")] method handles one event.
use ulo::{Dep, Ext, controller, handlers};
use ulo_ws::{Payload, Session};
#[controller]
pub struct Chat {
journal: Dep<Journal>,
}
#[handlers]
#[ulo_ws::gateway(
path = "/chat",
port = own,
session_with = |head: Dep<UpgradeHead>| Visitor {
name: head.headers().get(NAME).and_then(|name| name.to_str().ok()).unwrap_or("anonymous").to_owned(),
badge: OnceLock::new(),
},
connect_guards(value = Admit),
)]
#[guards(value = Stamp)]
impl Chat {
/// Answers the message that carried the same `id`.
#[ulo_ws::message("say")]
fn say(&self, text: Payload<String>, speaker: Ext<Speaker>) -> String {
format!("{}: {}", speaker.0, text.0)
}
/// The badge the connect guard found, as `on_connect` kept it.
#[ulo_ws::message("badge")]
fn badge(&self, visitor: Session<Visitor>) -> String {
visitor.badge.get().cloned().unwrap_or_else(|| "unset".to_owned())
}
}The attribute accepts these keys, all optional except path:
| Key | Meaning |
|---|---|
path = ".." | The gateway's path. |
namespace = ".." | A name rooms can be addressed by: rooms.namespace("lobby"). |
event = ".." | The envelope's event field, "event" unset. "type" for graphql-ws. |
codec = msgpack | Binary MessagePack frames instead of JSON text. |
subprotocols = [..] | What the handshake may echo, in preference order: the first one the client offered. |
refuse = handshake | Refuse a connect with the HTTP status of its error before the 101, instead of a close code after it. |
overflow = drop_oldest | A full outbound queue drops its oldest message instead of closing the connection. |
port = http | own | Which server serves the gateway. Separate port. |
session = T / session_with = .. | The connection's session. See below. |
connect_guards(..) | Guards that run on the upgrade. |
max_message, max_connections, max_inflight, max_outbound, ping_interval, pong_timeout | Limits. |
The message envelope
Text frames carry JSON. With codec = msgpack, binary frames carry MessagePack and the shapes below are the same.
→ {"event":"say","id":1,"data":"hello"}
← {"id":1,"data":"ada: hello"}idis any JSON scalar. It is echoed back byte for byte and matched by equality.- A message without an
idis fire-and-forget: success sends no reply, and a failure answers the error envelope without anid. - A streamed answer sends one frame per item under the
idand ends with{"id":7,"complete":true}. An error item ends the stream with the error frame instead. A handler returning nothing is answered with that samecompleteframe when the message carried anid. - A failure of any kind, an extraction error, a guard, a handler error, a panic or an event nothing handles, answers
{"id":7,"error":{"kind":"..","message":"..","details":[]}}. A frame naming no event answersbad_request, an unknown eventunimplemented. {"event":"cancel","id":7}cancels the message with that id.cancelis reserved:#[ulo_ws::message("cancel")]is a compile error.- Ping, pong and close frames are answered by the protocol layer and never reach a handler.
A request without a data key fails a Payload<T> extractor.
Guards on messages
#[guards(..)] on the impl or on one method adds guards that run before each message. Each message is its own execution, so a guard writes into the message's extensions and the handler reads that value with Ext<T>:
use ulo::{BoxError, Guard};
use ulo_ws::{Ws, WsCx};
/// Runs before every message and names who sent it.
struct Stamp;
impl Guard<Ws> for Stamp {
async fn can_activate(&self, cx: &WsCx) -> Result<bool, BoxError> {
let name = cx.conn().session().get::<Visitor>().map_or_else(|| "nobody".to_owned(), |visitor| visitor.name.clone());
cx.extensions().insert(Speaker(name));
Ok(true)
}
}A guard that returns Ok(false) or an error answers the error envelope. The connection stays open.
Connect guards, OnConnect and the session
The connect phase is one execution per connection. connect_guards(..) entries are Guard<WsConnect> implementations, and they run before OnConnect.
use ulo::{BoxError, Guard};
use ulo_ws::{ConnectCx, WsConnect};
pub struct Admit;
impl Guard<WsConnect> for Admit {
async fn can_activate(&self, cx: &ConnectCx) -> Result<bool, BoxError> {
let badge = cx.head().headers().get(BADGE).and_then(|badge| badge.to_str().ok()).unwrap_or("guest");
cx.extensions().insert(Badge(badge.to_owned()));
Ok(true)
}
}OnConnect runs after the connect guards admit and may refuse. It is implemented on the gateway type:
use ulo_ws::{ConnectCx, ConnectRefused, OnConnect};
impl OnConnect for Chat {
async fn on_connect(&self, cx: &ConnectCx) -> Result<(), ConnectRefused> {
let name = cx.conn().session().get::<Visitor>().map_or_else(|| "nobody".to_owned(), |visitor| visitor.name.clone());
self.journal.record(format!("connected {name}"));
let badge = cx.ext::<Badge>().map_or_else(|_| "missing".to_owned(), |badge| badge.0.clone());
if let Some(visitor) = cx.conn().session().get::<Visitor>() {
let _ = visitor.badge.set(badge);
}
Ok(())
}
}Two rules this example demonstrates:
- The connect phase's extensions reach
OnConnectonly. A message is a separate execution, so a value the connect guard produced is not in a later message's extensions.on_connectcopies it into the session, which every message of the connection can read. - The session is built from the upgrade head before any guard runs. A field written afterwards, by a guard or by
on_connect, needs interior mutability. The example uses aOnceLock.
session = T builds a session from T::default(). session_with = |head: Dep<UpgradeHead>| .. builds it from the upgrade request, as above. A session is a typed store (session().get::<T>()), is dropped with the connection and is empty on a reconnect.
Refusing a connection
ConnectRefused carries a close code and a reason. ConnectRefused::kind(kind, reason) maps an ErrorKind to a code through CloseCode::of_kind: Unauthorized to 3000, Forbidden to 3003, Timeout to 3008, BadRequest, NotFound, Conflict and Unprocessable to 1008, TooManyRequests and Unavailable to 1013, and every other kind to 1011. The close-code table lists the reasons. ConnectRefused::code(code, reason) takes a CloseCode and sets it explicitly, as graphql-transport-ws does with 4401. It returns a Result and refuses a reason over 123 bytes with CloseCodeError. CloseCode::new(u16) refuses, with the same error, 1004, 1005, 1006 and 1015, the unassigned 1016 to 2999 and anything outside 1000 to 4999.
A failing connect guard refuses the same way. By default the refusal is a close frame after the 101, the one a browser can read. refuse = handshake answers before the upgrade with the status and headers HTTP gives the error, for non-browser clients and proxy logs. Unauthorized is 401 with the WWW-Authenticate of the error or, when it names none, the challenge of the HTTP server or embedding serving the port (Bearer unset), or Bearer on a gateway's own port, Forbidden 403, TooManyRequests 429 and Unavailable 503, each with Retry-After when the error carries a RetryAfter detail. WithHttpStatus overrides the status. A connection over max_connections and a connect during the drain are 503 with Retry-After: the HTTP server's shed_retry_after on its port, one second on a gateway's own port. A refusal written with ConnectRefused::code has no kind and answers 403.
OnDisconnect and AfterInit
use ulo_ws::{Connection, DisconnectReason, OnDisconnect};
impl OnDisconnect for Chat {
async fn on_disconnect(&self, conn: &Connection, why: DisconnectReason) {
let name = conn.session().get::<Visitor>().map_or_else(|| "nobody".to_owned(), |visitor| visitor.name.clone());
self.journal.record(format!("disconnected {name}: {why:?}"));
}
}on_disconnect runs once for every connection whose OnConnect ran, as a terminal execution without guards. Its failures and panics are logged. The session is still readable. A connection refused or turned away for capacity never connected and gets no on_disconnect.
DisconnectReason (non-exhaustive) says how the connection ended:
| Variant | Cause |
|---|---|
ClientClose { code, reason } | The client sent a Close frame. A frame without a status reads as 1005. |
ServerClose { code } | The gateway closed it: Connection::close, a slow consumer's 1008, a binary frame on a text-only gateway's 1003. |
ProtocolError | A protocol, UTF-8 or message-size error. |
Drain | The server's shutdown, close code 1001. |
Lost | An I/O error, a connection closed without a Close frame, or a Pong that missed pong_timeout. |
RuntimeShutDown | The runtime timing the keep-alive shut down. |
AfterInit runs once per gateway after listen() returns, with a GatewayRef giving the path() and namespace(). It is a lifecycle call, not an execution.