larust_live/push.rs
1//! Genuine server-*pushed* real-time updates - `@live('channel') ...
2//! @endlive` in a template, paired with a [`broadcast`] call wherever
3//! server state actually changes. Deliberately a *different* mechanism
4//! from `@wire`'s reactive components, not a bigger version of the same
5//! one: `@wire` is client-*initiated* (a user's own `wire:model`/
6//! `wire:click`/`wire:submit` triggers an AJAX round-trip that only ever
7//! updates *that visitor's own* view); `@live` is server-*initiated* (any
8//! server-side event pushes an update to *every currently connected
9//! viewer* of that channel, with zero interaction required in any of
10//! their tabs - the live-chat/live-notification case neither `@wire` nor
11//! real Livewire itself can do, since both are built around a
12//! request/response cycle, not a held-open connection).
13//!
14//! Real-time push is the one thing PHP/Laravel genuinely can't do
15//! natively (no long-running process to hold a WebSocket open across
16//! requests - Laravel's own answer is an external system, Echo/Reverb).
17//! Larust has no such constraint: it's already one long-running process,
18//! same as everything else this framework relies on (`larust_orm::pool()`,
19//! `larust-live`'s own component registry), so this is a native fit, not
20//! a bolt-on.
21//!
22//! No component trait, no session state, no server-side struct at all -
23//! deliberately simpler than `@wire`'s `WireComponent` machinery.
24//! `@live(channel) ... @endlive` just renders its body once, normally, at
25//! page-load time (in the *caller's* own scope, same as `@loadonce`'s
26//! body), wrapped in a `<div data-live-channel="...">`. From then on,
27//! whoever calls [`broadcast`] is responsible for constructing new HTML
28//! shaped the same way ([`wrap`] helps) and pushing it to every open
29//! socket on that channel - there's no "component" the framework
30//! re-renders on the app's behalf, since there's nothing for it to
31//! re-render *from* (no stored state to re-render against). This is a
32//! deliberate simplicity trade: the app owns keeping the initial render
33//! and each broadcast payload in sync, in exchange for not needing to
34//! reinvent `@wire`'s stateful-component complexity for what's meant to
35//! be a thin, real-time notification layer.
36
37use axum::extract::ws::{Message, WebSocket, WebSocketUpgrade};
38use axum::extract::Path;
39use axum::http::header::CONTENT_TYPE;
40use axum::http::StatusCode;
41use axum::response::{IntoResponse, Response};
42use std::collections::HashMap;
43use std::sync::{Arc, Mutex, OnceLock};
44use tokio::sync::{broadcast, OwnedSemaphorePermit, Semaphore};
45
46/// How many not-yet-delivered broadcasts a channel buffers before a slow
47/// subscriber starts missing the oldest ones (`RecvError::Lagged`, handled
48/// by just catching up to the newest available message - a dropped
49/// intermediate update is an accepted v1 tradeoff for "the page eventually
50/// reflects the latest state," not a "never miss an update" delivery
51/// guarantee this isn't trying to make).
52const CHANNEL_CAPACITY: usize = 32;
53
54/// Bounds process memory consumed by attacker-controlled channel names.
55const MAX_CHANNELS: usize = 1_024;
56/// Bounds file descriptors/tasks consumed by long-lived WebSocket clients.
57const MAX_PUSH_CONNECTIONS: usize = 1_024;
58const MAX_CHANNEL_NAME_BYTES: usize = 128;
59
60type ChannelMap = HashMap<String, broadcast::Sender<String>>;
61
62static CHANNELS: OnceLock<Mutex<ChannelMap>> = OnceLock::new();
63static CONNECTIONS: OnceLock<Arc<Semaphore>> = OnceLock::new();
64
65/// Process-wide, per-channel-name broadcast sender - same single-process
66/// `OnceLock` shape `larust_orm::pool()`/`larust-live`'s own component
67/// registry already use (this framework has no multi-worker story
68/// anywhere yet). Channels are created lazily on first use (by either a
69/// `broadcast()` call or an incoming WebSocket subscription, whichever
70/// happens first). Their count is bounded by [`MAX_CHANNELS`] so untrusted
71/// subscription paths cannot grow process memory without limit.
72fn sender_for(channel: &str) -> Option<broadcast::Sender<String>> {
73 let mut channels = CHANNELS
74 .get_or_init(|| Mutex::new(HashMap::new()))
75 .lock()
76 .unwrap_or_else(|poisoned| poisoned.into_inner());
77 if let Some(sender) = channels.get(channel) {
78 return Some(sender.clone());
79 }
80 if channels.len() >= MAX_CHANNELS {
81 tracing::warn!(
82 channel,
83 max_channels = MAX_CHANNELS,
84 "live channel limit reached"
85 );
86 return None;
87 }
88 let sender = broadcast::channel(CHANNEL_CAPACITY).0;
89 channels.insert(channel.to_string(), sender.clone());
90 Some(sender)
91}
92
93/// Pushes `html` to every browser tab currently subscribed to `channel`
94/// via an open `@live(...)` WebSocket - call this from wherever server
95/// state actually changes (an event listener, a controller action), not
96/// from inside the request that's rendering the page itself. A no-op, not
97/// an error, when nobody's listening (`Sender::send` returning `Err` only
98/// ever means "zero receivers exist right now"): ordinary fire-and-forget
99/// pub/sub semantics, since there's no reason a broadcast should fail just
100/// because no browser tab happens to have this channel open at the
101/// moment.
102///
103/// `html` should be shaped like the `<div data-live-channel="...">...
104/// </div>` wrapper `@live(...)`'s own initial render produces - see
105/// [`wrap`] for building that shape by hand from a plain HTML fragment.
106pub fn broadcast(channel: &str, html: impl Into<String>) {
107 if valid_channel_name(channel) {
108 if let Some(sender) = sender_for(channel) {
109 let _ = sender.send(html.into());
110 }
111 } else {
112 tracing::warn!(channel, "refusing broadcast to invalid live channel name");
113 }
114}
115
116/// Wraps `inner_html` in the same `data-live-channel`-carrying `<div>`
117/// `@live(...)`'s own codegen produces for its initial render - the
118/// client's DOM patcher matches an incoming broadcast against the
119/// existing root element by *replacing* it wholesale if position/tag
120/// don't line up, so a broadcast payload needs this exact wrapper shape,
121/// not just the inner content, to patch cleanly in place instead of being
122/// discarded or mismatched.
123pub fn wrap(channel: &str, inner_html: &str) -> String {
124 format!(
125 r#"<div data-live-channel="{}">{inner_html}</div>"#,
126 larust_view::escape(channel)
127 )
128}
129
130/// `GET /__larust_push/{channel}` - upgrades to a WebSocket and streams
131/// every [`broadcast`] call's HTML straight through, verbatim, for the
132/// lifetime of the connection. Pure server → client push in v1: no
133/// client → server message is ever acted on (an inbound message is only
134/// read at all to detect the browser tab closing the connection).
135///
136/// Deliberately outside any CSRF check (unlike `@wire(...)`'s `update`
137/// route) - CSRF protects against an *attacker-initiated state change*
138/// riding the victim's cookies, and this endpoint never processes a
139/// client-originated state change at all, only pushes data out. If a
140/// channel carries anything sensitive, gate it the same way any other
141/// route would be gated - this handler is registered explicitly by the
142/// app (matching `@wire(...)`'s own routes), so ordinary middleware
143/// composition already covers it; no per-channel authorization exists at
144/// the framework level in v1.
145pub async fn socket(Path(channel): Path<String>, ws: WebSocketUpgrade) -> Response {
146 if !valid_channel_name(&channel) {
147 return (StatusCode::BAD_REQUEST, "invalid live channel").into_response();
148 }
149
150 let permits = CONNECTIONS
151 .get_or_init(|| Arc::new(Semaphore::new(MAX_PUSH_CONNECTIONS)))
152 .clone();
153 let Ok(permit) = permits.try_acquire_owned() else {
154 return (
155 StatusCode::TOO_MANY_REQUESTS,
156 "live connection limit reached",
157 )
158 .into_response();
159 };
160 let Some(sender) = sender_for(&channel) else {
161 return (
162 StatusCode::SERVICE_UNAVAILABLE,
163 "live channel limit reached",
164 )
165 .into_response();
166 };
167
168 ws.on_upgrade(move |socket| handle_socket(socket, sender, permit))
169 .into_response()
170}
171
172async fn handle_socket(
173 mut socket: WebSocket,
174 sender: broadcast::Sender<String>,
175 _permit: OwnedSemaphorePermit,
176) {
177 let mut updates = sender.subscribe();
178 loop {
179 tokio::select! {
180 update = updates.recv() => {
181 match update {
182 Ok(html) => {
183 if socket.send(Message::Text(html)).await.is_err() {
184 // The browser tab navigated away or closed -
185 // nothing left to push to.
186 break;
187 }
188 }
189 Err(broadcast::error::RecvError::Lagged(_)) => continue,
190 Err(broadcast::error::RecvError::Closed) => break,
191 }
192 }
193 incoming = socket.recv() => {
194 // Only read to detect the client closing the connection
195 // (`None`) or the transport erroring - the *content* of
196 // any client -> server message is ignored; this is a
197 // push-only channel in v1.
198 if incoming.is_none() {
199 break;
200 }
201 }
202 }
203 }
204}
205
206/// Keep channel identifiers predictable and safely bounded. Dynamic channel
207/// names remain supported (for example `orders.42`), but clients cannot use
208/// arbitrary long or control-character-bearing path values to consume memory.
209fn valid_channel_name(channel: &str) -> bool {
210 !channel.is_empty()
211 && channel.len() <= MAX_CHANNEL_NAME_BYTES
212 && channel
213 .bytes()
214 .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-'))
215}
216
217const RUNTIME_JS: &str = include_str!("../assets/push-runtime.js");
218
219/// `GET /__larust_push/runtime.js` - the vendored client runtime, same
220/// "served from the installed crate itself, not copied into
221/// `public/js/`" reasoning as `crate::routes::runtime_js`.
222pub async fn runtime_js() -> impl IntoResponse {
223 (
224 [(CONTENT_TYPE, "text/javascript; charset=utf-8")],
225 RUNTIME_JS,
226 )
227}
228
229/// The two routes `@live(...)`/[`broadcast`] need, bundled for
230/// [`larust_http::Router::plugin`] - sugar for the two `.get` calls this
231/// module's own doc comment shows an app writing by hand today.
232pub struct PushPlugin;
233
234impl larust_http::Plugin for PushPlugin {
235 fn routes(&self) -> larust_http::Router {
236 larust_http::Router::new()
237 .get("/__larust_push/runtime.js", runtime_js)
238 .get("/__larust_push/{channel}", socket)
239 }
240}
241
242#[cfg(test)]
243mod tests {
244 use super::*;
245
246 #[test]
247 fn push_plugin_contributes_exactly_the_two_routes_an_app_used_to_hand_write() {
248 let routes = larust_http::Router::new().plugin(PushPlugin).routes();
249
250 assert_eq!(routes.len(), 2);
251 assert_eq!(routes[0].method, "GET");
252 assert_eq!(routes[0].path, "/__larust_push/runtime.js");
253 assert_eq!(routes[1].method, "GET");
254 assert_eq!(routes[1].path, "/__larust_push/{channel}");
255 }
256
257 #[test]
258 fn wrap_produces_the_same_shape_the_live_directive_renders() {
259 let html = wrap("posts.count", "<span>5 posts</span>");
260 assert_eq!(
261 html,
262 r#"<div data-live-channel="posts.count"><span>5 posts</span></div>"#
263 );
264 }
265
266 #[test]
267 fn wrap_escapes_the_channel_name() {
268 let html = wrap("a\"b", "x");
269 assert!(!html.contains("a\"b\""), "channel name should be escaped");
270 }
271
272 #[tokio::test]
273 async fn broadcast_with_no_subscribers_is_a_harmless_no_op() {
274 broadcast("nobody-is-listening-to-this-channel", "<p>hi</p>");
275 }
276
277 #[tokio::test]
278 async fn a_subscriber_receives_a_broadcast_sent_after_it_subscribed() {
279 let mut rx = sender_for("subscriber-test-channel").unwrap().subscribe();
280 broadcast("subscriber-test-channel", "<p>update</p>");
281 let received = rx.recv().await.unwrap();
282 assert_eq!(received, "<p>update</p>");
283 }
284
285 #[test]
286 fn channel_names_are_bounded_and_reject_control_characters() {
287 assert!(valid_channel_name("orders.42_status"));
288 assert!(!valid_channel_name(""));
289 assert!(!valid_channel_name("orders/42"));
290 assert!(!valid_channel_name("orders\n42"));
291 assert!(!valid_channel_name(&"a".repeat(MAX_CHANNEL_NAME_BYTES + 1)));
292 }
293}