larust_reverb/lib.rs
1//! A generic WebSocket pub/sub broadcasting server - Larust's port of
2//! `laravel/reverb`. Sibling to, not a replacement for, `larust_live::push`
3//! (`@live(channel) ... @endlive`): that mechanism pushes pre-rendered HTML
4//! fragments to a fixed `[data-live-channel]` DOM element and has no
5//! notion of a named event; this one pushes arbitrary JSON payloads,
6//! tagged with an event name, to whatever JS code on the page chooses to
7//! subscribe (`LarustReverb.channel(name).listen(eventName, callback)`,
8//! not a DOM patch). Deliberately a separate route namespace
9//! (`/__larust_reverb/*`, not `/__larust_push/*`) and a separate channel
10//! registry - an app that pointed both mechanisms at the same channel
11//! name would have `@live`'s client try to DOM-patch a JSON payload, or a
12//! Reverb listener receive raw HTML instead of `{event, data}`, so the two
13//! contracts stay physically separate rather than trying to share one
14//! wire format.
15//!
16//! The channel/broadcast/WebSocket-upgrade plumbing below intentionally
17//! mirrors `larust_live::push`'s own - the same process-wide, lazily
18//! created channel-registry shape, the same connection-limiting
19//! semaphore, the same bounded/validated channel names - duplicated
20//! rather than shared, since it's a small, well-understood mechanism and
21//! the two crates' payload contracts (opaque HTML vs. a JSON envelope)
22//! are different enough that forcing a shared abstraction across them
23//! would cost more clarity than it'd save.
24//!
25//! # Public vs. private channels
26//!
27//! A channel name starting with `private-` requires authorization (see
28//! [`authorize`]); any other name is public - anyone who can reach the
29//! route can subscribe, no different from `@live`'s own channels today.
30//! This is Pusher/Laravel's own real naming convention, not invented here.
31//!
32//! # Deliberately out of scope
33//!
34//! - **No presence channels** - membership tracking, join/leave events,
35//! a `here()`/`joining()`/`leaving()` client API. A real, separate
36//! feature; not attempted in this version.
37//! - **No Pusher-wire-protocol compatibility.** This isn't a drop-in
38//! replacement for `pusher-js` or Laravel Echo - [`authorize`]'s
39//! callback runs directly at WebSocket-upgrade time (the browser
40//! already carries the session cookie to this same-origin request),
41//! not via a separate `POST .../auth` round trip the way real
42//! Pusher/Reverb need to (their split exists because Pusher itself is
43//! a third-party service with no access to the app's own session -
44//! this server *is* the app, so that round trip has no purpose here).
45//! - **No per-channel-pattern authorization registry.** Laravel lets an
46//! app register a separate callback per channel-name pattern
47//! (`Broadcast::channel('orders.{id}', fn ($user, $id) => ...)`). This
48//! crate has one global callback instead - it receives the full
49//! channel name and does its own matching inside - avoiding a
50//! route-pattern-matching mini-DSL for what's usually a handful of
51//! `if`/`match` arms in practice.
52//!
53//! # Example
54//!
55//! ```ignore
56//! // At app boot, next to `larust_support::wire::components()...publish()`:
57//! larust_support::reverb::authorize(|session, channel| async move {
58//! let Ok(Some(user)) = larust_support::auth::user::<User>(&session).await else {
59//! return false;
60//! };
61//! // e.g. "private-orders.42" -> only order 42's own owner may listen.
62//! channel == format!("private-orders.{}", user.id)
63//! });
64//!
65//! // Route registration - shorthand for the pair of `.get(...)` calls this
66//! // crate's own `ReverbPlugin` bundles:
67//! // .plugin(larust_support::reverb::ReverbPlugin)
68//!
69//! // Wherever an order actually ships:
70//! larust_support::reverb::broadcast_event(
71//! &format!("private-orders.{}", order.user_id),
72//! "OrderShipped",
73//! &order,
74//! )?;
75//! ```
76
77use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
78use axum::extract::Path;
79use axum::http::header::CONTENT_TYPE;
80use axum::http::StatusCode;
81use axum::response::{IntoResponse, Response};
82use larust_core::AppError;
83use larust_http::session::Session;
84use serde::Serialize;
85use std::collections::HashMap;
86use std::future::Future;
87use std::pin::Pin;
88use std::sync::{Arc, Mutex, OnceLock};
89use tokio::sync::{broadcast, OwnedSemaphorePermit, Semaphore};
90
91/// See [`larust_live::push`]'s own `CHANNEL_CAPACITY` doc comment - same
92/// "an occasional dropped update under a slow subscriber is an accepted
93/// trade-off" reasoning applies here.
94const CHANNEL_CAPACITY: usize = 32;
95const MAX_CHANNELS: usize = 1_024;
96const MAX_CONNECTIONS: usize = 1_024;
97const MAX_CHANNEL_NAME_BYTES: usize = 128;
98
99/// Channel names starting with this prefix require [`authorize`]'s
100/// callback to allow the subscription; every other name is public.
101/// Pusher/Laravel's own real convention, not invented here.
102const PRIVATE_CHANNEL_PREFIX: &str = "private-";
103
104type ChannelMap = HashMap<String, broadcast::Sender<String>>;
105
106static CHANNELS: OnceLock<Mutex<ChannelMap>> = OnceLock::new();
107static CONNECTIONS: OnceLock<Arc<Semaphore>> = OnceLock::new();
108
109type AuthorizeFn =
110 dyn Fn(Session, String) -> Pin<Box<dyn Future<Output = bool> + Send>> + Send + Sync;
111
112static AUTHORIZER: OnceLock<Box<AuthorizeFn>> = OnceLock::new();
113
114/// Registers the callback deciding whether a `private-`-prefixed channel
115/// may be subscribed to. Called with the current request's `Session` and
116/// the full channel name (prefix included) at WebSocket-upgrade time,
117/// before the connection is accepted - never called at all for a channel
118/// that isn't `private-`-prefixed (public, unauthenticated by design).
119///
120/// No authorizer registered and a private channel requested is denied
121/// (fail closed, not fail open). Call this once, at app boot - same
122/// registration convention as `larust_support::wire::components()`; a
123/// second call is ignored (logged as a warning) rather than silently
124/// replacing the first, so a duplicate registration is visible instead of
125/// quietly changing which callback governs authorization.
126pub fn authorize<F, Fut>(callback: F)
127where
128 F: Fn(Session, String) -> Fut + Send + Sync + 'static,
129 Fut: Future<Output = bool> + Send + 'static,
130{
131 let boxed: Box<AuthorizeFn> =
132 Box::new(move |session, channel| Box::pin(callback(session, channel)));
133 if AUTHORIZER.set(boxed).is_err() {
134 tracing::warn!(
135 "larust_reverb::authorize() called more than once; ignoring the later registration"
136 );
137 }
138}
139
140fn sender_for(channel: &str) -> Option<broadcast::Sender<String>> {
141 let mut channels = CHANNELS
142 .get_or_init(|| Mutex::new(HashMap::new()))
143 .lock()
144 .unwrap_or_else(|poisoned| poisoned.into_inner());
145 if let Some(sender) = channels.get(channel) {
146 return Some(sender.clone());
147 }
148 if channels.len() >= MAX_CHANNELS {
149 tracing::warn!(
150 channel,
151 max_channels = MAX_CHANNELS,
152 "reverb channel limit reached"
153 );
154 return None;
155 }
156 let sender = broadcast::channel(CHANNEL_CAPACITY).0;
157 channels.insert(channel.to_string(), sender.clone());
158 Some(sender)
159}
160
161/// Broadcasts `event_name`/`payload` - JSON-serialized as `{"event":
162/// event_name, "data": payload}` - to every client currently subscribed
163/// to `channel`. Call this from wherever server state actually changes
164/// (an event listener, a controller action), not from inside the request
165/// rendering the page itself.
166///
167/// A no-op, not an error, when nobody's listening or the channel name is
168/// invalid - the same fire-and-forget tolerance `larust_live::push::
169/// broadcast` already uses: ordinary pub/sub semantics, since nothing
170/// about "zero receivers right now" is actually exceptional. The only
171/// real error case is `payload` failing to serialize.
172///
173/// Not auto-wired to `larust-events::dispatch` - call it explicitly
174/// wherever it belongs, the same way `push::broadcast` and `larust-events`
175/// are bridged today: by hand, in app code, not a framework-level
176/// "ShouldBroadcast" marker trait.
177pub fn broadcast_event<E: Serialize>(
178 channel: &str,
179 event_name: &str,
180 payload: &E,
181) -> Result<(), AppError> {
182 if !valid_channel_name(channel) {
183 tracing::warn!(channel, "refusing broadcast to invalid reverb channel name");
184 return Ok(());
185 }
186 let envelope = serde_json::json!({ "event": event_name, "data": payload });
187 let serialized =
188 serde_json::to_string(&envelope).map_err(|source| AppError::Internal(Box::new(source)))?;
189 if let Some(sender) = sender_for(channel) {
190 let _ = sender.send(serialized);
191 }
192 Ok(())
193}
194
195/// `GET /__larust_reverb/{channel}` - upgrades to a WebSocket and streams
196/// every [`broadcast_event`] call's JSON envelope through, verbatim, for
197/// the lifetime of the connection. Pure server → client push: no client →
198/// server message is ever acted on (an inbound message is only read to
199/// detect the browser tab closing the connection).
200///
201/// A `private-`-prefixed `channel` is checked against [`authorize`]'s
202/// registered callback before the upgrade completes; anything else
203/// subscribes unconditionally, same as `larust_live::push::socket` today.
204pub async fn socket(
205 Path(channel): Path<String>,
206 session: Session,
207 ws: WebSocketUpgrade,
208) -> Response {
209 if !valid_channel_name(&channel) {
210 return (StatusCode::BAD_REQUEST, "invalid reverb channel").into_response();
211 }
212
213 if channel.starts_with(PRIVATE_CHANNEL_PREFIX) {
214 let authorized = match AUTHORIZER.get() {
215 Some(authorize) => authorize(session, channel.clone()).await,
216 None => false,
217 };
218 if !authorized {
219 return StatusCode::FORBIDDEN.into_response();
220 }
221 }
222
223 let permits = CONNECTIONS
224 .get_or_init(|| Arc::new(Semaphore::new(MAX_CONNECTIONS)))
225 .clone();
226 let Ok(permit) = permits.try_acquire_owned() else {
227 return (
228 StatusCode::TOO_MANY_REQUESTS,
229 "reverb connection limit reached",
230 )
231 .into_response();
232 };
233 let Some(sender) = sender_for(&channel) else {
234 return (
235 StatusCode::SERVICE_UNAVAILABLE,
236 "reverb channel limit reached",
237 )
238 .into_response();
239 };
240
241 ws.on_upgrade(move |socket| handle_socket(socket, sender, permit))
242 .into_response()
243}
244
245async fn handle_socket(
246 mut socket: WebSocket,
247 sender: broadcast::Sender<String>,
248 _permit: OwnedSemaphorePermit,
249) {
250 let mut updates = sender.subscribe();
251 loop {
252 tokio::select! {
253 update = updates.recv() => {
254 match update {
255 Ok(json) => {
256 if socket.send(Message::Text(json)).await.is_err() {
257 break;
258 }
259 }
260 Err(broadcast::error::RecvError::Lagged(_)) => continue,
261 Err(broadcast::error::RecvError::Closed) => break,
262 }
263 }
264 incoming = socket.recv() => {
265 if incoming.is_none() {
266 break;
267 }
268 }
269 }
270 }
271}
272
273/// Same bounds/character-set rules as `larust_live::push`'s own
274/// `valid_channel_name` - see its doc comment for the reasoning.
275fn valid_channel_name(channel: &str) -> bool {
276 !channel.is_empty()
277 && channel.len() <= MAX_CHANNEL_NAME_BYTES
278 && channel
279 .bytes()
280 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
281}
282
283const RUNTIME_JS: &str = include_str!("../assets/reverb-runtime.js");
284
285/// `GET /__larust_reverb/runtime.js` - the vendored client runtime, served
286/// from the installed crate itself rather than copied into `public/js/`,
287/// same reasoning as `larust_live::push::runtime_js`.
288pub async fn runtime_js() -> impl IntoResponse {
289 (
290 [(CONTENT_TYPE, "text/javascript; charset=utf-8")],
291 RUNTIME_JS,
292 )
293}
294
295/// The two routes a Reverb-broadcasting app needs, bundled for
296/// [`larust_http::Router::plugin`] - sugar for the `.get`/`.get` pair this
297/// crate's own doc comment example shows an app writing by hand today.
298/// Gated behind the `reverb` Cargo feature one layer up, in
299/// `larust_support::reverb` - this crate itself has no feature flags of
300/// its own, since it only ever compiles when that optional dependency is
301/// pulled in.
302pub struct ReverbPlugin;
303
304impl larust_http::Plugin for ReverbPlugin {
305 fn routes(&self) -> larust_http::Router {
306 larust_http::Router::new()
307 .get("/__larust_reverb/runtime.js", runtime_js)
308 .get("/__larust_reverb/{channel}", socket)
309 }
310}
311
312#[cfg(test)]
313mod tests {
314 use super::*;
315
316 #[test]
317 fn reverb_plugin_contributes_exactly_the_two_routes_an_app_used_to_hand_write() {
318 let routes = larust_http::Router::new().plugin(ReverbPlugin).routes();
319
320 assert_eq!(routes.len(), 2);
321 assert_eq!(routes[0].method, "GET");
322 assert_eq!(routes[0].path, "/__larust_reverb/runtime.js");
323 assert_eq!(routes[1].method, "GET");
324 assert_eq!(routes[1].path, "/__larust_reverb/{channel}");
325 }
326
327 #[test]
328 fn channel_names_are_bounded_and_reject_control_characters() {
329 assert!(valid_channel_name("orders.42_status"));
330 assert!(valid_channel_name("private-orders.42"));
331 assert!(!valid_channel_name(""));
332 assert!(!valid_channel_name("orders/42"));
333 assert!(!valid_channel_name("orders\n42"));
334 assert!(!valid_channel_name(&"a".repeat(MAX_CHANNEL_NAME_BYTES + 1)));
335 }
336
337 #[tokio::test]
338 async fn broadcast_with_no_subscribers_is_a_harmless_no_op() {
339 broadcast_event("nobody-is-listening", "SomeEvent", &serde_json::json!({})).unwrap();
340 }
341
342 #[tokio::test]
343 async fn a_subscriber_receives_the_event_envelope() {
344 let mut rx = sender_for("reverb-lib-test-channel").unwrap().subscribe();
345 broadcast_event(
346 "reverb-lib-test-channel",
347 "OrderShipped",
348 &serde_json::json!({ "id": 42 }),
349 )
350 .unwrap();
351 let received = rx.recv().await.unwrap();
352 assert_eq!(received, r#"{"data":{"id":42},"event":"OrderShipped"}"#);
353 }
354}