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,
37 #[serde(default)]
39 pub prefix: String,
40 #[serde(default)]
42 pub suffix: String,
43}
44
45#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
47pub struct Message {
48 pub author: String,
50 pub at: String,
52 pub text: String,
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
58pub struct Thread {
59 pub anchor: Anchor,
61 pub thread: Vec<Message>,
63}
64
65#[derive(Debug, Clone, Serialize, PartialEq)]
67pub struct Listed {
68 pub id: String,
70 #[serde(flatten)]
72 pub thread: Thread,
73 #[serde(skip_serializing_if = "std::ops::Not::not")]
77 pub detached: bool,
78}
79
80#[derive(Debug, Default, PartialEq)]
83pub struct Carry {
84 moved: Vec<Moved>,
86 pages: std::collections::BTreeSet<String>,
89}
90
91impl Carry {
92 pub fn moved(&self) -> &[Moved] {
94 &self.moved
95 }
96}
97
98#[derive(Debug, PartialEq)]
101pub struct Moved {
102 pub id: String,
104 pub anchor: Option<Anchor>,
106}
107
108pub trait Store: Send + Sync {
114 fn list(&self, page: &str) -> Result<Vec<Listed>>;
116 fn create(&self, page: &str, anchor: Anchor, first: Message) -> Result<String>;
118 fn reply(&self, id: &str, message: Message) -> Result<Option<String>>;
121 fn resolve(&self, id: &str) -> Result<Option<String>>;
124 fn attached(&self) -> Result<Vec<(String, Listed)>>;
127 fn heard(&self, paths: &[PathBuf]) -> Vec<String>;
132}
133
134#[derive(Debug)]
136pub enum Refused {
137 Unidentified(String),
140 NotAPage(String),
142 NoThread(String),
144 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#[derive(Debug, Clone, PartialEq)]
169pub enum Identity {
170 Local(String),
172 Header(String),
174}
175
176impl Identity {
177 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#[derive(Clone)]
200pub struct Comments {
201 store: Arc<dyn Store>,
203 changes: Arc<dyn Publish>,
205 folder: ServedFolder,
207}
208
209impl Comments {
210 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 pub fn list(&self, page: &str) -> Result<Vec<Listed>, Refused> {
222 Ok(self.store.list(&page_key(page)?)?)
223 }
224
225 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 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 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 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 pub fn carried(&self, carry: Carry) {
293 for page in carry.pages {
294 self.announce(page);
295 }
296 }
297
298 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 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 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 fn announce(&self, page: String) {
339 self.changes.publish(Change::Comments(page));
340 }
341}
342
343fn 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
356fn message(author: &str, text: &str) -> Message {
358 Message {
359 author: author.into(),
360 at: now().0,
361 text: text.into(),
362 }
363}
364
365pub fn new_id() -> String {
369 let (stamp, nanos) = now();
370 format!("{}-{:04x}", stamp.replace(['-', ':'], ""), nanos & 0xffff)
371}
372
373pub fn is_id(id: &str) -> bool {
375 !id.is_empty() && id.chars().all(|c| c.is_ascii_alphanumeric() || c == '-')
376}
377
378fn 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 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 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 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 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}