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