Skip to main content

Crate rustlavel_ws

Crate rustlavel_ws 

Source
Expand description

rustlavel-ws: WebSockets and broadcasting, written from scratch on Tokio.

Laravel answers real-time with Echo on the client and Reverb on the server. This is both halves in one crate: an RFC 6455 implementation — handshake, framing, control frames, close handshake — and a Broadcaster with public, private and presence channels on top of it.

§An echo server

ⓘ
use rustlavel_ws::{websocket, WebSocket};

r.get("/ws", websocket(|mut socket, _request| async move {
    while let Some(message) = socket.recv().await {
        let _ = socket.send(message).await;
    }
}));

recv yields whole Messages. Fragments are reassembled, pings are answered, text is checked for UTF-8, and a close is replied to with a close — none of which an application should have to remember.

§Broadcasting

ⓘ
use rustlavel_ws::Broadcaster;

let broadcaster = Broadcaster::new()
    .authorize(|request: &Request, channel: &str| {
        request.extension::<User>().is_some_and(|user| user.may_watch(channel))
    });

r.get("/broadcasting", broadcaster.route());

// From anywhere: a controller, a queued job, a background task.
broadcaster.broadcast("orders", "order.created", Json::object([("id", 7.into())]));

The wire protocol clients speak is documented on broadcast.

§What is reported

ws.connected, ws.message, ws.disconnected and broadcast.sent go to rustlavel_core::events, carrying the channel, counts and durations — and never a payload. A socket’s contents are the application’s business.

Re-exports§

pub use broadcast::Authorizer;
pub use broadcast::Broadcaster;
pub use broadcast::ChannelKind;
pub use broadcast::Member;
pub use broadcast::SubscriberId;
pub use broadcast::authorize_async;
pub use connection::Sender;
pub use connection::WebSocket;
pub use connection::WebSocketConfig;
pub use connection::channel;
pub use error::WsError;
pub use error::WsResult;
pub use frame::CloseCode;
pub use frame::CloseFrame;
pub use frame::Frame;
pub use frame::OpCode;
pub use frame::Role;
pub use handshake::Handshake;
pub use handshake::HandshakeError;
pub use handshake::accept_key;
pub use message::Message;
pub use route::WebSocketRoute;
pub use route::websocket;

Modules§

base64
Base64, needed by the opening handshake.
broadcast
Channels and broadcasting — the Laravel Echo half of this crate.
connection
A live WebSocket connection.
error
What can go wrong once a socket is speaking WebSocket.
frame
RFC 6455 framing: the bytes on the wire.
handshake
The RFC 6455 opening handshake.
message
What an application sends and receives.
route
Mounting a socket on the router.