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    /// The system module in `file` — a system widget's, `Tabs.tsx`, or a
142    /// shared module's, `live.ts` — compiled as its address serves it: it
143    /// renders by name only system widgets, and each relative import is
144    /// rewritten to the imported system module's address. `None` for a
145    /// file that isn't one.
146    pub fn system(&self, file: &str) -> Option<Result<String>> {
147        let (source, imports) = system(file)?;
148        let known: Vec<String> = SYSTEM.iter().map(|(name, _)| name.to_string()).collect();
149        Some(self.compile(Path::new(file), source, &known, &imports))
150    }
151
152    /// `file`'s source and resolved imports, read again only when it changed.
153    fn read(&self, file: &Path) -> Option<Read> {
154        let meta = std::fs::metadata(file).ok().filter(|m| m.is_file())?;
155        let (changed, len) = (meta.modified().ok(), meta.len());
156        if let Some(found) = self.inner.read.lock().ok().and_then(|cache| {
157            cache
158                .get(file)
159                .filter(|r| r.changed == changed && r.len == len)
160                .cloned()
161        }) {
162            return Some(found);
163        }
164        let source: Arc<str> = std::fs::read_to_string(file).ok()?.into();
165        let folder = file.parent().unwrap_or(file);
166        let specifiers = relative_imports(file, &source);
167        let specified = specifiers
168            .iter()
169            .map(|specifier| lexical(&folder.join(specifier)))
170            .collect();
171        let imports = specifiers
172            .into_iter()
173            .filter_map(|specifier| {
174                let base = folder.join(&specifier);
175                IMPORT_EXTENSIONS
176                    .iter()
177                    .map(|ext| PathBuf::from(format!("{}{ext}", base.display())))
178                    .find(|path| path.is_file())
179                    .and_then(|path| path.canonicalize().ok())
180                    .map(|path| (specifier, path))
181            })
182            .collect();
183        let read = Read {
184            changed,
185            len,
186            source,
187            imports,
188            specified,
189        };
190        if let Ok(mut cache) = self.inner.read.lock() {
191            if cache.len() > 4096 {
192                cache.clear();
193            }
194            cache.insert(file.to_path_buf(), read.clone());
195        }
196        Some(read)
197    }
198}
199
200/// The files a module is made from, each read once: the module and every
201/// module its relative imports reach inside the served folder. Its version
202/// and its compiled bytes both come from one snapshot, so a save landing
203/// between the two can't serve new bytes under the old version.
204#[derive(Debug)]
205pub struct Snapshot {
206    /// The served folder the files were read in.
207    served: ServedFolder,
208    /// Each file read, by its path.
209    reads: BTreeMap<PathBuf, Read>,
210    /// Where its compiles are remembered.
211    modules: Modules,
212}
213
214impl Snapshot {
215    /// The served folder the snapshot was read in.
216    pub fn served(&self) -> &ServedFolder {
217        &self.served
218    }
219
220    /// `file` and every module its relative imports reach, as read: `file`
221    /// first, then the rest in path order, each with its source. Empty when
222    /// `file` couldn't be read.
223    pub fn closure(&self, file: &Path) -> Vec<(PathBuf, Arc<str>)> {
224        let Some(root) = self.reads.get(file) else {
225            return Vec::new();
226        };
227        let mut found: BTreeMap<PathBuf, Arc<str>> = BTreeMap::new();
228        let mut queue: Vec<PathBuf> = root.imports.iter().map(|(_, p)| p.clone()).collect();
229        while let Some(next) = queue.pop() {
230            if next == file || found.contains_key(&next) || !self.served.contains(&next) {
231                continue;
232            }
233            let Some(read) = self.reads.get(&next) else {
234                continue;
235            };
236            queue.extend(read.imports.iter().map(|(_, p)| p.clone()));
237            found.insert(next, read.source.clone());
238        }
239        std::iter::once((file.to_path_buf(), root.source.clone()))
240            .chain(found)
241            .collect()
242    }
243
244    /// A module's version: a hash of its source, the sources of every module
245    /// its relative imports reach (each with its path), the widget names it
246    /// can render and devpage's build — everything its compiled bytes are
247    /// made from. [`Snapshot::address`] is the address that carries it.
248    pub fn hash(&self, file: &Path, known: &[String]) -> String {
249        let mut hash = Sha256::new();
250        hash.update(crate::addresses::BUILD);
251        hash.update(known.join("\0"));
252        for (path, source) in self.closure(file) {
253            hash.update([0]);
254            hash.update(self.name(&path).as_bytes());
255            hash.update([0]);
256            hash.update(source.as_bytes());
257        }
258        crate::addresses::short(&hash.finalize())
259    }
260
261    /// The address `file` is served at, carrying its [version](Self::hash):
262    /// the one a page names it by and an import of it asks for.
263    ///
264    /// Panics on a file outside the served folder, which has no address: a
265    /// snapshot reads and imports only modules inside it, so that is a
266    /// mistake in devpage, not in a document.
267    pub fn address(&self, file: &Path, known: &[String]) -> String {
268        let name = self.name(file);
269        address(Owned::Module {
270            mount: self.served.mount(),
271            name: &name,
272            hash: &self.hash(file, known),
273        })
274    }
275
276    /// A module's name in the served folder. Panics on one outside it, as
277    /// [`Self::address`] does: a snapshot reads only modules inside.
278    fn name(&self, file: &Path) -> String {
279        self.served
280            .name(file)
281            .unwrap_or_else(|| panic!("{} is outside the served folder", file.display()))
282    }
283
284    /// A project widget or helper, compiled as its address serves it: each
285    /// relative import rewritten to the imported module's address, made
286    /// from this same snapshot.
287    pub fn compile(&self, file: &Path, known: &[String]) -> Result<String> {
288        let read = self
289            .reads
290            .get(file)
291            .ok_or_else(|| anyhow!("{} can't be read", file.display()))?;
292        let imports = read
293            .imports
294            .iter()
295            .filter(|(_, path)| self.served.contains(path))
296            .map(|(specifier, path)| (specifier.clone(), self.address(path, known)))
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
310            .snapshot(&ServedFolder::new(served).unwrap(), file)
311            .hash(file, known)
312    }
313
314    #[test]
315    fn compiling_is_remembered_until_the_source_or_an_import_changes() {
316        let modules = Modules::default();
317        let compile_cached =
318            |path: &Path, source: &str, known: &[String], imports: &BTreeMap<String, String>| {
319                modules.compile(path, source, known, imports)
320            };
321        let path = Path::new("Same.tsx");
322        let none = BTreeMap::new();
323        let first = compile_cached(path, "export default () => <b>1</b>;", &[], &none).unwrap();
324        let again = compile_cached(path, "export default () => <b>1</b>;", &[], &none).unwrap();
325        assert_eq!(first, again);
326        let edited = compile_cached(path, "export default () => <b>2</b>;", &[], &none).unwrap();
327        assert!(edited.contains('2'), "{edited}");
328        let source = "export { x } from \"./x\";";
329        let imports = |v: &str| BTreeMap::from([("./x".to_string(), format!("/x.ts?v={v}"))]);
330        let one = compile_cached(path, source, &[], &imports("1")).unwrap();
331        let two = compile_cached(path, source, &[], &imports("2")).unwrap();
332        assert!(
333            one.contains("/x.ts?v=1") && two.contains("/x.ts?v=2"),
334            "{two}"
335        );
336        let error = compile_cached(path, "export default (", &[], &none).unwrap_err();
337        assert!(!error.to_string().is_empty());
338    }
339
340    #[test]
341    fn editing_a_helper_changes_its_importers_addresses_only() {
342        let modules = Modules::default();
343        let dir = std::env::temp_dir().join(format!("devpage-wversion-{}", std::process::id()));
344        let _ = std::fs::remove_dir_all(&dir);
345        std::fs::create_dir_all(dir.join("w")).unwrap();
346        let dir = dir.canonicalize().unwrap();
347        let w = dir.join("w");
348        std::fs::write(
349            w.join("Card.tsx"),
350            "import { label } from \"./label\";\nexport default () => label;",
351        )
352        .unwrap();
353        std::fs::write(
354            w.join("Deep.tsx"),
355            "export * from \"./Card\";\nexport default () => null;",
356        )
357        .unwrap();
358        std::fs::write(w.join("Other.tsx"), "export default () => null;").unwrap();
359        std::fs::write(w.join("label.ts"), "export const label = 1;").unwrap();
360        let known = vec!["Card".to_string(), "Deep".to_string(), "Other".to_string()];
361        let hashes = || {
362            ["Card.tsx", "Deep.tsx", "Other.tsx", "label.ts"]
363                .map(|name| module_hash(&modules, &dir, &w.join(name), &known))
364        };
365        let before = hashes();
366        // Same size, and possibly the same change time: the watcher's word is
367        // what makes it read again.
368        std::fs::write(w.join("label.ts"), "export const label = 2;").unwrap();
369        modules.forget(&w.join("label.ts"));
370        let after = hashes();
371        assert_ne!(before[0], after[0], "the widget importing it");
372        assert_ne!(before[1], after[1], "a widget importing that widget");
373        assert_eq!(before[2], after[2], "a widget that doesn't import it");
374        assert_ne!(before[3], after[3], "the helper itself");
375        // The importer names the helper by the helper's own address.
376        let card = modules
377            .snapshot(&ServedFolder::new(&dir).unwrap(), &w.join("Card.tsx"))
378            .compile(&w.join("Card.tsx"), &known)
379            .unwrap();
380        let label = modules
381            .snapshot(&ServedFolder::new(&dir).unwrap(), &w.join("label.ts"))
382            .address(&w.join("label.ts"), &known);
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 = modules
417            .snapshot(&ServedFolder::new(&dir).unwrap(), &w.join("label.ts"))
418            .address(&w.join("label.ts"), &known);
419        let compiled = modules
420            .snapshot(&ServedFolder::new(&dir).unwrap(), &other)
421            .compile(&other, &known)
422            .unwrap();
423        assert!(compiled.contains(&format!("\"{label}\"")), "{compiled}");
424        std::fs::write(w.join("label.ts"), "export const label = 2;").unwrap();
425        modules.forget(&w.join("label.ts"));
426        assert_ne!(
427            created,
428            module_hash(&modules, &dir, &other, &known),
429            "editing the helper"
430        );
431        // Removing it moves the address again.
432        let edited = module_hash(&modules, &dir, &other, &known);
433        std::fs::remove_file(w.join("label.ts")).unwrap();
434        modules.forget(&w.join("label.ts"));
435        assert_ne!(
436            edited,
437            module_hash(&modules, &dir, &other, &known),
438            "removing it"
439        );
440    }
441
442    #[test]
443    fn a_snapshot_hashes_and_compiles_what_it_read_whatever_is_saved_since() {
444        let modules = Modules::default();
445        let dir = std::env::temp_dir().join(format!("devpage-wsnap-{}", std::process::id()));
446        let _ = std::fs::remove_dir_all(&dir);
447        std::fs::create_dir_all(dir.join("w")).unwrap();
448        let dir = dir.canonicalize().unwrap();
449        let w = dir.join("w");
450        let card = w.join("Card.tsx");
451        std::fs::write(
452            &card,
453            "import { label } from \"./label\";\nexport default () => \"old\" + label;",
454        )
455        .unwrap();
456        std::fs::write(w.join("label.ts"), "export const label = 1;").unwrap();
457        let known = vec!["Card".to_string()];
458        let snapshot = modules.snapshot(&ServedFolder::new(&dir).unwrap(), &card);
459        let hash = snapshot.hash(&card, &known);
460        // Saves land between hashing and compiling.
461        std::fs::write(
462            &card,
463            "import { label } from \"./label\";\nexport default () => \"new\" + label;",
464        )
465        .unwrap();
466        std::fs::write(w.join("label.ts"), "export const label = 2;").unwrap();
467        modules.forget(&card);
468        modules.forget(&w.join("label.ts"));
469        assert_ne!(
470            hash,
471            module_hash(&modules, &dir, &card, &known),
472            "the files did change"
473        );
474        assert_eq!(hash, snapshot.hash(&card, &known));
475        let compiled = snapshot.compile(&card, &known).unwrap();
476        assert!(compiled.contains("\"old\""), "{compiled}");
477        let label = snapshot.address(&w.join("label.ts"), &known);
478        assert!(compiled.contains(&format!("\"{label}\"")), "{compiled}");
479        assert_ne!(
480            label,
481            modules
482                .snapshot(&ServedFolder::new(&dir).unwrap(), &w.join("label.ts"))
483                .address(&w.join("label.ts"), &known)
484        );
485    }
486
487    #[test]
488    fn a_module_or_import_that_links_out_of_the_served_folder_is_never_read() {
489        let top = std::env::temp_dir().join(format!("devpage-wlinkout-{}", std::process::id()));
490        let _ = std::fs::remove_dir_all(&top);
491        std::fs::create_dir_all(top.join("served/w")).unwrap();
492        std::fs::create_dir_all(top.join("outside")).unwrap();
493        let top = top.canonicalize().unwrap();
494        let (served, w) = (top.join("served"), top.join("served/w"));
495        std::fs::write(
496            top.join("outside/secret.ts"),
497            "export const secret = \"SECRET\";",
498        )
499        .unwrap();
500        std::fs::write(
501            top.join("outside/Evil.tsx"),
502            "export default () => \"EVIL\";",
503        )
504        .unwrap();
505        crate::folder::symlink(&top.join("outside/secret.ts"), &w.join("leak.ts")).unwrap();
506        crate::folder::symlink(&top.join("outside/Evil.tsx"), &w.join("Evil.tsx")).unwrap();
507        std::fs::write(
508            w.join("Card.tsx"),
509            "import { secret } from \"./leak\";\nexport default () => secret;",
510        )
511        .unwrap();
512        let modules = Modules::default();
513        let card = modules.snapshot(&ServedFolder::new(&served).unwrap(), &w.join("Card.tsx"));
514        let closure: Vec<PathBuf> = card
515            .closure(&w.join("Card.tsx"))
516            .into_iter()
517            .map(|(p, _)| p)
518            .collect();
519        assert_eq!(closure, vec![w.join("Card.tsx")]);
520        let compiled = card.compile(&w.join("Card.tsx"), &[]).unwrap();
521        assert!(!compiled.contains("SECRET"), "{compiled}");
522        let evil = modules.snapshot(&ServedFolder::new(&served).unwrap(), &w.join("Evil.tsx"));
523        assert!(evil.closure(&w.join("Evil.tsx")).is_empty());
524        assert!(evil.compile(&w.join("Evil.tsx"), &[]).is_err());
525    }
526}