Skip to main content

devpage_core/widgets/
modules.rs

1//! The module cache: what was read of each project widget and helper, and
2//! what each compiled to, kept until a file changes — so a widget is read and
3//! compiled once per change rather than once per request. One cache belongs to
4//! one served folder's [index](crate::index::Index), which forgets a file when
5//! the watcher says it changed.
6
7use std::collections::{BTreeMap, HashMap};
8use std::hash::{Hash, Hasher};
9use std::path::{Path, PathBuf};
10use std::sync::{Arc, Mutex};
11
12use anyhow::{Result, anyhow};
13use sha2::{Digest, Sha256};
14
15use super::compile::{compile, relative_imports};
16use super::{SYSTEM, system};
17use crate::addresses::{Owned, address};
18use crate::served::{Served, ServedFolder};
19
20/// What was read and compiled, shared by every handle to it.
21#[derive(Clone, Default)]
22pub struct Modules {
23    inner: Arc<Caches>,
24}
25
26#[derive(Default)]
27struct Caches {
28    read: Mutex<HashMap<PathBuf, Read>>,
29    /// Compiled modules, by a hash of what went into them.
30    compiled: Mutex<HashMap<u64, Result<String, String>>>,
31}
32
33impl std::fmt::Debug for Modules {
34    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
35        f.write_str("Modules")
36    }
37}
38
39/// A module file as last read: its source and the files its relative imports
40/// name, remembered until its change time or size moves or the cache is told
41/// it — or a file one of its imports could name — changed.
42#[derive(Clone, Debug)]
43struct Read {
44    changed: Option<std::time::SystemTime>,
45    len: u64,
46    source: Arc<str>,
47    /// Each relative specifier and the file it names, when there is one.
48    imports: Vec<(String, PathBuf)>,
49    /// Each relative specifier's path, resolved or not: a file created or
50    /// removed at one of them, with or without an extension [`Modules::read`]
51    /// tries, changes what the module imports.
52    specified: Vec<PathBuf>,
53}
54
55/// The extensions a relative specifier is tried with, in order.
56const IMPORT_EXTENSIONS: [&str; 3] = ["", ".tsx", ".ts"];
57
58impl Modules {
59    /// Reads `file` and every module its relative imports reach inside the
60    /// served folder `served`, each once. A file that resolves outside the
61    /// folder — through `..` or a symbolic link — is never read.
62    pub fn snapshot(&self, served: impl Served, file: &Path) -> Snapshot {
63        let served = served.served();
64        let mut reads = BTreeMap::new();
65        let mut queue = vec![file.to_path_buf()];
66        while let Some(next) = queue.pop() {
67            if reads.contains_key(&next) || served.file(&next).is_none() {
68                continue;
69            }
70            let Some(read) = self.read(&next) else {
71                continue;
72            };
73            queue.extend(read.imports.iter().map(|(_, p)| p.clone()));
74            reads.insert(next, read);
75        }
76        Snapshot {
77            served,
78            reads,
79            modules: self.clone(),
80        }
81    }
82
83    /// Forgets what was read of `file`, so the next address or compile reads it
84    /// again, and what was read of every module with an import that could name
85    /// it, so a helper created or removed after its importer was read changes
86    /// what the importer imports. Called for every changed file: a change time
87    /// can miss an edit made within its resolution that keeps the size.
88    pub fn forget(&self, file: &Path) {
89        let file = lexical(file);
90        if let Ok(mut cache) = self.inner.read.lock() {
91            cache.remove(&file);
92            cache.retain(|_, read| {
93                !read.specified.iter().any(|base| {
94                    IMPORT_EXTENSIONS
95                        .iter()
96                        .any(|ext| file.as_os_str() == format!("{}{ext}", base.display()).as_str())
97                })
98            });
99        }
100    }
101
102    /// [`compile`], remembered: the same file, source, widget names and import
103    /// addresses compile once.
104    pub fn compile(
105        &self,
106        path: &Path,
107        source: &str,
108        known: &[String],
109        imports: &BTreeMap<String, String>,
110    ) -> Result<String> {
111        let mut hasher = std::collections::hash_map::DefaultHasher::new();
112        (path, source, known, imports).hash(&mut hasher);
113        let key = hasher.finish();
114        if let Some(found) = self
115            .inner
116            .compiled
117            .lock()
118            .ok()
119            .and_then(|cache| cache.get(&key).cloned())
120        {
121            return found.map_err(|e| anyhow!(e));
122        }
123        let result = compile(path, source, known, imports).map_err(|e| e.to_string());
124        if let Ok(mut cache) = self.inner.compiled.lock() {
125            // A long session edits many versions; start over rather than grow.
126            if cache.len() > 512 {
127                cache.clear();
128            }
129            cache.insert(key, result.clone());
130        }
131        result.map_err(|e| anyhow!(e))
132    }
133
134    /// A system widget, compiled as its address serves it — system widgets
135    /// compose only each other. `None` for a name that isn't one.
136    pub fn system(&self, name: &str) -> Option<Result<String>> {
137        let source = system(name)?;
138        let known: Vec<String> = SYSTEM.iter().map(|(name, _)| name.to_string()).collect();
139        Some(self.compile(
140            Path::new(&format!("{name}.tsx")),
141            source,
142            &known,
143            &Default::default(),
144        ))
145    }
146
147    /// `file`'s source and resolved imports, read again only when it changed.
148    fn read(&self, file: &Path) -> Option<Read> {
149        let meta = std::fs::metadata(file).ok().filter(|m| m.is_file())?;
150        let (changed, len) = (meta.modified().ok(), meta.len());
151        if let Some(found) = self.inner.read.lock().ok().and_then(|cache| {
152            cache
153                .get(file)
154                .filter(|r| r.changed == changed && r.len == len)
155                .cloned()
156        }) {
157            return Some(found);
158        }
159        let source: Arc<str> = std::fs::read_to_string(file).ok()?.into();
160        let folder = file.parent().unwrap_or(file);
161        let specifiers = relative_imports(file, &source);
162        let specified = specifiers
163            .iter()
164            .map(|specifier| lexical(&folder.join(specifier)))
165            .collect();
166        let imports = specifiers
167            .into_iter()
168            .filter_map(|specifier| {
169                let base = folder.join(&specifier);
170                IMPORT_EXTENSIONS
171                    .iter()
172                    .map(|ext| PathBuf::from(format!("{}{ext}", base.display())))
173                    .find(|path| path.is_file())
174                    .and_then(|path| path.canonicalize().ok())
175                    .map(|path| (specifier, path))
176            })
177            .collect();
178        let read = Read {
179            changed,
180            len,
181            source,
182            imports,
183            specified,
184        };
185        if let Ok(mut cache) = self.inner.read.lock() {
186            if cache.len() > 4096 {
187                cache.clear();
188            }
189            cache.insert(file.to_path_buf(), read.clone());
190        }
191        Some(read)
192    }
193}
194
195/// `path` with its `.` and `..` components resolved by name, not on disk: a
196/// specifier's path when the file it names may not exist.
197fn lexical(path: &Path) -> PathBuf {
198    use std::path::Component;
199    let mut out = PathBuf::new();
200    for component in path.components() {
201        match component {
202            Component::CurDir => {}
203            Component::ParentDir => {
204                out.pop();
205            }
206            other => out.push(other),
207        }
208    }
209    out
210}
211
212/// The files a module is made from, each read once: the module and every
213/// module its relative imports reach inside the served folder. Its version
214/// and its compiled bytes both come from one snapshot, so a save landing
215/// between the two can't serve new bytes under the old version.
216#[derive(Debug)]
217pub struct Snapshot {
218    served: ServedFolder,
219    reads: BTreeMap<PathBuf, Read>,
220    /// Where its compiles are remembered.
221    modules: Modules,
222}
223
224impl Snapshot {
225    /// The served folder the snapshot was read in.
226    pub fn served(&self) -> &ServedFolder {
227        &self.served
228    }
229
230    /// `file` and every module its relative imports reach, as read: `file`
231    /// first, then the rest in path order, each with its source. Empty when
232    /// `file` couldn't be read.
233    pub fn closure(&self, file: &Path) -> Vec<(PathBuf, Arc<str>)> {
234        let Some(root) = self.reads.get(file) else {
235            return Vec::new();
236        };
237        let mut found: BTreeMap<PathBuf, Arc<str>> = BTreeMap::new();
238        let mut queue: Vec<PathBuf> = root.imports.iter().map(|(_, p)| p.clone()).collect();
239        while let Some(next) = queue.pop() {
240            if next == file || found.contains_key(&next) || !self.served.contains(&next) {
241                continue;
242            }
243            let Some(read) = self.reads.get(&next) else {
244                continue;
245            };
246            queue.extend(read.imports.iter().map(|(_, p)| p.clone()));
247            found.insert(next, read.source.clone());
248        }
249        std::iter::once((file.to_path_buf(), root.source.clone()))
250            .chain(found)
251            .collect()
252    }
253
254    /// A module's version: a hash of its source, the sources of every module
255    /// its relative imports reach (each with its path), the widget names it
256    /// can render and devpage's build — everything its compiled bytes are
257    /// made from. [`address`] is the address that carries it.
258    pub fn hash(&self, file: &Path, known: &[String]) -> String {
259        let mut hash = Sha256::new();
260        hash.update(crate::addresses::BUILD);
261        hash.update(known.join("\0"));
262        for (path, source) in self.closure(file) {
263            hash.update([0]);
264            hash.update(
265                self.served
266                    .relative(&path)
267                    .unwrap_or(&path)
268                    .to_string_lossy()
269                    .as_bytes(),
270            );
271            hash.update([0]);
272            hash.update(source.as_bytes());
273        }
274        crate::addresses::short(&hash.finalize())
275    }
276
277    /// A project widget or helper, compiled as its address serves it: each
278    /// relative import rewritten to the imported module's address, made
279    /// from this same snapshot.
280    pub fn compile(&self, file: &Path, known: &[String]) -> Result<String> {
281        let read = self
282            .reads
283            .get(file)
284            .ok_or_else(|| anyhow!("{} can't be read", file.display()))?;
285        let imports = read
286            .imports
287            .iter()
288            .filter(|(_, path)| self.served.contains(path))
289            .map(|(specifier, path)| {
290                let url = address(Owned::Module {
291                    snapshot: self,
292                    file: path,
293                    known,
294                });
295                (specifier.clone(), url)
296            })
297            .collect();
298        self.modules.compile(file, &read.source, known, &imports)
299    }
300}
301
302#[cfg(test)]
303mod tests {
304    use super::*;
305    use crate::widgets::is_widget_file;
306
307    /// [`Snapshot::hash`] of `file`, read now.
308    fn module_hash(modules: &Modules, served: &Path, file: &Path, known: &[String]) -> String {
309        modules.snapshot(served, file).hash(file, known)
310    }
311
312    #[test]
313    fn compiling_is_remembered_until_the_source_or_an_import_changes() {
314        let modules = Modules::default();
315        let compile_cached =
316            |path: &Path, source: &str, known: &[String], imports: &BTreeMap<String, String>| {
317                modules.compile(path, source, known, imports)
318            };
319        let path = Path::new("Same.tsx");
320        let none = BTreeMap::new();
321        let first = compile_cached(path, "export default () => <b>1</b>;", &[], &none).unwrap();
322        let again = compile_cached(path, "export default () => <b>1</b>;", &[], &none).unwrap();
323        assert_eq!(first, again);
324        let edited = compile_cached(path, "export default () => <b>2</b>;", &[], &none).unwrap();
325        assert!(edited.contains('2'), "{edited}");
326        let source = "export { x } from \"./x\";";
327        let imports = |v: &str| BTreeMap::from([("./x".to_string(), format!("/x.ts?v={v}"))]);
328        let one = compile_cached(path, source, &[], &imports("1")).unwrap();
329        let two = compile_cached(path, source, &[], &imports("2")).unwrap();
330        assert!(
331            one.contains("/x.ts?v=1") && two.contains("/x.ts?v=2"),
332            "{two}"
333        );
334        let error = compile_cached(path, "export default (", &[], &none).unwrap_err();
335        assert!(!error.to_string().is_empty());
336    }
337
338    #[test]
339    fn editing_a_helper_changes_its_importers_addresses_only() {
340        let modules = Modules::default();
341        let dir = std::env::temp_dir().join(format!("devpage-wversion-{}", std::process::id()));
342        let _ = std::fs::remove_dir_all(&dir);
343        std::fs::create_dir_all(dir.join("w")).unwrap();
344        let dir = dir.canonicalize().unwrap();
345        let w = dir.join("w");
346        std::fs::write(
347            w.join("Card.tsx"),
348            "import { label } from \"./label\";\nexport default () => label;",
349        )
350        .unwrap();
351        std::fs::write(
352            w.join("Deep.tsx"),
353            "export * from \"./Card\";\nexport default () => null;",
354        )
355        .unwrap();
356        std::fs::write(w.join("Other.tsx"), "export default () => null;").unwrap();
357        std::fs::write(w.join("label.ts"), "export const label = 1;").unwrap();
358        let known = vec!["Card".to_string(), "Deep".to_string(), "Other".to_string()];
359        let hashes = || {
360            ["Card.tsx", "Deep.tsx", "Other.tsx", "label.ts"]
361                .map(|name| module_hash(&modules, &dir, &w.join(name), &known))
362        };
363        let before = hashes();
364        // Same size, and possibly the same change time: the watcher's word is
365        // what makes it read again.
366        std::fs::write(w.join("label.ts"), "export const label = 2;").unwrap();
367        modules.forget(&w.join("label.ts"));
368        let after = hashes();
369        assert_ne!(before[0], after[0], "the widget importing it");
370        assert_ne!(before[1], after[1], "a widget importing that widget");
371        assert_eq!(before[2], after[2], "a widget that doesn't import it");
372        assert_ne!(before[3], after[3], "the helper itself");
373        // The importer names the helper by the helper's own address.
374        let card = modules
375            .snapshot(&dir, &w.join("Card.tsx"))
376            .compile(&w.join("Card.tsx"), &known)
377            .unwrap();
378        let label = address(Owned::Module {
379            snapshot: &modules.snapshot(&dir, &w.join("label.ts")),
380            file: &w.join("label.ts"),
381            known: &known,
382        });
383        assert!(card.contains(&format!("\"{label}\"")), "{card}");
384        assert!(label.ends_with(&format!("?v={}", after[3])), "{label}");
385        // The names a widget can render are part of what it is compiled from.
386        assert_ne!(
387            module_hash(&modules, &dir, &w.join("Other.tsx"), &known[..2]),
388            after[2]
389        );
390        assert!(is_widget_file(&w.join("label.ts"), &w));
391        assert!(!is_widget_file(&w.join("notes.md"), &w));
392    }
393
394    #[test]
395    fn a_helper_created_after_its_importer_moves_the_importers_address() {
396        let modules = Modules::default();
397        let dir = std::env::temp_dir().join(format!("devpage-wlate-{}", std::process::id()));
398        let _ = std::fs::remove_dir_all(&dir);
399        std::fs::create_dir_all(dir.join("w")).unwrap();
400        let dir = dir.canonicalize().unwrap();
401        let w = dir.join("w");
402        let other = w.join("Other.tsx");
403        std::fs::write(
404            &other,
405            "import { label } from \"./label\";\nexport default () => label;",
406        )
407        .unwrap();
408        let known = vec!["Other".to_string()];
409        // Read while `./label` names nothing.
410        let missing = module_hash(&modules, &dir, &other, &known);
411        // The watcher reports the created file, then each edit to it.
412        std::fs::write(w.join("label.ts"), "export const label = 1;").unwrap();
413        modules.forget(&w.join("label.ts"));
414        let created = module_hash(&modules, &dir, &other, &known);
415        assert_ne!(missing, created, "creating the helper");
416        let label = address(Owned::Module {
417            snapshot: &modules.snapshot(&dir, &w.join("label.ts")),
418            file: &w.join("label.ts"),
419            known: &known,
420        });
421        let compiled = modules
422            .snapshot(&dir, &other)
423            .compile(&other, &known)
424            .unwrap();
425        assert!(compiled.contains(&format!("\"{label}\"")), "{compiled}");
426        std::fs::write(w.join("label.ts"), "export const label = 2;").unwrap();
427        modules.forget(&w.join("label.ts"));
428        assert_ne!(
429            created,
430            module_hash(&modules, &dir, &other, &known),
431            "editing the helper"
432        );
433        // Removing it moves the address again.
434        let edited = module_hash(&modules, &dir, &other, &known);
435        std::fs::remove_file(w.join("label.ts")).unwrap();
436        modules.forget(&w.join("label.ts"));
437        assert_ne!(
438            edited,
439            module_hash(&modules, &dir, &other, &known),
440            "removing it"
441        );
442    }
443
444    #[test]
445    fn a_snapshot_hashes_and_compiles_what_it_read_whatever_is_saved_since() {
446        let modules = Modules::default();
447        let dir = std::env::temp_dir().join(format!("devpage-wsnap-{}", std::process::id()));
448        let _ = std::fs::remove_dir_all(&dir);
449        std::fs::create_dir_all(dir.join("w")).unwrap();
450        let dir = dir.canonicalize().unwrap();
451        let w = dir.join("w");
452        let card = w.join("Card.tsx");
453        std::fs::write(
454            &card,
455            "import { label } from \"./label\";\nexport default () => \"old\" + label;",
456        )
457        .unwrap();
458        std::fs::write(w.join("label.ts"), "export const label = 1;").unwrap();
459        let known = vec!["Card".to_string()];
460        let snapshot = modules.snapshot(&dir, &card);
461        let hash = snapshot.hash(&card, &known);
462        // Saves land between hashing and compiling.
463        std::fs::write(
464            &card,
465            "import { label } from \"./label\";\nexport default () => \"new\" + label;",
466        )
467        .unwrap();
468        std::fs::write(w.join("label.ts"), "export const label = 2;").unwrap();
469        modules.forget(&card);
470        modules.forget(&w.join("label.ts"));
471        assert_ne!(
472            hash,
473            module_hash(&modules, &dir, &card, &known),
474            "the files did change"
475        );
476        assert_eq!(hash, snapshot.hash(&card, &known));
477        let compiled = snapshot.compile(&card, &known).unwrap();
478        assert!(compiled.contains("\"old\""), "{compiled}");
479        let label = address(Owned::Module {
480            snapshot: &snapshot,
481            file: &w.join("label.ts"),
482            known: &known,
483        });
484        assert!(compiled.contains(&format!("\"{label}\"")), "{compiled}");
485        assert_ne!(
486            label,
487            address(Owned::Module {
488                snapshot: &modules.snapshot(&dir, &w.join("label.ts")),
489                file: &w.join("label.ts"),
490                known: &known,
491            })
492        );
493    }
494
495    #[cfg(unix)]
496    #[test]
497    fn a_module_or_import_that_links_out_of_the_served_folder_is_never_read() {
498        let top = std::env::temp_dir().join(format!("devpage-wlinkout-{}", std::process::id()));
499        let _ = std::fs::remove_dir_all(&top);
500        std::fs::create_dir_all(top.join("served/w")).unwrap();
501        std::fs::create_dir_all(top.join("outside")).unwrap();
502        let top = top.canonicalize().unwrap();
503        let (served, w) = (top.join("served"), top.join("served/w"));
504        std::fs::write(
505            top.join("outside/secret.ts"),
506            "export const secret = \"SECRET\";",
507        )
508        .unwrap();
509        std::fs::write(
510            top.join("outside/Evil.tsx"),
511            "export default () => \"EVIL\";",
512        )
513        .unwrap();
514        std::os::unix::fs::symlink(top.join("outside/secret.ts"), w.join("leak.ts")).unwrap();
515        std::os::unix::fs::symlink(top.join("outside/Evil.tsx"), w.join("Evil.tsx")).unwrap();
516        std::fs::write(
517            w.join("Card.tsx"),
518            "import { secret } from \"./leak\";\nexport default () => secret;",
519        )
520        .unwrap();
521        let modules = Modules::default();
522        let card = modules.snapshot(&served, &w.join("Card.tsx"));
523        let closure: Vec<PathBuf> = card
524            .closure(&w.join("Card.tsx"))
525            .into_iter()
526            .map(|(p, _)| p)
527            .collect();
528        assert_eq!(closure, vec![w.join("Card.tsx")]);
529        let compiled = card.compile(&w.join("Card.tsx"), &[]).unwrap();
530        assert!(!compiled.contains("SECRET"), "{compiled}");
531        let evil = modules.snapshot(&served, &w.join("Evil.tsx"));
532        assert!(evil.closure(&w.join("Evil.tsx")).is_empty());
533        assert!(evil.compile(&w.join("Evil.tsx"), &[]).is_err());
534    }
535}