rustlavel_ws/lib.rs
1//! rustlavel-ws: WebSockets and broadcasting, written from scratch on Tokio.
2//!
3//! Laravel answers real-time with Echo on the client and Reverb on the server.
4//! This is both halves in one crate: an RFC 6455 implementation — handshake,
5//! framing, control frames, close handshake — and a [`Broadcaster`] with
6//! public, private and presence channels on top of it.
7//!
8//! # An echo server
9//!
10//! ```ignore
11//! use rustlavel_ws::{websocket, WebSocket};
12//!
13//! r.get("/ws", websocket(|mut socket, _request| async move {
14//! while let Some(message) = socket.recv().await {
15//! let _ = socket.send(message).await;
16//! }
17//! }));
18//! ```
19//!
20//! `recv` yields whole [`Message`]s. Fragments are reassembled, pings are
21//! answered, text is checked for UTF-8, and a close is replied to with a close —
22//! none of which an application should have to remember.
23//!
24//! # Broadcasting
25//!
26//! ```ignore
27//! use rustlavel_ws::Broadcaster;
28//!
29//! let broadcaster = Broadcaster::new()
30//! .authorize(|request: &Request, channel: &str| {
31//! request.extension::<User>().is_some_and(|user| user.may_watch(channel))
32//! });
33//!
34//! r.get("/broadcasting", broadcaster.route());
35//!
36//! // From anywhere: a controller, a queued job, a background task.
37//! broadcaster.broadcast("orders", "order.created", Json::object([("id", 7.into())]));
38//! ```
39//!
40//! The wire protocol clients speak is documented on [`broadcast`].
41//!
42//! # What is reported
43//!
44//! `ws.connected`, `ws.message`, `ws.disconnected` and `broadcast.sent` go to
45//! `rustlavel_core::events`, carrying the channel, counts and durations — and
46//! never a payload. A socket's contents are the application's business.
47
48pub mod base64;
49pub mod broadcast;
50pub mod connection;
51pub mod error;
52pub mod frame;
53pub mod handshake;
54pub mod message;
55pub mod route;
56
57pub use broadcast::{Authorizer, Broadcaster, ChannelKind, Member, SubscriberId, authorize_async};
58pub use connection::{Sender, WebSocket, WebSocketConfig, channel};
59pub use error::{WsError, WsResult};
60pub use frame::{CloseCode, CloseFrame, Frame, OpCode, Role};
61pub use handshake::{Handshake, HandshakeError, accept_key};
62pub use message::Message;
63pub use route::{WebSocketRoute, websocket};
64
65#[cfg(test)]
66mod testing;