1pub 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#[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#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
51pub struct Thread {
52 pub anchor: Anchor,
53 pub thread: Vec<Message>,
54}
55
56#[derive(Debug, Clone, Serialize, PartialEq)]
58pub struct Listed {
59 pub id: String,
60 #[serde(flatten)]
61 pub thread: Thread,
62 #[serde(skip_serializing_if = "std::ops::Not::not")]
66 pub detached: bool,
67}
68
69#[derive(Debug, Default, PartialEq)]
72pub struct Carry {
73 moved: Vec<Moved>,
74 pages: std::collections::BTreeSet<String>,
75}
76
77impl Carry {
78 pub fn moved(&self) -> &[Moved] {
80 &self.moved
81 }
82}
83
84#[derive(Debug, PartialEq)]
87pub struct Moved {
88 pub id: String,
89 pub anchor: Option<Anchor>,
90}
91
92pub trait Store: Send + Sync {
98 fn list(&self, page: &str) -> Result<Vec<Listed>>;
100 fn create(&self, page: &str, anchor: Anchor, first: Message) -> Result<String>;
102 fn reply(&self, id: &str, message: Message) -> Result<Option<String>>;
105 fn resolve(&self, id: &str) -> Result<Option<String>>;
108 fn attached(&self) -> Result<Vec<(String, Listed)>>;
111 fn heard(&self, paths: &[PathBuf]) -> Vec<String>;
116}
117
118#[derive(Debug)]
120pub enum Refused {
121 Unidentified(String),
124 NotAPage(String),
126 NoThread(String),
128 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#[derive(Debug, Clone, PartialEq)]
153pub enum Identity {
154 Local(String),
155 Header(String),
156}
157
158impl Identity {
159 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#[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 pub fn list(&self, page: &str) -> Result<Vec<Listed>, Refused> {
199 Ok(self.store.list(&page_key(page)?)?)
200 }
201
202 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 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 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 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 pub fn carried(&self, carry: Carry) {
270 for page in carry.pages {
271 self.announce(page);
272 }
273 }
274
275 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 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 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
319fn 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
332fn message(author: &str, text: &str) -> Message {
334 Message {
335 author: author.into(),
336 at: now().0,
337 text: text.into(),
338 }
339}
340
341pub fn new_id() -> String {
345 let (stamp, nanos) = now();
346 format!("{}-{:04x}", stamp.replace(['-', ':'], ""), nanos & 0xffff)
347}
348
349pub fn is_id(id: &str) -> bool {
351 !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
352}
353
354fn 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 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 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 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 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}