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
22use std::cell::RefCell;
23use std::collections::BTreeSet;
24use std::sync::{Arc, RwLock};
25
26use indexmap::IndexMap;
27
28use crate::Value;
29
30/// Properties that are traps when they hold `undefined`.
31pub const TRAP_KEYS: [&str; 4] = ["templateContent", "content", "template", "collections"];
32
33/// The properties that hold a collection item's rendered content.
34pub const CONTENT_KEYS: [&str; 2] = ["templateContent", "content"];
35
36/// Prefix of a trap recorded for a marker property (`item.templateContent`).
37pub const ITEM_PREFIX: &str = "item.";
38/// Prefix of a trap recorded for a missing property of an open object.
39pub const OPEN_PREFIX: &str = "collections.";
40
41static OPEN: RwLock<Vec<usize>> = RwLock::new(Vec::new());
42
43/// What a [`ContentSource`] has for an item.
44#[derive(Debug, Clone)]
45pub enum Content {
46    /// The rendered content.
47    Ready(Value),
48    /// Not rendered yet: the read gives `undefined`, and the render that
49    /// made it is only a draft.
50    Pending,
51    /// It will never be there: the page failed, or 11ty doesn't render it.
52    Refused,
53}
54
55/// How a read of an item's content went, as [`take_item_reads`] reports it.
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum Outcome {
58    Ready,
59    Pending,
60    Refused,
61}
62
63/// The rendered content of collection items, for the pages rendering on
64/// this thread.
65pub trait ContentSource: Send + Sync {
66    /// The content of the item whose [`object_id`] is `item`, or `None` when
67    /// `item` is not an item this source knows.
68    fn content(&self, item: usize) -> Option<Content>;
69}
70
71thread_local! {
72    static HITS: RefCell<BTreeSet<String>> = const { RefCell::new(BTreeSet::new()) };
73    static SOURCE: RefCell<Option<Arc<dyn ContentSource>>> = const { RefCell::new(None) };
74    static ITEM_READS: RefCell<Vec<(usize, Outcome)>> = const { RefCell::new(Vec::new()) };
75}
76
77/// Register an object: reading a property it doesn't have is a trap.
78/// `id` is [`object_id`] of the object. Call [`close`] when the build ends.
79pub fn open(id: usize) {
80    if let Ok(mut v) = OPEN.write() {
81        v.push(id);
82    }
83}
84
85pub fn close(id: usize) {
86    if let Ok(mut v) = OPEN.write() {
87        v.retain(|x| *x != id);
88    }
89}
90
91/// An object's identity while its `Arc` lives.
92pub fn object_id(o: &IndexMap<String, Value>) -> usize {
93    o as *const IndexMap<String, Value> as usize
94}
95
96fn is_open(o: &IndexMap<String, Value>) -> bool {
97    let id = object_id(o);
98    OPEN.read().map(|v| v.contains(&id)).unwrap_or(false)
99}
100
101/// Record a trap by name, as a read that hit one does.
102pub fn record(name: String) {
103    hit(name);
104}
105
106fn hit(name: String) {
107    HITS.with(|h| {
108        h.borrow_mut().insert(name);
109    });
110}
111
112/// Forget traps recorded so far on this thread.
113pub fn clear() {
114    HITS.with(|h| h.borrow_mut().clear());
115}
116
117/// The traps recorded on this thread since the last [`clear`], sorted.
118pub fn take() -> Vec<String> {
119    HITS.with(|h| std::mem::take(&mut *h.borrow_mut()).into_iter().collect())
120}
121
122/// Installs a content source on this thread until it is dropped, and
123/// starts a new record of item reads.
124pub struct SourceGuard(Option<Arc<dyn ContentSource>>);
125
126/// Use `source` for item content read on this thread while the guard lives.
127pub fn install(source: Arc<dyn ContentSource>) -> SourceGuard {
128    ITEM_READS.with(|r| r.borrow_mut().clear());
129    let previous = SOURCE.with(|s| s.borrow_mut().replace(source));
130    SourceGuard(previous)
131}
132
133impl Drop for SourceGuard {
134    fn drop(&mut self) {
135        let previous = self.0.take();
136        SOURCE.with(|s| *s.borrow_mut() = previous);
137    }
138}
139
140/// The item content reads on this thread since [`install`]: each item's
141/// [`object_id`] and what the read gave, in read order.
142pub fn take_item_reads() -> Vec<(usize, Outcome)> {
143    ITEM_READS.with(|r| std::mem::take(&mut *r.borrow_mut()))
144}
145
146/// The content of `o`, an item, under `key`, when the installed source
147/// knows the item. `None` when there's no source or `o` is not its item.
148fn item_content(o: &IndexMap<String, Value>) -> Option<Content> {
149    let id = object_id(o);
150    let content = SOURCE.with(|s| s.borrow().as_ref().and_then(|src| src.content(id)))?;
151    let outcome = match &content {
152        Content::Ready(_) => Outcome::Ready,
153        Content::Pending => Outcome::Pending,
154        Content::Refused => Outcome::Refused,
155    };
156    ITEM_READS.with(|r| r.borrow_mut().push((id, outcome)));
157    Some(content)
158}
159
160/// A read of `key` from `o`, which has `found` there: the value the read
161/// gives. An item's content comes from the installed source; other markers
162/// and missing properties of an open object are recorded as traps.
163pub fn read(o: &IndexMap<String, Value>, key: &str, found: Option<Value>) -> Option<Value> {
164    match &found {
165        Some(Value::Undefined) if CONTENT_KEYS.contains(&key) => match item_content(o) {
166            Some(Content::Ready(v)) => Some(v),
167            Some(Content::Pending | Content::Refused) => found,
168            None => {
169                hit(format!("{ITEM_PREFIX}{key}"));
170                found
171            }
172        },
173        Some(Value::Undefined) if TRAP_KEYS.contains(&key) => {
174            hit(format!("{ITEM_PREFIX}{key}"));
175            found
176        }
177        None if is_open(o) => {
178            hit(format!("{OPEN_PREFIX}{key}"));
179            found
180        }
181        _ => found,
182    }
183}
184
185/// A top-level read of `key` from `data`, the data of a sub-evaluation
186/// (`where: "templateContent"` reads the item as its variables): the item's
187/// content when `key` holds it, else `found`.
188pub fn read_top(data: &Value, key: &str, found: Option<Value>) -> Option<Value> {
189    match (data, &found) {
190        (Value::Object(o), Some(Value::Undefined)) if CONTENT_KEYS.contains(&key) => {
191            match item_content(o) {
192                Some(Content::Ready(v)) => Some(v),
193                _ => found,
194            }
195        }
196        _ => found,
197    }
198}
199
200/// A top-level lookup of `key` in `item`, the data of a sub-evaluation,
201/// that gave `undefined`.
202pub fn read_item(item: &Value, key: &str) {
203    if let Value::Object(o) = item {
204        read(o, key, o.get(key).cloned());
205    }
206}
207
208/// A listing of `o`'s property names (or a count of them), without their
209/// values. An item's names are all there, so only an open object, which
210/// may have more, is a trap. True when it recorded one.
211pub fn keys(o: &IndexMap<String, Value>) -> bool {
212    if is_open(o) {
213        hit(format!("{OPEN_PREFIX}*"));
214        return true;
215    }
216    false
217}
218
219/// Whether `o` has `key` as an own property (`key in o`). A name an open
220/// object doesn't have is a trap: the config may add it.
221pub fn has(o: &IndexMap<String, Value>, key: &str) -> bool {
222    if o.contains_key(key) {
223        return true;
224    }
225    if is_open(o) {
226        hit(format!("{OPEN_PREFIX}{key}"));
227    }
228    false
229}
230
231/// A listing of all of `o`'s properties. True when it recorded a trap: the
232/// caller's result will be refused, so a walk of the data can stop there.
233pub fn entries(o: &IndexMap<String, Value>) -> bool {
234    let mut trapped = false;
235    let mut item_known = None;
236    for key in TRAP_KEYS {
237        if matches!(o.get(key), Some(Value::Undefined)) {
238            // An item's content can be listed when a source has it; the
239            // listing still trips on `template`.
240            if CONTENT_KEYS.contains(&key) {
241                let known = *item_known.get_or_insert_with(|| {
242                    SOURCE.with(|s| {
243                        s.borrow()
244                            .as_ref()
245                            .is_some_and(|src| src.content(object_id(o)).is_some())
246                    })
247                });
248                if known {
249                    continue;
250                }
251            }
252            hit(format!("{ITEM_PREFIX}{key}"));
253            trapped = true;
254        }
255    }
256    if is_open(o) {
257        hit(format!("{OPEN_PREFIX}*"));
258        trapped = true;
259    }
260    trapped
261}
262
263#[cfg(test)]
264mod tests {
265    use super::*;
266
267    struct One(usize, Content);
268
269    impl ContentSource for One {
270        fn content(&self, item: usize) -> Option<Content> {
271            (item == self.0).then(|| self.1.clone())
272        }
273    }
274
275    fn item() -> IndexMap<String, Value> {
276        let mut o = IndexMap::new();
277        o.insert("templateContent".to_string(), Value::Undefined);
278        o.insert("content".to_string(), Value::Undefined);
279        o.insert("template".to_string(), Value::Undefined);
280        o
281    }
282
283    #[test]
284    fn a_source_answers_content_reads_and_records_them() {
285        let o = item();
286        let id = object_id(&o);
287        let ready = Value::String("<p>x</p>".into());
288        {
289            let _g = install(Arc::new(One(id, Content::Ready(ready.clone()))));
290            clear();
291            let got = read(&o, "content", o.get("content").cloned());
292            assert_eq!(got, Some(ready.clone()));
293            assert_eq!(take_item_reads(), vec![(id, Outcome::Ready)]);
294            assert!(take().is_empty());
295        }
296        // Without a source, the same read is a trap.
297        clear();
298        let got = read(&o, "templateContent", o.get("templateContent").cloned());
299        assert_eq!(got, Some(Value::Undefined));
300        assert_eq!(take(), vec!["item.templateContent".to_string()]);
301    }
302
303    #[test]
304    fn pending_and_refused_reads_give_undefined() {
305        let o = item();
306        let id = object_id(&o);
307        for (content, outcome) in [
308            (Content::Pending, Outcome::Pending),
309            (Content::Refused, Outcome::Refused),
310        ] {
311            let _g = install(Arc::new(One(id, content)));
312            clear();
313            let got = read(&o, "templateContent", Some(Value::Undefined));
314            assert_eq!(got, Some(Value::Undefined));
315            assert_eq!(take_item_reads(), vec![(id, outcome)]);
316            assert!(take().is_empty());
317        }
318    }
319
320    #[test]
321    fn listing_a_known_item_trips_only_on_template() {
322        let o = item();
323        let id = object_id(&o);
324        let _g = install(Arc::new(One(id, Content::Ready(Value::String("x".into())))));
325        clear();
326        entries(&o);
327        assert_eq!(take(), vec!["item.template".to_string()]);
328    }
329}