Message handlers with DI
What a WebSocket handler can take as parameters and return, and how dependencies reach a gateway.
A gateway is a #[controller]. Its fields are filled by DI. Each message handler is a method that runs in a fresh execution (one message, see Scopes), so execution-scoped providers are built per message.
Dependencies
Constructor dependencies are fields, as in an HTTP controller (examples/23-ws-gateway):
#[controller]
pub struct Chat {
journal: Dep<Journal>,
}A handler can also take a dependency as a parameter. examples/24-ws-rooms takes Dep<Rooms> that way:
use ulo::{Dep, handlers};
use ulo_ws::{BroadcastError, Payload, Rooms, WsCx};
#[handlers]
#[ulo_ws::gateway(path = "/rooms")]
impl Lobby {
#[ulo_ws::message("join")]
async fn join(&self, room: Payload<String>, cx: WsCx) {
cx.conn().join(room.0).await;
}
/// To every member of the room, whichever process holds the connection.
#[ulo_ws::message("shout")]
async fn shout(&self, shout: Payload<Shout>, rooms: Dep<Rooms>) -> Result<(), BroadcastError> {
rooms.to_room(shout.0.room).emit("shouted", &shout.0.text).await
}
#[ulo_ws::message("ping")]
fn ping(&self) -> &'static str {
"pong"
}
}Shout in that handler is the example's payload struct, a room and a text. Rooms is covered in Rooms and broadcast.
Parameters
Every parameter is an extractor over the message's context. A handler takes any of these, in any order:
| Parameter | Gives |
|---|---|
Payload<T> | The envelope's data, deserialised as T. A missing data key fails the extractor. |
Dep<T> | A provider, resolved in the message's execution. |
Ext<T> | A value a guard wrote into the message's extensions. |
Session<T> | The connection's session, as the type it was declared with. |
WsCx | The message's context: conn() for the connection, extensions() and the rest. |
An extractor failure answers the error envelope and the connection stays open. See Extractors for the shared vocabulary and Valid<..> validation.
A handler is a method: &self or self: Arc<Self>.
Return values
A handler's return value becomes the reply under the message's id:
- A plain value, such as the
Stringinsayabove, is one reply frame. Anything serialisable works. ()sends no data. A message that carried anidis answered{"id":..,"complete":true}.Result<V, E>puts an error on the error side.Econverts intoCallError, as everyClassifytype does, andClassifydecides the errorkindthe client sees.- A stream of
Result<T, E>items,Tserialisable andEconverting intoCallError, sends one frame per item and ends withcomplete. AnErritem ends the stream with the error frame.
A stream handler that borrows self is written with self: Arc<Self>, since the stream has to outlive the call.
Enhancers
#[guards(..)], #[interceptors(..)] and #[meta(..)] apply to gateway handlers as they do to HTTP ones, by type or by value (#[guards(value = Stamp)]). Guards for the connection phase are separate, in the gateway attribute's connect_guards(..). See Request lifecycle.