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