Skip to main content

devpage_core/comments/
mod.rs

1//! Comments: threads readers leave on a page, kept by a comment store. The
2//! [`Store`] port is what a store must do — list, create, reply, resolve —
3//! and [`Comments`] is what the server writes through: every write it makes
4//! announces itself on the change bus, so open pages hear it whatever keeps
5//! the threads. The YAML files under `.devpage/comments/` are one store
6//! ([`yaml`]); tests keep threads in memory ([`memory`]). Where a store
7//! keeps threads across versions of a document, [`anchor`] carries each one
8//! onto the next version's text.
9
10pub mod anchor;
11pub mod yaml;
12
13#[cfg(any(test, feature = "testing"))]
14pub mod memory;
15
16use std::path::Path;
17use std::sync::Arc;
18use std::time::{SystemTime, UNIX_EPOCH};
19
20use anyhow::Result;
21use serde::{Deserialize, Serialize};
22
23use crate::changes::{Change, Publish, Scope};
24
25/// What a thread is attached to: rendered text, with a little context.
26#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
27pub struct Anchor {
28    pub quote: String,
29    #[serde(default)]
30    pub prefix: String,
31    #[serde(default)]
32    pub suffix: String,
33}
34
35#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
36pub struct Message {
37    pub author: String,
38    pub at: String,
39    pub text: String,
40}
41
42/// A thread as stored: its anchor and its messages, oldest first.
43#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
44pub struct Thread {
45    pub anchor: Anchor,
46    pub thread: Vec<Message>,
47}
48
49/// A thread with its id, as the page receives it.
50#[derive(Debug, Clone, Serialize, PartialEq)]
51pub struct Listed {
52    pub id: String,
53    #[serde(flatten)]
54    pub thread: Thread,
55    /// Its text is gone from the version shown: the page lists it among the
56    /// detached comments wherever its quote may still appear. Only a store
57    /// that keeps threads across versions sets it.
58    #[serde(skip_serializing_if = "std::ops::Not::not")]
59    pub detached: bool,
60}
61
62/// The comment store port: where one served folder's threads are kept. A
63/// `page` is the address of the Markdown file a thread is about (`/a.md`);
64/// one that climbs out of the served folder, and an id that isn't a thread's,
65/// are errors. Writes are silent — announcing them is [`Comments`]'s job.
66pub trait Store: Send + Sync {
67    /// A page's threads, oldest first.
68    fn list(&self, page: &str) -> Result<Vec<Listed>>;
69    /// Starts a thread on `page`; answers its id.
70    fn create(&self, page: &str, anchor: Anchor, author: &str, text: &str) -> Result<String>;
71    /// Appends a reply to thread `id`.
72    fn reply(&self, page: &str, id: &str, author: &str, text: &str) -> Result<()>;
73    /// Resolves thread `id`: it is gone.
74    fn resolve(&self, page: &str, id: &str) -> Result<()>;
75}
76
77/// The comments of the documents under one scope: a store, and the bus every
78/// successful write is announced on — `comments <page>`, once, as the write
79/// lands — so open pages fetch that page's threads again.
80#[derive(Clone)]
81pub struct Comments {
82    store: Arc<dyn Store>,
83    changes: Arc<dyn Publish>,
84    scope: Scope,
85}
86
87impl Comments {
88    pub fn new(store: Arc<dyn Store>, changes: Arc<dyn Publish>, scope: Scope) -> Self {
89        Self {
90            store,
91            changes,
92            scope,
93        }
94    }
95
96    pub fn list(&self, page: &str) -> Result<Vec<Listed>> {
97        self.store.list(page)
98    }
99
100    pub fn create(&self, page: &str, anchor: Anchor, author: &str, text: &str) -> Result<String> {
101        let id = self.store.create(page, anchor, author, text)?;
102        self.announce(page);
103        Ok(id)
104    }
105
106    pub fn reply(&self, page: &str, id: &str, author: &str, text: &str) -> Result<()> {
107        self.store.reply(page, id, author, text)?;
108        self.announce(page);
109        Ok(())
110    }
111
112    pub fn resolve(&self, page: &str, id: &str) -> Result<()> {
113        self.store.resolve(page, id)?;
114        self.announce(page);
115        Ok(())
116    }
117
118    fn announce(&self, page: &str) {
119        let page = format!("/{}", page.trim_start_matches('/'));
120        self.changes.publish(&self.scope, Change::Comments(page));
121    }
122}
123
124/// A new thread's id: the UTC time it was started, to the second, and four
125/// hex digits from the clock's nanoseconds — so a page's threads list oldest
126/// first — with when it was started.
127pub fn new_id() -> (String, String) {
128    let (stamp, nanos) = now();
129    let id = format!("{}-{:04x}", stamp.replace(['-', ':'], ""), nanos & 0xffff);
130    (id, stamp)
131}
132
133/// Whether `id` can be a thread's: letters, digits and dashes, never empty.
134pub fn is_id(id: &str) -> bool {
135    !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
136}
137
138/// Whether `page` stays inside the served folder: only plain path parts.
139pub fn is_page(page: &str) -> bool {
140    Path::new(page.trim_start_matches('/'))
141        .components()
142        .all(|part| matches!(part, std::path::Component::Normal(_)))
143}
144
145/// The local author: `git config user.name` as git sees it from the served
146/// folder — its global setting counts, so no `.git` folder is needed — or the
147/// system's user name when git has none.
148pub fn local_author(served: &Path) -> String {
149    std::process::Command::new("git")
150        .arg("-C")
151        .arg(served)
152        .args(["config", "user.name"])
153        .output()
154        .ok()
155        .filter(|output| output.status.success())
156        .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string())
157        .filter(|name| !name.is_empty())
158        .or_else(|| std::env::var("USER").ok())
159        .or_else(|| std::env::var("USERNAME").ok())
160        .unwrap_or_else(|| "unknown".into())
161}
162
163/// Now, as RFC 3339 UTC to the second, and the sub-second nanoseconds.
164fn now() -> (String, u32) {
165    let since = SystemTime::now()
166        .duration_since(UNIX_EPOCH)
167        .unwrap_or_default();
168    let secs = since.as_secs() as i64;
169    let (days, rest) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
170    // Civil date from days since 1970-01-01 (Howard Hinnant's algorithm).
171    let z = days + 719_468;
172    let era = z.div_euclid(146_097);
173    let doe = z - era * 146_097;
174    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
175    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
176    let mp = (5 * doy + 2) / 153;
177    let day = doy - (153 * mp + 2) / 5 + 1;
178    let month = if mp < 10 { mp + 3 } else { mp - 9 };
179    let year = yoe + era * 400 + i64::from(month <= 2);
180    (
181        format!(
182            "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}Z",
183            rest / 3600,
184            rest % 3600 / 60,
185            rest % 60
186        ),
187        since.subsec_nanos(),
188    )
189}
190
191#[cfg(test)]
192mod tests {
193    use super::*;
194    use std::process::Command;
195
196    fn anchor() -> Anchor {
197        Anchor {
198            quote: "retries".into(),
199            prefix: "The client ".into(),
200            suffix: ".".into(),
201        }
202    }
203
204    #[test]
205    fn every_write_announces_its_page_once_and_a_failed_one_nothing() {
206        let changes = Arc::new(crate::changes::Recorder::default());
207        let comments = Comments::new(
208            Arc::new(memory::Memory::default()),
209            changes.clone(),
210            Scope::root(),
211        );
212        let id = comments
213            .create("/a.md", anchor(), "Ana", "Every write?")
214            .unwrap();
215        comments
216            .reply("/a.md", &id, "Bo", "Only the outbox.")
217            .unwrap();
218        comments.resolve("/a.md", &id).unwrap();
219        assert!(comments.reply("/a.md", &id, "Bo", "gone").is_err());
220        assert!(comments.create("/../x.md", anchor(), "Ana", "no").is_err());
221        let comments_of_a = Change::Comments("/a.md".into());
222        assert_eq!(
223            changes.drain(&Scope::root()),
224            [comments_of_a.clone(), comments_of_a.clone(), comments_of_a],
225            "one per write that landed, none for the two refused"
226        );
227    }
228
229    #[test]
230    fn the_local_author_needs_no_git_folder() {
231        let folder = std::env::temp_dir().join(format!("devpage-author-{}", std::process::id()));
232        std::fs::create_dir_all(&folder).unwrap();
233        assert!(!folder.join(".git").exists());
234        let expected = Command::new("git")
235            .args(["config", "--global", "user.name"])
236            .output()
237            .ok()
238            .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string())
239            .filter(|name| !name.is_empty())
240            .or_else(|| std::env::var("USER").ok());
241        assert_eq!(Some(local_author(&folder)), expected);
242    }
243
244    #[test]
245    fn timestamps_are_rfc3339_utc() {
246        let (stamp, _) = now();
247        assert_eq!(stamp.len(), 20);
248        assert!(
249            stamp.ends_with('Z') && stamp.as_bytes()[10] == b'T',
250            "{stamp}"
251        );
252    }
253
254    #[test]
255    fn a_page_that_climbs_out_and_a_made_up_id_are_refused() {
256        assert!(is_page("/docs/a.md"));
257        assert!(!is_page("/../x.md"));
258        assert!(is_id("20261025T181502Z-7f3a"));
259        assert!(!is_id("../x") && !is_id(""));
260    }
261}