1use 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
36pub const TRAP_KEYS: [&str; 5] = [
38 "templateContent",
39 "content",
40 "template",
41 "collections",
42 "rawInput",
43];
44
45pub const CONTENT_KEYS: [&str; 2] = ["templateContent", "content"];
47
48pub const ITEM_PREFIX: &str = "item.";
50pub const OPEN_PREFIX: &str = "collections.";
52
53pub const WITHHELD_PREFIX: &str = "withheld.";
55
56static OPEN: RwLock<Vec<usize>> = RwLock::new(Vec::new());
57
58static UNORDERED: RwLock<Vec<(usize, Arc<str>, bool)>> = RwLock::new(Vec::new());
61
62pub const ORDER_PREFIX: &str = "order.";
65
66static WATCHED: RwLock<Vec<usize>> = RwLock::new(Vec::new());
69static WATCHED_COUNT: AtomicUsize = AtomicUsize::new(0);
71
72static WITHHELD: LazyLock<RwLock<HashMap<usize, Arc<[String]>>>> =
74 LazyLock::new(|| RwLock::new(HashMap::new()));
75static WITHHELD_COUNT: AtomicUsize = AtomicUsize::new(0);
77
78#[derive(Debug, Clone)]
80pub enum Content {
81 Ready(Value),
83 Pending,
86 Refused,
88}
89
90#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92pub enum Outcome {
93 Ready,
94 Pending,
95 Refused,
96}
97
98pub trait ContentSource: Send + Sync {
101 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
113pub 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
132pub 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
148pub 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
162pub 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
171pub 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
187pub 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
204fn partial_reason(o: &IndexMap<String, Value>) -> Option<Arc<str>> {
207 unordered_entry(o).and_then(|(why, partial)| partial.then_some(why))
208}
209
210pub fn is_guarded_object(o: &IndexMap<String, Value>) -> bool {
212 is_open(o) || unordered_reason(o).is_some()
213}
214
215fn 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
226pub 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
249pub fn withheld_keys(o: &IndexMap<String, Value>) -> Option<Arc<[String]>> {
251 withheld(o)
252}
253
254pub fn is_open_object(o: &IndexMap<String, Value>) -> bool {
256 is_open(o)
257}
258
259fn 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
271fn 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
282pub 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
292pub 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
303pub fn clear() {
305 HITS.with(|h| h.borrow_mut().clear());
306}
307
308pub fn take() -> Vec<String> {
310 HITS.with(|h| std::mem::take(&mut *h.borrow_mut()).into_iter().collect())
311}
312
313pub struct SourceGuard(Option<Arc<dyn ContentSource>>);
316
317pub 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
331pub fn take_item_reads() -> Vec<(usize, Outcome)> {
334 ITEM_READS.with(|r| std::mem::take(&mut *r.borrow_mut()))
335}
336
337fn 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
351pub 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
387pub 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
402pub 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
410pub 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
428pub 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
445pub 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 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 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}