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