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