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