1use std::cell::RefCell;
23use std::collections::BTreeSet;
24use std::sync::{Arc, RwLock};
25
26use indexmap::IndexMap;
27
28use crate::Value;
29
30pub const TRAP_KEYS: [&str; 4] = ["templateContent", "content", "template", "collections"];
32
33pub const CONTENT_KEYS: [&str; 2] = ["templateContent", "content"];
35
36pub const ITEM_PREFIX: &str = "item.";
38pub const OPEN_PREFIX: &str = "collections.";
40
41static OPEN: RwLock<Vec<usize>> = RwLock::new(Vec::new());
42
43#[derive(Debug, Clone)]
45pub enum Content {
46 Ready(Value),
48 Pending,
51 Refused,
53}
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57pub enum Outcome {
58 Ready,
59 Pending,
60 Refused,
61}
62
63pub trait ContentSource: Send + Sync {
66 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
77pub 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
91pub 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
101pub 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
112pub fn clear() {
114 HITS.with(|h| h.borrow_mut().clear());
115}
116
117pub fn take() -> Vec<String> {
119 HITS.with(|h| std::mem::take(&mut *h.borrow_mut()).into_iter().collect())
120}
121
122pub struct SourceGuard(Option<Arc<dyn ContentSource>>);
125
126pub 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
140pub fn take_item_reads() -> Vec<(usize, Outcome)> {
143 ITEM_READS.with(|r| std::mem::take(&mut *r.borrow_mut()))
144}
145
146fn 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
160pub 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
185pub 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
200pub 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
208pub 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
219pub 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
231pub 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 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 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}