Skip to main content

devpage_core/comments/
yaml.rs

1//! The comment store as files: one YAML file per thread,
2//! `.devpage/comments/<page>/<id>.yml`, under the served folder. It writes
3//! nothing outside `.devpage/`, and finds a thread by its id through the
4//! served folder, so a thread file that leads out of it is never read.
5//!
6//! It also remembers what each thread file held when open pages last heard
7//! of it, so a thread file is announced by the watcher only when someone
8//! other than this store changed it — a write through the store is
9//! announced once, by [`super::Comments`], and a hand edit once, by the
10//! watcher.
11
12use std::collections::HashMap;
13use std::path::{Path, PathBuf};
14use std::sync::Mutex;
15
16use anyhow::Result;
17
18use super::{Anchor, Listed, Message, Store, Thread, new_id};
19use crate::folder::{ServedFolder, slashed};
20
21/// Thread files that don't parse, each with its error.
22type Unparsable = Vec<(PathBuf, String)>;
23
24pub struct Yaml {
25    served: ServedFolder,
26    /// Each thread file's bytes as open pages last heard of them — `None`
27    /// once it is gone. Held while writing, so the watcher never reads a
28    /// write before it is remembered.
29    heard: Mutex<HashMap<PathBuf, Option<Vec<u8>>>>,
30}
31
32impl Yaml {
33    pub fn new(served: &ServedFolder) -> Self {
34        Self {
35            served: served.clone(),
36            heard: Mutex::default(),
37        }
38    }
39
40    fn root(&self) -> PathBuf {
41        self.served.path().join(".devpage")
42    }
43
44    fn comments(&self) -> PathBuf {
45        self.root().join("comments")
46    }
47
48    /// The folder holding a page's threads.
49    fn folder(&self, page: &str) -> PathBuf {
50        self.comments().join(page.trim_start_matches('/'))
51    }
52
53    /// The page a thread file is about, from its path: `/<page>` for
54    /// `.devpage/comments/<page>/<id>.yml` in the served folder.
55    fn page_of(&self, file: &Path) -> Option<String> {
56        let thread = self
57            .served
58            .relative(file)?
59            .strip_prefix(".devpage/comments")
60            .ok()?;
61        if thread.extension().is_none_or(|ext| ext != "yml") {
62            return None;
63        }
64        let page = thread
65            .parent()
66            .filter(|page| !page.as_os_str().is_empty())?;
67        Some(format!("/{}", slashed(page)))
68    }
69
70    /// Thread `id`'s file and its page, found through the served folder.
71    fn find(&self, id: &str) -> Option<(PathBuf, String)> {
72        let name = format!("{id}.yml");
73        thread_files(&self.comments())
74            .into_iter()
75            .filter(|file| file.file_name().is_some_and(|n| n == name.as_str()))
76            .filter_map(|file| self.served.file(&file))
77            .find_map(|file| self.page_of(&file).map(|page| (file, page)))
78    }
79
80    /// Creates `.devpage/` with a `.gitignore` that keeps git away from it.
81    fn prepare(&self) -> Result<()> {
82        std::fs::create_dir_all(self.root())?;
83        let ignore = self.root().join(".gitignore");
84        if !ignore.exists() {
85            std::fs::write(ignore, "*\n")?;
86        }
87        Ok(())
88    }
89
90    /// The page's threads, and the thread files that don't parse with why.
91    fn read(&self, page: &str) -> (Vec<Listed>, Unparsable) {
92        let Ok(entries) = std::fs::read_dir(self.folder(page)) else {
93            return Default::default();
94        };
95        let (mut listed, mut broken) = (Vec::new(), Vec::new());
96        for entry in entries.flatten() {
97            let path = entry.path();
98            if path.extension().is_none_or(|ext| ext != "yml") {
99                continue;
100            }
101            match parse(&path) {
102                Ok(thread) => {
103                    let id = path
104                        .file_stem()
105                        .unwrap_or_default()
106                        .to_string_lossy()
107                        .into_owned();
108                    listed.push(Listed {
109                        id,
110                        thread,
111                        detached: false,
112                    });
113                }
114                Err(error) => broken.push((path, format!("{error:#}"))),
115            }
116        }
117        listed.sort_by(|a, b| a.id.cmp(&b.id));
118        broken.sort();
119        (listed, broken)
120    }
121
122    /// Writes `thread` to `file`, remembering it as heard.
123    fn write(&self, file: PathBuf, thread: &Thread) -> Result<()> {
124        let bytes = serde_yaml::to_string(thread)?.into_bytes();
125        let mut heard = self.heard.lock().unwrap_or_else(|p| p.into_inner());
126        std::fs::write(&file, &bytes)?;
127        heard.insert(file, Some(bytes));
128        Ok(())
129    }
130
131    /// Whether open pages have yet to hear of the thread file at `path` as it
132    /// is now — true for a file someone else changed, false for one this
133    /// store just wrote or deleted. Asking marks it heard: whoever asks
134    /// announces it.
135    fn unheard(&self, path: &Path) -> bool {
136        let mut heard = self.heard.lock().unwrap_or_else(|p| p.into_inner());
137        let now = std::fs::read(path).ok();
138        if heard.get(path) == Some(&now) {
139            return false;
140        }
141        heard.insert(path.to_path_buf(), now);
142        true
143    }
144}
145
146fn parse(file: &Path) -> Result<Thread> {
147    Ok(serde_yaml::from_str(&std::fs::read_to_string(file)?)?)
148}
149
150/// Every `.yml` file under `folder`, not following symbolic links to folders.
151fn thread_files(folder: &Path) -> Vec<PathBuf> {
152    let mut found = Vec::new();
153    let mut folders = vec![folder.to_path_buf()];
154    while let Some(folder) = folders.pop() {
155        let Ok(entries) = std::fs::read_dir(&folder) else {
156            continue;
157        };
158        for entry in entries.flatten() {
159            let path = entry.path();
160            match entry.file_type() {
161                Ok(kind) if kind.is_dir() => folders.push(path),
162                _ if path.extension().is_some_and(|ext| ext == "yml") => found.push(path),
163                _ => {}
164            }
165        }
166    }
167    found.sort();
168    found
169}
170
171impl Store for Yaml {
172    /// A thread file that doesn't parse is left out — and left alone;
173    /// [`problems`] names it.
174    fn list(&self, page: &str) -> Result<Vec<Listed>> {
175        Ok(self.read(page).0)
176    }
177
178    fn create(&self, page: &str, anchor: Anchor, first: Message) -> Result<String> {
179        self.prepare()?;
180        let id = new_id();
181        let file = self.folder(page).join(format!("{id}.yml"));
182        std::fs::create_dir_all(file.parent().unwrap())?;
183        let thread = Thread {
184            anchor,
185            thread: vec![first],
186        };
187        self.write(file, &thread)?;
188        Ok(id)
189    }
190
191    fn reply(&self, id: &str, message: Message) -> Result<Option<String>> {
192        let Some((file, page)) = self.find(id) else {
193            return Ok(None);
194        };
195        let mut thread = parse(&file)?;
196        thread.thread.push(message);
197        self.write(file, &thread)?;
198        Ok(Some(page))
199    }
200
201    /// Resolving a thread deletes its file.
202    fn resolve(&self, id: &str) -> Result<Option<String>> {
203        let Some((file, page)) = self.find(id) else {
204            return Ok(None);
205        };
206        let mut heard = self.heard.lock().unwrap_or_else(|p| p.into_inner());
207        std::fs::remove_file(&file)?;
208        heard.insert(file, None);
209        Ok(Some(page))
210    }
211
212    /// Every thread that parses: a served folder's threads are never
213    /// detached.
214    fn attached(&self) -> Result<Vec<(String, Listed)>> {
215        Ok(thread_files(&self.comments())
216            .into_iter()
217            .filter_map(|file| self.served.file(&file))
218            .filter_map(|file| {
219                let page = self.page_of(&file)?;
220                let thread = parse(&file).ok()?;
221                let id = file.file_stem()?.to_string_lossy().into_owned();
222                Some((
223                    page,
224                    Listed {
225                        id,
226                        thread,
227                        detached: false,
228                    },
229                ))
230            })
231            .collect())
232    }
233
234    fn heard(&self, paths: &[PathBuf]) -> Vec<String> {
235        paths
236            .iter()
237            .filter_map(|path| self.page_of(path).filter(|_| self.unheard(path)))
238            .collect()
239    }
240}
241
242/// The page's thread files that don't parse, as problems: listed on the page
243/// in the preview and reported by `devpage check`.
244pub fn problems(document: &crate::document::Document, page: &Path) -> Vec<crate::problem::Problem> {
245    let store = Yaml::new(&document.served);
246    // A page names its threads by its path in the served folder, whatever
247    // the folder's mount; a page outside it has none.
248    let Some(name) = document.name(page) else {
249        return Vec::new();
250    };
251    let (_, unparsable) = store.read(&format!("/{name}"));
252    unparsable
253        .into_iter()
254        .map(|(file, error)| crate::problem::Problem {
255            // Read from the page's folder of threads, so inside by
256            // construction.
257            file: document
258                .name(&file)
259                .unwrap_or_else(|| panic!("{} is outside the served folder", file.display())),
260            line: None,
261            message: format!("comment thread doesn't parse — {error}"),
262            target: None,
263        })
264        .collect()
265}
266
267#[cfg(test)]
268mod tests {
269    use super::*;
270    use crate::folder::ServedFolder;
271    use std::process::Command;
272
273    fn git(repo: &Path, args: &[&str]) -> String {
274        let output = Command::new("git")
275            .arg("-C")
276            .arg(repo)
277            .args(args)
278            .output()
279            .unwrap();
280        String::from_utf8_lossy(&output.stdout).into_owned()
281    }
282
283    fn anchor() -> Anchor {
284        Anchor {
285            quote: "retries".into(),
286            prefix: "The client ".into(),
287            suffix: ".".into(),
288        }
289    }
290
291    fn message(author: &str, text: &str) -> Message {
292        Message {
293            author: author.into(),
294            at: "2026-10-25T18:15:02Z".into(),
295            text: text.into(),
296        }
297    }
298
299    /// A fresh served folder at a temporary path named for `name`.
300    fn served(name: &str) -> ServedFolder {
301        let root = std::env::temp_dir().join(format!("devpage-{name}-{}", std::process::id()));
302        let _ = std::fs::remove_dir_all(&root);
303        std::fs::create_dir_all(&root).unwrap();
304        ServedFolder::new(&root).unwrap()
305    }
306
307    #[test]
308    fn a_thread_lives_and_dies_without_touching_the_repository() {
309        let served = served("yaml-repo");
310        let repo = served.path();
311        std::fs::create_dir_all(repo.join("docs")).unwrap();
312        std::fs::write(repo.join("docs/a.md"), "# A\n\nThe client retries.\n").unwrap();
313        git(repo, &["init", "-q"]);
314        git(repo, &["add", "."]);
315        git(
316            repo,
317            &[
318                "-c",
319                "user.name=t",
320                "-c",
321                "user.email=t@t",
322                "commit",
323                "-qm",
324                "x",
325            ],
326        );
327
328        let store = Yaml::new(&served);
329        let id = store
330            .create("/docs/a.md", anchor(), message("Ana", "Every write?"))
331            .unwrap();
332        assert_eq!(
333            store
334                .reply(&id, message("Bo", "Only the outbox."))
335                .unwrap()
336                .as_deref(),
337            Some("/docs/a.md"),
338            "found by its id alone"
339        );
340        let listed = store.list("/docs/a.md").unwrap();
341        assert_eq!(listed.len(), 1);
342        assert_eq!(listed[0].thread.anchor, anchor());
343        assert_eq!(listed[0].thread.thread[1].author, "Bo");
344        assert!(
345            repo.join(format!(".devpage/comments/docs/a.md/{id}.yml"))
346                .is_file()
347        );
348        assert_eq!(
349            git(repo, &["status", "--porcelain"]),
350            "",
351            "git sees nothing"
352        );
353
354        assert_eq!(store.resolve(&id).unwrap().as_deref(), Some("/docs/a.md"));
355        assert!(store.list("/docs/a.md").unwrap().is_empty());
356        assert_eq!(store.resolve(&id).unwrap(), None);
357        assert_eq!(store.reply(&id, message("Bo", "gone")).unwrap(), None);
358    }
359
360    #[test]
361    fn a_thread_file_reached_through_a_link_out_of_the_folder_is_never_found() {
362        let served = served("yaml-link");
363        let outside =
364            std::env::temp_dir().join(format!("devpage-yaml-outside-{}", std::process::id()));
365        let _ = std::fs::remove_dir_all(&outside);
366        std::fs::create_dir_all(&outside).unwrap();
367        let id = "20261025T000000Z-0000";
368        std::fs::write(
369            outside.join(format!("{id}.yml")),
370            "anchor:\n  quote: x\nthread: []\n",
371        )
372        .unwrap();
373        let folder = served.path().join(".devpage/comments/a.md");
374        std::fs::create_dir_all(&folder).unwrap();
375        crate::folder::symlink(
376            &outside.join(format!("{id}.yml")),
377            &folder.join(format!("{id}.yml")),
378        )
379        .unwrap();
380        let store = Yaml::new(&served);
381        assert_eq!(store.reply(id, message("Bo", "out")).unwrap(), None);
382        assert_eq!(store.resolve(id).unwrap(), None);
383        assert!(outside.join(format!("{id}.yml")).is_file(), "left alone");
384    }
385
386    #[test]
387    fn a_thread_file_is_the_yaml_it_always_was() {
388        let served = served("yaml-format");
389        let root = served.path();
390        let store = Yaml::new(&served);
391        let id = store
392            .create("/a.md", anchor(), message("Ana", "Every write?"))
393            .unwrap();
394        store.reply(&id, message("Bo", "Only the outbox.")).unwrap();
395        let file = root.join(format!(".devpage/comments/a.md/{id}.yml"));
396        let text = std::fs::read_to_string(file).unwrap();
397        assert_eq!(
398            text,
399            "anchor:\n  quote: retries\n  prefix: 'The client '\n  suffix: .\nthread:\n\
400             - author: Ana\n  at: 2026-10-25T18:15:02Z\n  text: Every write?\n\
401             - author: Bo\n  at: 2026-10-25T18:15:02Z\n  text: Only the outbox.\n"
402        );
403        assert_eq!(
404            std::fs::read_to_string(root.join(".devpage/.gitignore")).unwrap(),
405            "*\n"
406        );
407    }
408
409    #[test]
410    fn a_thread_file_that_doesnt_parse_is_named_and_left_alone() {
411        let served = served("yaml-unparsable");
412        let root = served.path();
413        let store = Yaml::new(&served);
414        store
415            .create("/a.md", anchor(), message("Ana", "fine"))
416            .unwrap();
417        let bad = root.join(".devpage/comments/a.md/20261025T000000Z-0000.yml");
418        std::fs::write(&bad, "anchor: [not, a, mapping]\n").unwrap();
419        assert_eq!(
420            store.list("/a.md").unwrap().len(),
421            1,
422            "the good thread still lists"
423        );
424        let broken = store.read("/a.md").1;
425        assert_eq!(broken.len(), 1);
426        assert_eq!(broken[0].0, bad);
427        assert!(bad.is_file(), "left alone");
428
429        std::fs::write(root.join("a.md"), "# A\n").unwrap();
430        let document = crate::document::Document::load(&root.join("a.md"), &served).unwrap();
431        let found = problems(&document, &document.served.path().join("a.md"));
432        assert_eq!(found.len(), 1);
433        assert_eq!(
434            found[0].file,
435            ".devpage/comments/a.md/20261025T000000Z-0000.yml"
436        );
437        assert!(
438            found[0].message.starts_with("comment thread doesn't parse"),
439            "{}",
440            found[0]
441        );
442    }
443
444    #[test]
445    fn only_a_change_the_store_didnt_make_is_heard() {
446        let served = served("yaml-heard");
447        let root = served.path();
448        let store = Yaml::new(&served);
449        let id = store
450            .create("/docs/a.md", anchor(), message("Ana", "Every write?"))
451            .unwrap();
452        let file = root.join(format!(".devpage/comments/docs/a.md/{id}.yml"));
453        let heard = |path: &Path| store.heard(&[path.to_path_buf()]);
454        let a = vec!["/docs/a.md".to_string()];
455        assert!(heard(&file).is_empty(), "the store's own write");
456        store.reply(&id, message("Bo", "Only the outbox.")).unwrap();
457        assert!(heard(&file).is_empty(), "the store's own reply");
458
459        // A hand edit is heard once; asked again, it has been heard.
460        let edited =
461            std::fs::read_to_string(&file).unwrap() + "- author: Cy\n  at: x\n  text: hi\n";
462        std::fs::write(&file, &edited).unwrap();
463        assert_eq!(heard(&file), a, "a hand edit");
464        assert!(heard(&file).is_empty(), "the same edit, heard");
465
466        // Editing it back to what the store wrote is a change pages haven't seen.
467        store.reply(&id, message("Bo", "Again.")).unwrap();
468        let written = std::fs::read(&file).unwrap();
469        std::fs::write(&file, &edited).unwrap();
470        assert_eq!(heard(&file), a);
471        std::fs::write(&file, &written).unwrap();
472        assert_eq!(heard(&file), a, "back to the store's bytes, after an edit");
473
474        store.resolve(&id).unwrap();
475        assert!(heard(&file).is_empty(), "the store's own delete");
476        let other = root.join(".devpage/comments/docs/a.md/20261025T000000Z-0000.yml");
477        std::fs::write(&other, "x").unwrap();
478        std::fs::remove_file(&other).unwrap();
479        assert_eq!(heard(&other), a, "a file the store never touched");
480
481        // Only a thread file is one: not the page, nor another file there.
482        for path in [
483            root.join("docs/a.md"),
484            root.join(".devpage/comments/docs/a.md/notes.txt"),
485        ] {
486            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
487            std::fs::write(&path, "x").unwrap();
488            assert!(heard(&path).is_empty(), "{}", path.display());
489        }
490    }
491}