Skip to main content

livewire/
context.rs

1//! The request's Livewire state, reached through the framework's context instead of a static.
2//!
3//! Upstream Livewire keeps its render stack, component stack, and pending effects in PHP statics and
4//! weak maps, which one request can leak into another on a long-lived worker. Here one
5//! [`LivewireRequest`] per request holds the same state, created on first use in the framework's
6//! request-local store.
7//!
8//! The state is lock-protected, so never hold a guard across an `.await` or a nested render: take
9//! what you need from the state, release the lock, then render.
10
11use std::collections::{BTreeMap, BTreeSet};
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
14
15use laravel_core::context::{Context, Internals};
16use serde_json::{Map, Value};
17
18/// A file the browser downloads instead of rendering the component.
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub struct Download {
21    /// The file name the browser saves.
22    pub name: String,
23    /// The file's bytes.
24    pub content: Vec<u8>,
25    /// The file's media type, such as `text/csv`.
26    pub content_type: String,
27}
28
29/// One chunk a streamed component sent before its final response.
30#[derive(Debug, Clone, PartialEq)]
31pub struct Stream {
32    /// The component that streamed the chunk.
33    pub id: String,
34    /// The chunk's kind, such as `replace` or `append`.
35    pub chunk_type: String,
36    /// The chunk's content.
37    pub content: String,
38    /// Where the chunk goes: a CSS selector, or a target inside the component.
39    pub mode: String,
40    /// The selector the chunk replaces, or `None` for the component's own markup.
41    pub selector: Option<String>,
42    /// The island the chunk belongs to, or `None` for the component.
43    pub island: Option<String>,
44}
45
46/// One nested component a parent rendered, as the parent's memo records it.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct Child {
49    /// The key the parent gave the child, or the key it was rendered under.
50    pub key: String,
51    /// The child's tag name, which the browser uses to find the element.
52    pub tag: String,
53    /// The child's instance ID.
54    pub id: String,
55}
56
57/// The page a component was rendered from.
58#[derive(Debug, Clone, PartialEq, Eq)]
59pub struct PageContext {
60    /// The path the page was requested at, such as `/livewire/counter`.
61    pub path: String,
62    /// The method it was requested with.
63    pub method: String,
64    /// The origin it was requested from.
65    pub origin: String,
66}
67
68/// The state one component has within one request: what it rendered, and what it asks the browser
69/// to do.
70#[derive(Debug, Clone, Default)]
71pub struct ComponentState {
72    /// The component's registered name, such as `counter`.
73    pub name: String,
74    /// The ID of the component that rendered this one, when nested.
75    pub parent: Option<String>,
76    /// Effects the component added, keyed by effect name: `dispatches`, `listeners`, `url`,
77    /// `xjs`, `js`, `redirect`, `download`, `scripts`, and the module keys.
78    pub effects: Map<String, Value>,
79    /// Memo entries the component added, such as `lazy`, `isolate`, `with`, `async`, `html`.
80    pub memo: Map<String, Value>,
81    /// The named params its parent passed this request, which a reactive prop reads back and an
82    /// unchanged child skips on.
83    pub provided_props: Option<Map<String, Value>>,
84    /// The slot fragments this component stubbed a child with, sent so the browser can morph them.
85    pub slot_fragments: Vec<String>,
86    /// The nested components the component rendered, in render order.
87    pub children: Vec<Child>,
88    /// The `@script` blocks this render ran, keyed by component name and template position.
89    pub scripts: Vec<String>,
90    /// The `@assets` blocks this render ran, keyed the same way.
91    pub assets: Vec<String>,
92    /// The island fragments the component rendered, keyed by island name.
93    pub islands: Map<String, Value>,
94    /// The slot fragments the component rendered for its parent, keyed by slot name.
95    pub slots: Map<String, Value>,
96    /// The validate errors the component's last validation produced.
97    pub errors: Map<String, Value>,
98    /// The file the component asked the browser to download.
99    pub download: Option<Download>,
100}
101
102impl ComponentState {
103    /// Adds `value` to the effect `name`, keeping a list when it is one.
104    pub fn push_effect(&mut self, name: &str, value: Value) {
105        match self.effects.get_mut(name) {
106            Some(Value::Array(values)) => values.push(value),
107            Some(existing) => {
108                let first = std::mem::replace(existing, Value::Array(Vec::new()));
109                if let Some(Value::Array(values)) = self.effects.get_mut(name) {
110                    values.push(first);
111                    values.push(value);
112                }
113            }
114            None => {
115                self.effects.insert(name.to_owned(), value);
116            }
117        }
118    }
119}
120
121/// One request's mutable Livewire state.
122#[derive(Debug, Default)]
123pub struct LivewireRequest {
124    components: Mutex<BTreeMap<String, ComponentState>>,
125    /// The IDs of the components being rendered, outermost first.
126    rendering: Mutex<Vec<String>>,
127    /// The IDs of the components being mounted, outermost first.
128    mounting: Mutex<Vec<String>>,
129    /// Whether this batch already checked the client's checksum-failure allowance.
130    checksum_checked: AtomicBool,
131    /// Whether the page rendered the styles or scripts itself.
132    styles_rendered: AtomicBool,
133    scripts_rendered: AtomicBool,
134    /// Assets already rendered in this request, so `@assets` renders once.
135    rendered_assets: Mutex<BTreeSet<String>>,
136    /// Scripts already rendered in this request, so `@script` renders once.
137    rendered_scripts: Mutex<BTreeSet<String>>,
138    /// Assets the response reports, so the browser can load them.
139    response_assets: Mutex<BTreeSet<String>>,
140    /// The chunks a streamed action sent.
141    streams: Mutex<Vec<Stream>>,
142    /// Computed property values memoized for this request, keyed by `{component id}:{name}`.
143    computed: Mutex<BTreeMap<String, Value>>,
144    /// Values the route's persistent middleware resolved, so the batch reuses them.
145    persistent: Mutex<Map<String, Value>>,
146    /// The HTTP request being handled, so an action can read the signed-in user or a service.
147    http: Mutex<Option<Arc<laravel::http::Request>>>,
148    /// The page a component was rendered from, which an update replays.
149    page: Mutex<Option<PageContext>>,
150}
151
152impl LivewireRequest {
153    /// The request's state, created on first use, or `None` outside a request.
154    ///
155    /// # Panics
156    ///
157    /// Panics when the request-local store is unavailable, which only happens outside the
158    /// application.
159    #[must_use]
160    pub fn current() -> Option<Arc<Self>> {
161        Some(Context::current()?.local::<Self>())
162    }
163
164    fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
165        mutex.lock().unwrap_or_else(PoisonError::into_inner)
166    }
167
168    /// Marks a component as mounting, and returns a guard that unmarks it when dropped.
169    pub fn push_mounting(&self, id: &str) -> StackGuard<'_> {
170        let mut stack = Self::lock(&self.mounting);
171        let parent = stack.last().cloned();
172        stack.push(id.to_owned());
173        drop(stack);
174
175        if let Some(state) = Self::lock(&self.components).get_mut(id) {
176            state.parent = parent;
177        }
178
179        StackGuard { stack: &self.mounting }
180    }
181
182    /// The component that is mounting now, which is the parent of a component being mounted inside
183    /// it.
184    #[must_use]
185    pub fn mounting(&self) -> Option<String> {
186        Self::lock(&self.mounting).last().cloned()
187    }
188
189    /// Marks a component as rendering, and returns a guard that unmarks it when dropped.
190    pub fn push_rendering(&self, id: &str) -> StackGuard<'_> {
191        Self::lock(&self.rendering).push(id.to_owned());
192        StackGuard { stack: &self.rendering }
193    }
194
195    /// The component that is rendering now.
196    #[must_use]
197    pub fn rendering(&self) -> Option<String> {
198        Self::lock(&self.rendering).last().cloned()
199    }
200
201    /// How many components are rendering, which is the depth a nested render reports.
202    #[must_use]
203    pub fn render_depth(&self) -> usize {
204        Self::lock(&self.rendering).len()
205    }
206
207    /// Registers a component's state, replacing any state under the same ID.
208    pub fn register(&self, id: &str, state: ComponentState) {
209        Self::lock(&self.components).insert(id.to_owned(), state);
210    }
211
212    /// Remembers the page this request rendered, which a mount records and an update replays.
213    pub fn remember_page(&self, path: &str, method: &str, origin: &str) {
214        *Self::lock(&self.page) = Some(PageContext {
215            path: path.to_owned(),
216            method: method.to_owned(),
217            origin: origin.to_owned(),
218        });
219    }
220
221    /// The page this request rendered, when one did.
222    #[must_use]
223    pub fn page(&self) -> Option<PageContext> {
224        Self::lock(&self.page).clone()
225    }
226
227    /// Reads a component's state.
228    pub fn read<T>(&self, id: &str, read: impl FnOnce(&ComponentState) -> T) -> Option<T> {
229        Self::lock(&self.components).get(id).map(read)
230    }
231
232    /// Changes a component's state, creating it when the component is not registered yet.
233    pub fn change(&self, id: &str, change: impl FnOnce(&mut ComponentState)) {
234        let mut components = Self::lock(&self.components);
235        change(components.entry(id.to_owned()).or_default());
236    }
237
238    /// Whether any component rendered in this request, which decides whether the page needs the
239    /// runtime at all.
240    #[must_use]
241    pub fn has_rendered(&self) -> bool {
242        !Self::lock(&self.components).is_empty()
243    }
244
245    /// Forgets a component's state, after its last render.
246    pub fn forget(&self, id: &str) {
247        Self::lock(&self.components).remove(id);
248    }
249
250    /// Records that a component rendered a nested component.
251    pub fn add_child(&self, parent: &str, child: Child) {
252        self.change(parent, |state| {
253            if let Some(existing) = state.children.iter_mut().find(|existing| existing.key == child.key) {
254                *existing = child;
255            } else {
256                state.children.push(child);
257            }
258        });
259    }
260
261    /// The nested components a component rendered.
262    #[must_use]
263    pub fn children(&self, parent: &str) -> Vec<Child> {
264        self.read(parent, |state| state.children.clone()).unwrap_or_default()
265    }
266
267    /// Records an asset the response reports, returning whether it is new.
268    pub fn add_asset(&self, asset: &str) -> bool {
269        Self::lock(&self.response_assets).insert(asset.to_owned())
270    }
271
272    /// Takes the assets the response reports, in the order they were added.
273    #[must_use]
274    pub fn take_assets(&self) -> Vec<String> {
275        let mut assets = Self::lock(&self.response_assets);
276        std::mem::take(&mut *assets).into_iter().collect()
277    }
278
279    /// Records that the page called `livewire_styles()` itself, so the response does not add them
280    /// again.
281    pub fn mark_styles_rendered(&self) {
282        self.styles_rendered.store(true, Ordering::Release);
283    }
284
285    /// Whether the page called `livewire_styles()` itself.
286    #[must_use]
287    pub fn styles_rendered(&self) -> bool {
288        self.styles_rendered.load(Ordering::Acquire)
289    }
290
291    /// Records that the page called `livewire_scripts()` itself, so the response does not add them
292    /// again.
293    pub fn mark_scripts_rendered(&self) {
294        self.scripts_rendered.store(true, Ordering::Release);
295    }
296
297    /// Whether the page called `livewire_scripts()` itself.
298    #[must_use]
299    pub fn scripts_rendered(&self) -> bool {
300        self.scripts_rendered.load(Ordering::Acquire)
301    }
302
303    /// Marks an asset as rendered in this request, returning `false` when it already was.
304    pub fn first_asset_render(&self, asset: &str) -> bool {
305        Self::lock(&self.rendered_assets).insert(asset.to_owned())
306    }
307
308    /// Marks a script as rendered in this request, returning `false` when it already was.
309    pub fn first_script_render(&self, script: &str) -> bool {
310        Self::lock(&self.rendered_scripts).insert(script.to_owned())
311    }
312
313    /// Records a streamed chunk.
314    pub fn add_stream(&self, stream: Stream) {
315        Self::lock(&self.streams).push(stream);
316    }
317
318    /// Takes the streamed chunks, in the order they were sent.
319    #[must_use]
320    pub fn take_streams(&self) -> Vec<Stream> {
321        std::mem::take(&mut *Self::lock(&self.streams))
322    }
323
324    /// Whether anything streamed, so the response is an event stream.
325    #[must_use]
326    pub fn is_streaming(&self) -> bool {
327        !Self::lock(&self.streams).is_empty()
328    }
329
330    /// The memoized value of a computed property, if this request computed it already.
331    #[must_use]
332    pub fn computed(&self, component: &str, name: &str) -> Option<Value> {
333        Self::lock(&self.computed).get(&format!("{component}:{name}")).cloned()
334    }
335
336    /// Memoizes a computed property's value for the rest of the request.
337    pub fn set_computed(&self, component: &str, name: &str, value: Value) {
338        Self::lock(&self.computed).insert(format!("{component}:{name}"), value);
339    }
340
341    /// Forgets a computed property, so the next read recomputes it.
342    pub fn forget_computed(&self, component: &str, name: &str) {
343        Self::lock(&self.computed).remove(&format!("{component}:{name}"));
344    }
345
346    /// Whether this request already checked the client's checksum-failure allowance. The batch
347    /// checks once, however many components it updates.
348    #[must_use]
349    pub fn first_checksum_check(&self) -> bool {
350        !self.checksum_checked.swap(true, Ordering::AcqRel)
351    }
352
353    /// Keeps the HTTP request being handled, so an action can reach it.
354    pub fn set_http_request(&self, request: Arc<laravel::http::Request>) {
355        *Self::lock(&self.http) = Some(request);
356    }
357
358    /// The HTTP request being handled, or `None` outside a request.
359    #[must_use]
360    pub fn http_request(&self) -> Option<Arc<laravel::http::Request>> {
361        Self::lock(&self.http).clone()
362    }
363
364    /// Records a value the route's persistent middleware resolved.
365    pub fn set_persistent(&self, key: &str, value: Value) {
366        Self::lock(&self.persistent).insert(key.to_owned(), value);
367    }
368
369    /// Reads a value the route's persistent middleware resolved.
370    #[must_use]
371    pub fn persistent(&self, key: &str) -> Option<Value> {
372        Self::lock(&self.persistent).get(key).cloned()
373    }
374}
375
376/// Pops a stack when dropped, so a failed render cannot leave a component on it.
377#[derive(Debug)]
378pub struct StackGuard<'a> {
379    stack: &'a Mutex<Vec<String>>,
380}
381
382impl Drop for StackGuard<'_> {
383    fn drop(&mut self) {
384        LivewireRequest::lock(self.stack).pop();
385    }
386}
387
388#[cfg(test)]
389mod tests {
390    use super::*;
391
392    #[test]
393    fn a_render_stack_pops_even_when_a_render_fails() {
394        let request = LivewireRequest::default();
395        {
396            let _outer = request.push_rendering("a");
397            assert_eq!(request.rendering().as_deref(), Some("a"));
398            assert_eq!(request.render_depth(), 1);
399            let inner = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
400                let _inner = request.push_rendering("b");
401                assert_eq!(request.render_depth(), 2);
402                panic!("the component's view failed");
403            }));
404            assert!(inner.is_err());
405        }
406        assert_eq!(request.render_depth(), 0);
407    }
408
409    #[test]
410    fn a_mounting_component_records_its_parent() {
411        let request = LivewireRequest::default();
412        request.register("parent", ComponentState::default());
413        request.register("child", ComponentState::default());
414
415        {
416            let _parent = request.push_mounting("parent");
417            assert_eq!(request.mounting().as_deref(), Some("parent"));
418            {
419                let _child = request.push_mounting("child");
420                assert_eq!(request.mounting().as_deref(), Some("child"));
421            }
422        }
423
424        assert_eq!(request.mounting(), None);
425        assert_eq!(
426            request.read("child", |state| state.parent.clone()),
427            Some(Some("parent".to_owned()))
428        );
429    }
430
431    #[test]
432    fn child_records_replace_by_key_and_keep_order() {
433        let request = LivewireRequest::default();
434        request.register("parent", ComponentState::default());
435
436        for (key, id) in [("a", "1"), ("b", "2")] {
437            request.add_child(
438                "parent",
439                Child {
440                    key: key.to_owned(),
441                    tag: "div".to_owned(),
442                    id: id.to_owned(),
443                },
444            );
445        }
446        request.add_child(
447            "parent",
448            Child {
449                key: "a".to_owned(),
450                tag: "div".to_owned(),
451                id: "3".to_owned(),
452            },
453        );
454
455        let children = request.children("parent");
456        assert_eq!(children.len(), 2);
457        assert_eq!(children[0].id, "3");
458        assert_eq!(children[1].id, "2");
459    }
460
461    #[test]
462    fn assets_and_scripts_render_once_per_request() {
463        let request = LivewireRequest::default();
464
465        assert!(request.first_asset_render("chart.js"));
466        assert!(!request.first_asset_render("chart.js"));
467        assert!(request.first_script_render("counter"));
468
469        assert!(request.add_asset("chart.js"));
470        assert!(!request.add_asset("chart.js"));
471        assert_eq!(request.take_assets(), ["chart.js"]);
472        assert!(request.take_assets().is_empty());
473    }
474
475    #[test]
476    fn the_checksum_allowance_is_checked_once_per_batch() {
477        let request = LivewireRequest::default();
478
479        assert!(request.first_checksum_check());
480        assert!(!request.first_checksum_check());
481    }
482
483    #[test]
484    fn effects_collect_into_lists() {
485        let mut state = ComponentState::default();
486
487        state.push_effect("dispatches", Value::from("first"));
488        state.push_effect("dispatches", Value::from("second"));
489
490        assert_eq!(state.effects["dispatches"], serde_json::json!(["first", "second"]));
491    }
492
493    #[test]
494    fn computed_values_are_keyed_by_component_and_name() {
495        let request = LivewireRequest::default();
496
497        request.set_computed("a", "total", Value::from(1));
498        request.set_computed("b", "total", Value::from(2));
499
500        assert_eq!(request.computed("a", "total"), Some(Value::from(1)));
501        assert_eq!(request.computed("b", "total"), Some(Value::from(2)));
502
503        request.forget_computed("a", "total");
504        assert_eq!(request.computed("a", "total"), None);
505        assert_eq!(request.computed("b", "total"), Some(Value::from(2)));
506    }
507}