Skip to main content

devpage_core/comments/
mod.rs

1//! Comments: threads readers leave on a page, kept by a comment store.
2//! [`Comments`] is the only way a thread is written — from a page, from the
3//! API, or by a publish carrying threads onto a new version — and it holds
4//! every rule of a write: the page key, a new thread's page being a file in
5//! the served or version folder, replies and resolves going by thread id,
6//! where a carry moves each thread, and the one announcement each write
7//! makes on the change bus. A carry is the one write it hands over: the
8//! publish commits it together with the version, so both land or neither
9//! does. [`Identity`] says who writes. The [`Store`] port is only where
10//! threads are kept, by thread id: the YAML files under `.devpage/comments/`
11//! ([`yaml`]), server mode's SQLite store, and memory for tests
12//! ([`memory`]). [`anchor`] finds a carried thread's quote in the new
13//! version's text.
14
15pub mod anchor;
16pub mod yaml;
17
18#[cfg(any(test, feature = "testing"))]
19pub mod memory;
20
21use std::path::{Path, PathBuf};
22use std::sync::Arc;
23use std::time::{SystemTime, UNIX_EPOCH};
24
25use anyhow::Result;
26use serde::{Deserialize, Serialize};
27
28use crate::changes::{Change, Publish};
29use crate::folder::{Folder, ServedFolder};
30use crate::widgets::{Modules, Widgets};
31
32/// What a thread is attached to: rendered text, with a little context.
33#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
34pub struct Anchor {
35    pub quote: String,
36    #[serde(default)]
37    pub prefix: String,
38    #[serde(default)]
39    pub suffix: String,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
43pub struct Message {
44    pub author: String,
45    pub at: String,
46    pub text: String,
47}
48
49/// A thread as stored: its anchor and its messages, oldest first.
50#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
51pub struct Thread {
52    pub anchor: Anchor,
53    pub thread: Vec<Message>,
54}
55
56/// A thread with its id, as the page receives it.
57#[derive(Debug, Clone, Serialize, PartialEq)]
58pub struct Listed {
59    pub id: String,
60    #[serde(flatten)]
61    pub thread: Thread,
62    /// Its text is gone from the version shown: the page lists it among the
63    /// detached comments wherever its quote may still appear. Only a store
64    /// that keeps threads across versions sets it.
65    #[serde(skip_serializing_if = "std::ops::Not::not")]
66    pub detached: bool,
67}
68
69/// Where a publish carries a document's threads: each one that moves, and
70/// the pages they are on. Made by [`Comments::carry`].
71#[derive(Debug, Default, PartialEq)]
72pub struct Carry {
73    moved: Vec<Moved>,
74    pages: std::collections::BTreeSet<String>,
75}
76
77impl Carry {
78    /// The threads that move, each once.
79    pub fn moved(&self) -> &[Moved] {
80        &self.moved
81    }
82}
83
84/// A thread carried onto a new version: to `anchor`, or detached — `None` —
85/// when its text is gone.
86#[derive(Debug, PartialEq)]
87pub struct Moved {
88    pub id: String,
89    pub anchor: Option<Anchor>,
90}
91
92/// The comment store port: where one served folder's — or one published
93/// document's — threads are kept, by thread id. A `page` here is always a
94/// page key, `/a.md`, made by [`Comments`]; an `id` is always one that
95/// [`is_id`] accepts. Writes are silent — announcing them is [`Comments`]'s
96/// job.
97pub trait Store: Send + Sync {
98    /// A page's threads, oldest first.
99    fn list(&self, page: &str) -> Result<Vec<Listed>>;
100    /// Starts a thread on `page` with its first message; answers its id.
101    fn create(&self, page: &str, anchor: Anchor, first: Message) -> Result<String>;
102    /// Appends `message` to thread `id`: the page it is on, or `None` when
103    /// there is no such thread.
104    fn reply(&self, id: &str, message: Message) -> Result<Option<String>>;
105    /// Resolves thread `id` — it is gone: the page it was on, or `None` when
106    /// there was no such thread.
107    fn resolve(&self, id: &str) -> Result<Option<String>>;
108    /// Every thread still attached, each with its page: what a publish
109    /// carries onto the new version.
110    fn attached(&self) -> Result<Vec<(String, Listed)>>;
111    /// The pages whose threads changed among `paths` by a hand other than
112    /// this store's — a thread file edited in an editor. Asking marks them
113    /// heard: whoever asks announces them. A store with no files hears
114    /// nothing.
115    fn heard(&self, paths: &[PathBuf]) -> Vec<String>;
116}
117
118/// Why a comment request is refused.
119#[derive(Debug)]
120pub enum Refused {
121    /// The request names no author: the header [`Identity::Header`] names
122    /// is missing or blank.
123    Unidentified(String),
124    /// The page is not a file in the served or version folder.
125    NotAPage(String),
126    /// There is no such thread.
127    NoThread(String),
128    /// The store failed.
129    Failed(anyhow::Error),
130}
131
132impl std::fmt::Display for Refused {
133    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
134        match self {
135            Refused::Unidentified(header) => write!(f, "a write needs the {header} header"),
136            Refused::NotAPage(page) => write!(f, "{page} is not a page in the served folder"),
137            Refused::NoThread(id) => write!(f, "no thread {id}"),
138            Refused::Failed(error) => write!(f, "{error:#}"),
139        }
140    }
141}
142
143impl From<anyhow::Error> for Refused {
144    fn from(error: anyhow::Error) -> Self {
145        Refused::Failed(error)
146    }
147}
148
149/// Who writes: one local author — the git name locally, `anonymous` on a
150/// server with no header — or, deployed, whoever the auth proxy names in a
151/// header. devpage authenticates no one itself.
152#[derive(Debug, Clone, PartialEq)]
153pub enum Identity {
154    Local(String),
155    Header(String),
156}
157
158impl Identity {
159    /// The author of a write whose request carries `header`'s value by name:
160    /// the local author, or the header's value trimmed — refused when it is
161    /// missing or blank.
162    pub fn author<'a>(
163        &self,
164        header: impl FnOnce(&str) -> Option<&'a str>,
165    ) -> Result<String, Refused> {
166        match self {
167            Identity::Local(name) => Ok(name.clone()),
168            Identity::Header(name) => header(name)
169                .map(str::trim)
170                .filter(|value| !value.is_empty())
171                .map(str::to_string)
172                .ok_or_else(|| Refused::Unidentified(name.clone())),
173        }
174    }
175}
176
177/// The comments of one served or version folder: its store, the bus every
178/// successful write is announced on — `comments <page>`, once, as the write
179/// lands — so open pages fetch that page's threads again, and the folder a
180/// new thread's page must be a file in.
181#[derive(Clone)]
182pub struct Comments {
183    store: Arc<dyn Store>,
184    changes: Arc<dyn Publish>,
185    folder: ServedFolder,
186}
187
188impl Comments {
189    pub fn new(store: Arc<dyn Store>, changes: Arc<dyn Publish>, folder: ServedFolder) -> Self {
190        Self {
191            store,
192            changes,
193            folder,
194        }
195    }
196
197    /// A page's threads, oldest first.
198    pub fn list(&self, page: &str) -> Result<Vec<Listed>, Refused> {
199        Ok(self.store.list(&page_key(page)?)?)
200    }
201
202    /// Starts a thread on `page`, which must be a file in the folder.
203    pub fn create(
204        &self,
205        page: &str,
206        anchor: Anchor,
207        author: &str,
208        text: &str,
209    ) -> Result<String, Refused> {
210        let page = page_key(page)?;
211        if self.folder.file_at(&page).is_none() {
212            return Err(Refused::NotAPage(page));
213        }
214        let id = self.store.create(&page, anchor, message(author, text))?;
215        self.announce(page);
216        Ok(id)
217    }
218
219    /// Appends a reply to thread `id`, wherever it is — detached included.
220    pub fn reply(&self, id: &str, author: &str, text: &str) -> Result<(), Refused> {
221        let page = self.found(id, |id| self.store.reply(id, message(author, text)))?;
222        self.announce(page);
223        Ok(())
224    }
225
226    /// Resolves thread `id`: it is gone.
227    pub fn resolve(&self, id: &str) -> Result<(), Refused> {
228        let page = self.found(id, |id| self.store.resolve(id))?;
229        self.announce(page);
230        Ok(())
231    }
232
233    /// Where every attached thread goes on `version`, this folder opened on
234    /// the version's entry document: each finds its quote in its
235    /// page's text as the page shows it — front matter left out, widget
236    /// tags expanded — by its context where it can, and is detached when
237    /// the quote, or the page, is gone. Nothing is written: the publish
238    /// commits the [`Carry`] together with its version, so both land or
239    /// neither does, and then [`Comments::carried`] announces it. It renders
240    /// pages, which draws their diagrams: it blocks.
241    pub fn carry(&self, version: &Folder) -> Result<Carry> {
242        let modules = Modules::default();
243        let mut pages: std::collections::BTreeMap<String, Vec<Listed>> = Default::default();
244        for (page, thread) in self.store.attached()? {
245            pages.entry(page).or_default().push(thread);
246        }
247        let mut carry = Carry::default();
248        for (page, threads) in pages {
249            let text = self
250                .content(version, &modules, &page)
251                .map(|html| anchor::text(&html));
252            for listed in threads {
253                let found = text
254                    .as_deref()
255                    .and_then(|text| anchor::reanchor(&listed.thread.anchor, text));
256                if found.as_ref() != Some(&listed.thread.anchor) {
257                    carry.moved.push(Moved {
258                        id: listed.id,
259                        anchor: found,
260                    });
261                    carry.pages.insert(page.clone());
262                }
263            }
264        }
265        Ok(carry)
266    }
267
268    /// A carry committed: each page whose threads moved is announced once.
269    pub fn carried(&self, carry: Carry) {
270        for page in carry.pages {
271            self.announce(page);
272        }
273    }
274
275    /// The changes open pages should hear for `paths`, changed by another
276    /// hand: a page's comments for each page whose threads changed. Nothing
277    /// is published — the watcher publishes what it heard together.
278    pub fn heard(&self, paths: &[PathBuf]) -> Vec<Change> {
279        self.store
280            .heard(paths)
281            .into_iter()
282            .map(Change::Comments)
283            .collect()
284    }
285
286    /// The page thread `id` was on after `write`, or why there is none.
287    fn found(
288        &self,
289        id: &str,
290        write: impl FnOnce(&str) -> Result<Option<String>>,
291    ) -> Result<String, Refused> {
292        if !is_id(id) {
293            return Err(Refused::NoThread(id.into()));
294        }
295        write(id)?.ok_or_else(|| Refused::NoThread(id.into()))
296    }
297
298    /// The HTML of `page`'s content as its page shows it: rendered with the
299    /// widgets of the document that shows it — its owner, or else the
300    /// version's entry document. `None` when the page is gone.
301    fn content(&self, version: &Folder, modules: &Modules, page: &str) -> Option<String> {
302        let file = self.folder.file_at(page)?;
303        let source = std::fs::read_to_string(&file).ok()?;
304        let site = version.owner(&file).and_then(|owner| owner.document.ok());
305        let entry = version.entry();
306        let widgets = Widgets::of(site.as_ref().unwrap_or(&entry), modules);
307        Some(
308            crate::page::content(&widgets, &file, source)
309                .html()
310                .to_string(),
311        )
312    }
313
314    fn announce(&self, page: String) {
315        self.changes.publish(Change::Comments(page));
316    }
317}
318
319/// A page's key: its address with exactly one leading `/` — or a refusal
320/// when it is empty or climbs out of the folder.
321fn page_key(page: &str) -> Result<String, Refused> {
322    let name = page.trim_start_matches('/');
323    let plain = Path::new(name)
324        .components()
325        .all(|part| matches!(part, std::path::Component::Normal(_)));
326    if name.is_empty() || !plain {
327        return Err(Refused::NotAPage(page.into()));
328    }
329    Ok(format!("/{name}"))
330}
331
332/// A message by `author`, written now.
333fn message(author: &str, text: &str) -> Message {
334    Message {
335        author: author.into(),
336        at: now().0,
337        text: text.into(),
338    }
339}
340
341/// A new thread's id: the UTC time it was started, to the second, and four
342/// hex digits from the clock's nanoseconds — so a page's threads list oldest
343/// first.
344pub fn new_id() -> String {
345    let (stamp, nanos) = now();
346    format!("{}-{:04x}", stamp.replace(['-', ':'], ""), nanos & 0xffff)
347}
348
349/// Whether `id` can be a thread's: letters, digits and dashes, never empty.
350pub fn is_id(id: &str) -> bool {
351    !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
352}
353
354/// Now, as RFC 3339 UTC to the second, and the sub-second nanoseconds.
355fn now() -> (String, u32) {
356    let since = SystemTime::now()
357        .duration_since(UNIX_EPOCH)
358        .unwrap_or_default();
359    let secs = since.as_secs() as i64;
360    let (days, rest) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
361    // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
362    let z = days + 719_468;
363    let era = z.div_euclid(146_097);
364    let doe = z - era * 146_097;
365    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
366    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
367    let mp = (5 * doy + 2) / 153;
368    let day = doy - (153 * mp + 2) / 5 + 1;
369    let month = if mp < 10 { mp + 3 } else { mp - 9 };
370    let year = yoe + era * 400 + i64::from(month <= 2);
371    (
372        format!(
373            "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
374            rest / 3600,
375            rest % 3600 / 60,
376            rest % 60
377        ),
378        since.subsec_nanos(),
379    )
380}
381
382#[cfg(test)]
383mod tests {
384    use super::*;
385
386    fn anchor() -> Anchor {
387        Anchor {
388            quote: "retries".into(),
389            prefix: "The client ".into(),
390            suffix: ".".into(),
391        }
392    }
393
394    /// A served folder holding `files`, its comments in memory announcing
395    /// on a recorder.
396    fn folder(
397        name: &str,
398        files: &[(&str, &str)],
399    ) -> (
400        Comments,
401        Arc<crate::changes::Recorder>,
402        Arc<memory::Memory>,
403        ServedFolder,
404    ) {
405        let root =
406            std::env::temp_dir().join(format!("devpage-comments-{name}-{}", std::process::id()));
407        let _ = std::fs::remove_dir_all(&root);
408        for (file, text) in files {
409            let path = root.join(file);
410            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
411            std::fs::write(path, text).unwrap();
412        }
413        std::fs::create_dir_all(&root).unwrap();
414        let served = ServedFolder::new(&root).unwrap();
415        let changes = Arc::new(crate::changes::Recorder::default());
416        let store = Arc::new(memory::Memory::default());
417        let comments = Comments::new(store.clone(), changes.clone(), served.clone());
418        (comments, changes, store, served)
419    }
420
421    #[test]
422    fn every_write_announces_its_page_once_and_a_failed_one_nothing() {
423        let (comments, changes, _, _) = folder("announce", &[("a.md", "# A\n")]);
424        let id = comments
425            .create("a.md", anchor(), "Ana", "Every write?")
426            .unwrap();
427        comments.reply(&id, "Bo", "Only the outbox.").unwrap();
428        comments.resolve(&id).unwrap();
429        assert!(matches!(
430            comments.reply(&id, "Bo", "gone"),
431            Err(Refused::NoThread(_))
432        ));
433        assert!(matches!(
434            comments.create("/../x.md", anchor(), "Ana", "no"),
435            Err(Refused::NotAPage(_))
436        ));
437        let comments_of_a = Change::Comments("/a.md".into());
438        assert_eq!(
439            changes.drain(),
440            [comments_of_a.clone(), comments_of_a.clone(), comments_of_a],
441            "one per write that landed, keyed `/a.md` however it was named, none for the two refused"
442        );
443    }
444
445    #[test]
446    fn a_thread_starts_only_on_a_file_in_the_folder() {
447        let (comments, changes, _, _) = folder(
448            "create",
449            &[
450                ("a.md", "# A\n"),
451                ("notes/lone.md", "# Lone\n"),
452                ("docs/x", ""),
453            ],
454        );
455        // A lone page no document links to is still a file in the folder.
456        assert!(
457            comments
458                .create("/notes/lone.md", anchor(), "Ana", "ok")
459                .is_ok()
460        );
461        for page in ["/missing.md", "/notes", "/../escape.md", "", "/"] {
462            assert!(
463                matches!(
464                    comments.create(page, anchor(), "Ana", "no"),
465                    Err(Refused::NotAPage(_))
466                ),
467                "{page}"
468            );
469        }
470        assert_eq!(changes.drain(), [Change::Comments("/notes/lone.md".into())]);
471    }
472
473    #[test]
474    fn a_reply_and_a_resolve_go_by_id_whatever_page_it_is_on() {
475        let (comments, _, store, _) = folder("by-id", &[("a.md", "# A\n")]);
476        let id = comments.create("/a.md", anchor(), "Ana", "x").unwrap();
477        // Detached: its text is gone from the version shown.
478        store.detach(&id);
479        comments.reply(&id, "Bo", "still here").unwrap();
480        let listed = comments.list("/a.md").unwrap();
481        assert!(listed[0].detached);
482        assert_eq!(listed[0].thread.thread[1].text, "still here");
483        comments.resolve(&id).unwrap();
484        assert!(comments.list("/a.md").unwrap().is_empty());
485        assert!(matches!(
486            comments.resolve("../x"),
487            Err(Refused::NoThread(_))
488        ));
489    }
490
491    #[test]
492    fn carry_reads_the_page_as_it_is_shown() {
493        let page = "---\ntitle: Launch\n---\n\n# Launch\n\n<Callout>\nThe client **retries** every write.\n</Callout>\n";
494        let (comments, changes, store, served) = folder("carry", &[("a.md", page)]);
495        let kept = comments
496            .create(
497                "/a.md",
498                Anchor {
499                    quote: "retries every write".into(),
500                    prefix: "The client ".into(),
501                    suffix: ".".into(),
502                },
503                "Ana",
504                "kept",
505            )
506            .unwrap();
507        let gone = comments
508            .create(
509                "/a.md",
510                Anchor {
511                    quote: "title: Launch".into(),
512                    prefix: String::new(),
513                    suffix: String::new(),
514                },
515                "Ana",
516                "front matter is never shown",
517            )
518            .unwrap();
519        changes.drain();
520        let entry = crate::document::Document::load(&served.path().join("a.md"), &served).unwrap();
521        let carry = comments.carry(&Folder::new(Arc::new(entry))).unwrap();
522        assert_eq!(
523            carry.moved(),
524            [Moved {
525                id: gone,
526                anchor: None
527            }],
528            "the widget's text is found as the page shows it; front matter never is"
529        );
530        assert!(
531            store.list("/a.md").unwrap().iter().all(|t| !t.detached),
532            "nothing written: the publish commits the carry"
533        );
534        let _ = kept;
535        assert!(
536            changes.drain().is_empty(),
537            "nothing written, nothing announced"
538        );
539        comments.carried(carry);
540        assert_eq!(changes.drain(), [Change::Comments("/a.md".into())]);
541    }
542
543    #[test]
544    fn a_header_author_is_trimmed_and_a_blank_one_refused() {
545        let deployed = Identity::Header("X-Forwarded-Email".into());
546        for blank in [None, Some(""), Some("   ")] {
547            assert!(
548                matches!(deployed.author(|_| blank), Err(Refused::Unidentified(_))),
549                "{blank:?}"
550            );
551        }
552        assert_eq!(
553            deployed
554                .author(|name| (name == "X-Forwarded-Email").then_some(" ana@example.com "))
555                .unwrap(),
556            "ana@example.com"
557        );
558        let local = Identity::Local("Andrei".into());
559        assert_eq!(local.author(|_| None).unwrap(), "Andrei");
560    }
561
562    #[test]
563    fn timestamps_are_rfc3339_utc() {
564        let (stamp, _) = now();
565        assert_eq!(stamp.len(), 20);
566        assert!(
567            stamp.ends_with('Z') && stamp.as_bytes()[10] == b'T',
568            "{stamp}"
569        );
570    }
571
572    #[test]
573    fn a_page_that_climbs_out_and_a_made_up_id_are_refused() {
574        assert_eq!(page_key("docs/a.md").unwrap(), "/docs/a.md");
575        assert!(page_key("/../x.md").is_err());
576        assert!(is_id("20261025T181502Z-7f3a"));
577        assert!(!is_id("../x") && !is_id(""));
578    }
579}