WebSocket
Gateways, connection hooks, message handlers, rooms and cross-process broadcast on ulo-ws.
ulo-ws is the WebSocket transport. A gateway is a struct with message handlers, written with the same #[handlers], Dep<T> and guard vocabulary as an HTTP controller. The crate knows the protocol and owns no socket: a server over a runtime's listener accepts the connections.
What a gateway has
- Messages. Each client message names an event and optionally an
id. The reply carries the sameid. Handlers take extractors (Payload<T>,Dep<T>,Ext<T>,Session<T>) and return a value, aResultor a stream. - A connection phase. Connect guards and an
OnConnecthook can admit or refuse an upgrade.OnDisconnectruns once a connected client has gone. - Sessions. A typed store that lives as long as the connection.
- Rooms and broadcast.
Dep<Rooms>addresses every connection of every gateway, from a WebSocket handler or from an HTTP one. - Limits. Message size, connection count, in-flight messages and outbound queue are set per gateway.
Where the server comes from
| Gateway declared | Served by | Crate |
|---|---|---|
default (port = http) | the HTTP server's port, through an upgrade hand-off | WsModule, with an HTTP server that supports upgrades |
port = own | a standalone WebSocket server on its own port | ulo-ws-hyper |
Both run the same handshake and the same connection driver, so a gateway behaves the same on either. Separate port covers the choice.
Pages
- Gateways: messages, the wire format, guards, sessions and the connection hooks.
examples/23-ws-gateway. - Message handlers with DI: what a handler can take and return.
- Rooms and broadcast: joining rooms,
Rooms, pushing from HTTP.examples/24-ws-rooms. - Redis broadcast: one broadcast reaching connections held by several processes.
- Separate port:
port = ownandulo-ws-hyper. - Limits and shutdown: close codes, load shedding and the drain.
Setup
An application imports WsModule once, next to its gateways. examples/24-ws-rooms binds the HTTP server beside it:
use ulo::module;
use ulo_ws::WsModule;
#[module(imports = [WsModule::for_root()], providers = [Journal], controllers = [Chat])]
pub struct AppModule;WsModule::for_root() registers the upgrade hand-off, binds Rooms and the in-memory broadcast adapter, and carries the defaults for every gateway on the HTTP port. Without it a gateway on the HTTP port is reachable by nothing, and Dep<Rooms> is a missing dependency at wire().
(The module line is from examples/23-ws-gateway/src/lib.rs.)