Skip to main content

brrrty_js/
traps.rs

1//! Reads Brrrty can't answer from the data alone, noticed while a template
2//! renders.
3//!
4//! An object can hold a property whose value is `undefined` as a marker for
5//! "11ty has a value here that the data doesn't carry". Two kinds exist:
6//!
7//! - A collection item's `templateContent` and `content`. The build installs
8//!   a [`ContentSource`] on the rendering thread; a read asks it for the
9//!   item's rendered content and is recorded (see [`take_item_reads`]), so
10//!   the build knows which pages each page read and can order them like
11//!   11ty. Without a source (a permalink or computed value renders before
12//!   any content exists) the read is a trap.
13//! - Everything else in [`TRAP_KEYS`] (`template`, an item's own
14//!   `data.collections`): reading it, or listing the object's properties,
15//!   records a trap. The renderer collects the traps after each render, and
16//!   the caller refuses the page instead of printing a wrong value.
17//!
18//! A registered ("open") object also traps a read of a property it doesn't
19//! have: the `collections` object of a site whose 11ty config may add
20//! collections Brrrty can't see.
21//!
22//! A registered ("withholding") object traps a read of the keys it was
23//! registered with, and a listing of its properties: a collection item's
24//! `data`, which lacks the keys whose value Brrrty can't supply (see
25//! [`withhold`]).
26
27use std::cell::RefCell;
28use std::collections::{BTreeSet, HashMap};
29use std::sync::atomic::{AtomicUsize, Ordering};
30use std::sync::{Arc, LazyLock, RwLock};
31
32use indexmap::IndexMap;
33
34use crate::Value;
35
36/// Properties that are traps when they hold `undefined`.
37pub const TRAP_KEYS: [&str; 5] = [
38    "templateContent",
39    "content",
40    "template",
41    "collections",
42    "rawInput",
43];
44
45/// The properties that hold a collection item's rendered content.
46pub const CONTENT_KEYS: [&str; 2] = ["templateContent", "content"];
47
48/// Prefix of a trap recorded for a marker property (`item.templateContent`).
49pub const ITEM_PREFIX: &str = "item.";
50/// Prefix of a trap recorded for a missing property of an open object.
51pub const OPEN_PREFIX: &str = "collections.";
52
53/// Prefix of a trap recorded for a read of a withheld key (`withheld.site`).
54pub const WITHHELD_PREFIX: &str = "withheld.";
55
56static OPEN: RwLock<Vec<usize>> = RwLock::new(Vec::new());
57
58/// Objects whose names' order isn't known (the `collections` of a site
59/// where 11ty orders templates by file-read timing), with why.
60static UNORDERED: RwLock<Vec<(usize, Arc<str>, bool)>> = RwLock::new(Vec::new());
61
62/// Prefix of a trap recorded for a listing of an object whose order isn't
63/// known; the rest is why.
64pub const ORDER_PREFIX: &str = "order.";
65
66/// Watched objects, by [`object_id`]: any read of one, or a listing, is
67/// noted on the reading thread (see [`touched`]).
68static WATCHED: RwLock<Vec<usize>> = RwLock::new(Vec::new());
69/// How many objects are watched, so a read can skip the lock when none.
70static WATCHED_COUNT: AtomicUsize = AtomicUsize::new(0);
71
72/// Withholding objects, by [`object_id`], with the keys they lack.
73static WITHHELD: LazyLock<RwLock<HashMap<usize, Arc<[String]>>>> =
74    LazyLock::new(|| RwLock::new(HashMap::new()));
75/// How many objects are withholding, so a read can skip the lock when none.
76static WITHHELD_COUNT: AtomicUsize = AtomicUsize::new(0);
77
78/// What a [`ContentSource`] has for an item.
79#[derive(Debug, Clone)]
80pub enum Content {
81    /// The rendered content.
82    Ready(Value),
83    /// Not rendered yet: the read gives `undefined`, and the render that
84    /// made it is only a draft.
85    Pending,
86    /// It will never be there: the page failed, or 11ty doesn't render it.
87    Refused,
88}
89
90/// How a read of an item's content went, as [`take_item_reads`] reports it.
91#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Outcome {
93    Ready,
94    Pending,
95    Refused,
96}
97
98/// The rendered content of collection items, for the pages rendering on
99/// this thread.
100pub trait ContentSource: Send + Sync {
101    /// The content of the item whose [`object_id`] is `item`, or `None` when
102    /// `item` is not an item this source knows.
103    fn content(&self, item: usize) -> Option<Content>;
104}
105
106thread_local! {
107    static HITS: RefCell<BTreeSet<String>> = const { RefCell::new(BTreeSet::new()) };
108    static SOURCE: RefCell<Option<Arc<dyn ContentSource>>> = const { RefCell::new(None) };
109    static ITEM_READS: RefCell<Vec<(usize, Outcome)>> = const { RefCell::new(Vec::new()) };
110    static TOUCHED: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
111}
112
113/// Watch an object: a read of any of its properties, or a listing of them,
114/// is noted on the thread that made it. `id` is [`object_id`] of the
115/// object; call [`unwatch`] when done.
116pub fn watch(id: usize) {
117    if let Ok(mut v) = WATCHED.write() {
118        v.push(id);
119        WATCHED_COUNT.fetch_add(1, Ordering::SeqCst);
120    }
121}
122
123pub fn unwatch(id: usize) {
124    if let Ok(mut v) = WATCHED.write()
125        && let Some(i) = v.iter().position(|x| *x == id)
126    {
127        v.swap_remove(i);
128        WATCHED_COUNT.fetch_sub(1, Ordering::SeqCst);
129    }
130}
131
132/// Whether this thread read a watched object since the flag was last set,
133/// and set it to `to`.
134pub fn swap_touched(to: bool) -> bool {
135    TOUCHED.with(|t| t.replace(to))
136}
137
138fn touch(o: &IndexMap<String, Value>) {
139    if WATCHED_COUNT.load(Ordering::Relaxed) == 0 {
140        return;
141    }
142    let id = object_id(o);
143    if WATCHED.read().is_ok_and(|v| v.contains(&id)) {
144        TOUCHED.with(|t| t.set(true));
145    }
146}
147
148/// Register an object: reading a property it doesn't have is a trap.
149/// `id` is [`object_id`] of the object. Call [`close`] when the build ends.
150pub fn open(id: usize) {
151    if let Ok(mut v) = OPEN.write() {
152        v.push(id);
153    }
154}
155
156pub fn close(id: usize) {
157    if let Ok(mut v) = OPEN.write() {
158        v.retain(|x| *x != id);
159    }
160}
161
162/// Register an object whose names' order isn't known: listing them is a
163/// trap, recorded with `why` ("whose order 11ty decides by ..."). `id` is
164/// [`object_id`] of the object; call [`ordered`] when the build ends.
165pub fn unordered(id: usize, why: impl Into<Arc<str>>) {
166    if let Ok(mut v) = UNORDERED.write() {
167        v.push((id, why.into(), false));
168    }
169}
170
171/// Register an object holding only some of the names it stands for, which
172/// ones depending on an order that isn't known: listing it, or reading a
173/// name it doesn't have, is a trap recorded with `why`. Call [`ordered`]
174/// when done.
175pub fn partial(id: usize, why: impl Into<Arc<str>>) {
176    if let Ok(mut v) = UNORDERED.write() {
177        v.push((id, why.into(), true));
178    }
179}
180
181pub fn ordered(id: usize) {
182    if let Ok(mut v) = UNORDERED.write() {
183        v.retain(|(x, _, _)| *x != id);
184    }
185}
186
187/// Why `o`'s names' order isn't known, when it was registered with
188/// [`unordered`] or [`partial`].
189pub fn unordered_reason(o: &IndexMap<String, Value>) -> Option<Arc<str>> {
190    unordered_entry(o).map(|(why, _)| why)
191}
192
193fn unordered_entry(o: &IndexMap<String, Value>) -> Option<(Arc<str>, bool)> {
194    let v = UNORDERED.read().ok()?;
195    if v.is_empty() {
196        return None;
197    }
198    let id = object_id(o);
199    v.iter()
200        .find(|(x, _, _)| *x == id)
201        .map(|(_, why, partial)| (why.clone(), *partial))
202}
203
204/// Why a name `o` doesn't have can't be read, when `o` was registered with
205/// [`partial`].
206fn partial_reason(o: &IndexMap<String, Value>) -> Option<Arc<str>> {
207    unordered_entry(o).and_then(|(why, partial)| partial.then_some(why))
208}
209
210/// Whether `o` traps a read or a listing ([`open`] or [`unordered`]).
211pub fn is_guarded_object(o: &IndexMap<String, Value>) -> bool {
212    is_open(o) || unordered_reason(o).is_some()
213}
214
215/// Record the trap for a listing of an object whose order isn't known.
216fn list_unordered(o: &IndexMap<String, Value>) -> bool {
217    match unordered_reason(o) {
218        Some(why) => {
219            hit(format!("{ORDER_PREFIX}{why}"));
220            true
221        }
222        None => false,
223    }
224}
225
226/// Register an object as lacking `keys`, whose value Brrrty can't supply:
227/// reading one of them, or listing the object's properties, is a trap.
228/// `id` is [`object_id`] of the object, which must stay alive until
229/// [`release`].
230pub fn withhold(id: usize, keys: Arc<[String]>) {
231    if keys.is_empty() {
232        return;
233    }
234    if let Ok(mut m) = WITHHELD.write()
235        && m.insert(id, keys).is_none()
236    {
237        WITHHELD_COUNT.fetch_add(1, Ordering::SeqCst);
238    }
239}
240
241pub fn release(id: usize) {
242    if let Ok(mut m) = WITHHELD.write()
243        && m.remove(&id).is_some()
244    {
245        WITHHELD_COUNT.fetch_sub(1, Ordering::SeqCst);
246    }
247}
248
249/// The keys `o` was registered as lacking with [`withhold`], if it was.
250pub fn withheld_keys(o: &IndexMap<String, Value>) -> Option<Arc<[String]>> {
251    withheld(o)
252}
253
254/// Whether `o` was registered with [`open`].
255pub fn is_open_object(o: &IndexMap<String, Value>) -> bool {
256    is_open(o)
257}
258
259/// The keys `o` was registered as lacking, if it was.
260fn withheld(o: &IndexMap<String, Value>) -> Option<Arc<[String]>> {
261    if WITHHELD_COUNT.load(Ordering::SeqCst) == 0 {
262        return None;
263    }
264    WITHHELD.read().ok()?.get(&object_id(o)).cloned()
265}
266
267fn withholds(o: &IndexMap<String, Value>, key: &str) -> bool {
268    withheld(o).is_some_and(|keys| keys.iter().any(|k| k == key))
269}
270
271/// Record the trap for a listing of a withholding object. True when it was.
272fn list_withheld(o: &IndexMap<String, Value>) -> bool {
273    match withheld(o) {
274        Some(keys) => {
275            hit(format!("{WITHHELD_PREFIX}{}", keys[0]));
276            true
277        }
278        None => false,
279    }
280}
281
282/// An object's identity while its `Arc` lives.
283pub fn object_id(o: &IndexMap<String, Value>) -> usize {
284    o as *const IndexMap<String, Value> as usize
285}
286
287fn is_open(o: &IndexMap<String, Value>) -> bool {
288    let id = object_id(o);
289    OPEN.read().map(|v| v.contains(&id)).unwrap_or(false)
290}
291
292/// Record a trap by name, as a read that hit one does.
293pub fn record(name: String) {
294    hit(name);
295}
296
297fn hit(name: String) {
298    HITS.with(|h| {
299        h.borrow_mut().insert(name);
300    });
301}
302
303/// Forget traps recorded so far on this thread.
304pub fn clear() {
305    HITS.with(|h| h.borrow_mut().clear());
306}
307
308/// The traps recorded on this thread since the last [`clear`], sorted.
309pub fn take() -> Vec<String> {
310    HITS.with(|h| std::mem::take(&mut *h.borrow_mut()).into_iter().collect())
311}
312
313/// Installs a content source on this thread until it is dropped, and
314/// starts a new record of item reads.
315pub struct SourceGuard(Option<Arc<dyn ContentSource>>);
316
317/// Use `source` for item content read on this thread while the guard lives.
318pub fn install(source: Arc<dyn ContentSource>) -> SourceGuard {
319    ITEM_READS.with(|r| r.borrow_mut().clear());
320    let previous = SOURCE.with(|s| s.borrow_mut().replace(source));
321    SourceGuard(previous)
322}
323
324impl Drop for SourceGuard {
325    fn drop(&mut self) {
326        let previous = self.0.take();
327        SOURCE.with(|s| *s.borrow_mut() = previous);
328    }
329}
330
331/// The item content reads on this thread since [`install`]: each item's
332/// [`object_id`] and what the read gave, in read order.
333pub fn take_item_reads() -> Vec<(usize, Outcome)> {
334    ITEM_READS.with(|r| std::mem::take(&mut *r.borrow_mut()))
335}
336
337/// The content of `o`, an item, under `key`, when the installed source
338/// knows the item. `None` when there's no source or `o` is not its item.
339fn item_content(o: &IndexMap<String, Value>) -> Option<Content> {
340    let id = object_id(o);
341    let content = SOURCE.with(|s| s.borrow().as_ref().and_then(|src| src.content(id)))?;
342    let outcome = match &content {
343        Content::Ready(_) => Outcome::Ready,
344        Content::Pending => Outcome::Pending,
345        Content::Refused => Outcome::Refused,
346    };
347    ITEM_READS.with(|r| r.borrow_mut().push((id, outcome)));
348    Some(content)
349}
350
351/// A read of `key` from `o`, which has `found` there: the value the read
352/// gives. An item's content comes from the installed source; other markers
353/// and missing properties of an open object are recorded as traps.
354pub fn read(o: &IndexMap<String, Value>, key: &str, found: Option<Value>) -> Option<Value> {
355    touch(o);
356    match &found {
357        Some(Value::Undefined) if CONTENT_KEYS.contains(&key) => match item_content(o) {
358            Some(Content::Ready(v)) => Some(v),
359            Some(Content::Pending | Content::Refused) => found,
360            None => {
361                hit(format!("{ITEM_PREFIX}{key}"));
362                found
363            }
364        },
365        Some(Value::Undefined) if TRAP_KEYS.contains(&key) => {
366            hit(format!("{ITEM_PREFIX}{key}"));
367            found
368        }
369        None if withholds(o, key) => {
370            hit(format!("{WITHHELD_PREFIX}{key}"));
371            found
372        }
373        None if partial_reason(o).is_some() => {
374            if let Some(why) = partial_reason(o) {
375                hit(format!("{ORDER_PREFIX}{why}"));
376            }
377            found
378        }
379        None if is_open(o) => {
380            hit(format!("{OPEN_PREFIX}{key}"));
381            found
382        }
383        _ => found,
384    }
385}
386
387/// A top-level read of `key` from `data`, the data of a sub-evaluation
388/// (`where: "templateContent"` reads the item as its variables): the item's
389/// content when `key` holds it, else `found`.
390pub fn read_top(data: &Value, key: &str, found: Option<Value>) -> Option<Value> {
391    match (data, &found) {
392        (Value::Object(o), Some(Value::Undefined)) if CONTENT_KEYS.contains(&key) => {
393            match item_content(o) {
394                Some(Content::Ready(v)) => Some(v),
395                _ => found,
396            }
397        }
398        _ => found,
399    }
400}
401
402/// A top-level lookup of `key` in `item`, the data of a sub-evaluation,
403/// that gave `undefined`.
404pub fn read_item(item: &Value, key: &str) {
405    if let Value::Object(o) = item {
406        read(o, key, o.get(key).cloned());
407    }
408}
409
410/// A listing of `o`'s property names (or a count of them), without their
411/// values. An item's names are all there, so only an open object, which
412/// may have more, is a trap. True when it recorded one.
413pub fn keys(o: &IndexMap<String, Value>) -> bool {
414    touch(o);
415    if list_withheld(o) {
416        return true;
417    }
418    if list_unordered(o) {
419        return true;
420    }
421    if is_open(o) {
422        hit(format!("{OPEN_PREFIX}*"));
423        return true;
424    }
425    false
426}
427
428/// Whether `o` has `key` as an own property (`key in o`). A name an open
429/// object doesn't have is a trap: the config may add it.
430pub fn has(o: &IndexMap<String, Value>, key: &str) -> bool {
431    touch(o);
432    if o.contains_key(key) {
433        return true;
434    }
435    if withholds(o, key) {
436        hit(format!("{WITHHELD_PREFIX}{key}"));
437    } else if let Some(why) = partial_reason(o) {
438        hit(format!("{ORDER_PREFIX}{why}"));
439    } else if is_open(o) {
440        hit(format!("{OPEN_PREFIX}{key}"));
441    }
442    false
443}
444
445/// A listing of all of `o`'s properties. True when it recorded a trap: the
446/// caller's result will be refused, so a walk of the data can stop there.
447pub fn entries(o: &IndexMap<String, Value>) -> bool {
448    touch(o);
449    let mut trapped = false;
450    let mut item_known = None;
451    for key in TRAP_KEYS {
452        if matches!(o.get(key), Some(Value::Undefined)) {
453            // An item's content can be listed when a source has it; the
454            // listing still trips on `template`.
455            if CONTENT_KEYS.contains(&key) {
456                let known = *item_known.get_or_insert_with(|| {
457                    SOURCE.with(|s| {
458                        s.borrow()
459                            .as_ref()
460                            .is_some_and(|src| src.content(object_id(o)).is_some())
461                    })
462                });
463                if known {
464                    continue;
465                }
466            }
467            hit(format!("{ITEM_PREFIX}{key}"));
468            trapped = true;
469        }
470    }
471    if list_withheld(o) {
472        trapped = true;
473    }
474    if list_unordered(o) {
475        trapped = true;
476    }
477    if is_open(o) {
478        hit(format!("{OPEN_PREFIX}*"));
479        trapped = true;
480    }
481    trapped
482}
483
484#[cfg(test)]
485mod tests {
486    use super::*;
487
488    struct One(usize, Content);
489
490    impl ContentSource for One {
491        fn content(&self, item: usize) -> Option<Content> {
492            (item == self.0).then(|| self.1.clone())
493        }
494    }
495
496    fn item() -> IndexMap<String, Value> {
497        let mut o = IndexMap::new();
498        o.insert("templateContent".to_string(), Value::Undefined);
499        o.insert("content".to_string(), Value::Undefined);
500        o.insert("template".to_string(), Value::Undefined);
501        o
502    }
503
504    #[test]
505    fn a_watched_object_notes_reads_and_listings() {
506        let mut o = IndexMap::new();
507        o.insert("post".to_string(), Value::Array(Default::default()));
508        let other = IndexMap::new();
509        swap_touched(false);
510        read(&o, "post", o.get("post").cloned());
511        assert!(!swap_touched(false));
512        watch(object_id(&o));
513        read(&other, "post", None);
514        assert!(!swap_touched(false));
515        read(&o, "post", o.get("post").cloned());
516        assert!(swap_touched(false));
517        has(&o, "x");
518        assert!(swap_touched(false));
519        keys(&o);
520        assert!(swap_touched(false));
521        entries(&o);
522        assert!(swap_touched(false));
523        unwatch(object_id(&o));
524        read(&o, "post", o.get("post").cloned());
525        assert!(!swap_touched(false));
526    }
527
528    #[test]
529    fn a_withholding_object_traps_its_keys_and_listings() {
530        let mut o = IndexMap::new();
531        o.insert("title".to_string(), Value::String("t".into()));
532        let id = object_id(&o);
533        withhold(id, Arc::from(vec!["site".to_string()]));
534        clear();
535        assert_eq!(
536            read(&o, "title", o.get("title").cloned()),
537            o.get("title").cloned()
538        );
539        assert_eq!(read(&o, "other", None), None);
540        assert!(take().is_empty());
541        assert_eq!(read(&o, "site", None), None);
542        assert_eq!(take(), vec!["withheld.site".to_string()]);
543        assert!(!has(&o, "site"));
544        assert_eq!(take(), vec!["withheld.site".to_string()]);
545        assert!(entries(&o));
546        assert_eq!(take(), vec!["withheld.site".to_string()]);
547        release(id);
548        assert_eq!(read(&o, "site", None), None);
549        assert!(!entries(&o));
550        assert!(take().is_empty());
551    }
552
553    #[test]
554    fn a_source_answers_content_reads_and_records_them() {
555        let o = item();
556        let id = object_id(&o);
557        let ready = Value::String("<p>x</p>".into());
558        {
559            let _g = install(Arc::new(One(id, Content::Ready(ready.clone()))));
560            clear();
561            let got = read(&o, "content", o.get("content").cloned());
562            assert_eq!(got, Some(ready.clone()));
563            assert_eq!(take_item_reads(), vec![(id, Outcome::Ready)]);
564            assert!(take().is_empty());
565        }
566        // Without a source, the same read is a trap.
567        clear();
568        let got = read(&o, "templateContent", o.get("templateContent").cloned());
569        assert_eq!(got, Some(Value::Undefined));
570        assert_eq!(take(), vec!["item.templateContent".to_string()]);
571    }
572
573    #[test]
574    fn pending_and_refused_reads_give_undefined() {
575        let o = item();
576        let id = object_id(&o);
577        for (content, outcome) in [
578            (Content::Pending, Outcome::Pending),
579            (Content::Refused, Outcome::Refused),
580        ] {
581            let _g = install(Arc::new(One(id, content)));
582            clear();
583            let got = read(&o, "templateContent", Some(Value::Undefined));
584            assert_eq!(got, Some(Value::Undefined));
585            assert_eq!(take_item_reads(), vec![(id, outcome)]);
586            assert!(take().is_empty());
587        }
588    }
589
590    #[test]
591    fn listing_a_known_item_trips_only_on_template() {
592        let o = item();
593        let id = object_id(&o);
594        let _g = install(Arc::new(One(id, Content::Ready(Value::String("x".into())))));
595        clear();
596        entries(&o);
597        assert_eq!(take(), vec!["item.template".to_string()]);
598    }
599}