Skip to main content

adk_site/content/
store.rs

1//! Content stores: where items and their media live (spec 3.5 §7.8.2 "Content model").
2
3use std::collections::BTreeMap;
4use std::path::{Component, Path, PathBuf};
5use std::sync::Arc;
6
7use async_trait::async_trait;
8use awp_types::{ContentId, ContentItem, LanguageTag};
9use bytes::Bytes;
10use tokio::sync::RwLock;
11
12use super::frontmatter::{ItemDefaults, parse_item, render_item};
13use super::{CONTENT_DIR, kind_directory, kind_from_directory};
14use crate::error::{Result, SiteError};
15
16/// Reads and writes a site's content items and the media beside them.
17///
18/// Drafts on branches and the repository's history are the caller's git concern; a store
19/// holds one working copy. Implementations run [`content_store_conformance`].
20#[async_trait]
21pub trait ContentStore: Send + Sync {
22    /// Every item, sorted by id.
23    ///
24    /// # Errors
25    ///
26    /// Returns an error when the store cannot be read or an item is malformed.
27    async fn list(&self) -> Result<Vec<ContentItem>>;
28
29    /// The item with `id`.
30    ///
31    /// # Errors
32    ///
33    /// Returns an error when the store cannot be read.
34    async fn get(&self, id: &ContentId) -> Result<Option<ContentItem>>;
35
36    /// Creates or replaces an item.
37    ///
38    /// # Errors
39    ///
40    /// Returns an error when the item cannot be written.
41    async fn put(&self, item: &ContentItem) -> Result<()>;
42
43    /// Removes an item; returns whether it existed. Its media stays.
44    ///
45    /// # Errors
46    ///
47    /// Returns an error when the store cannot be written.
48    async fn remove(&self, id: &ContentId) -> Result<bool>;
49
50    /// Reads a media file by its repository path.
51    ///
52    /// # Errors
53    ///
54    /// Returns an error for a path outside the repository or a failing store.
55    async fn read_media(&self, path: &str) -> Result<Option<Bytes>>;
56
57    /// Writes a media file at its repository path.
58    ///
59    /// # Errors
60    ///
61    /// Returns an error for a path outside the repository or a failing store.
62    async fn write_media(&self, path: &str, bytes: Bytes) -> Result<()>;
63}
64
65/// Checks that a repository path stays inside the repository.
66pub(crate) fn safe_relative(path: &str) -> Result<PathBuf> {
67    let candidate = Path::new(path);
68    let ok = !path.is_empty()
69        && candidate.components().all(|c| matches!(c, Component::Normal(_)))
70        && !path.contains('\\');
71    if ok {
72        Ok(candidate.to_path_buf())
73    } else {
74        Err(SiteError::InvalidContent {
75            path: path.to_string(),
76            message: "media paths are relative to the repository and may not climb out of it"
77                .into(),
78        })
79    }
80}
81
82/// A store in memory, for tests and generated sites.
83///
84/// # Example
85///
86/// ```rust
87/// use adk_site::content::{ContentStore, InMemoryContentStore};
88///
89/// # async fn demo() -> adk_site::Result<()> {
90/// let store = InMemoryContentStore::default();
91/// assert!(store.list().await?.is_empty());
92/// # Ok(())
93/// # }
94/// ```
95#[derive(Debug, Default, Clone)]
96pub struct InMemoryContentStore {
97    items: Arc<RwLock<BTreeMap<ContentId, ContentItem>>>,
98    media: Arc<RwLock<BTreeMap<String, Bytes>>>,
99}
100
101#[async_trait]
102impl ContentStore for InMemoryContentStore {
103    async fn list(&self) -> Result<Vec<ContentItem>> {
104        Ok(self.items.read().await.values().cloned().collect())
105    }
106
107    async fn get(&self, id: &ContentId) -> Result<Option<ContentItem>> {
108        Ok(self.items.read().await.get(id).cloned())
109    }
110
111    async fn put(&self, item: &ContentItem) -> Result<()> {
112        self.items.write().await.insert(item.id.clone(), item.clone());
113        Ok(())
114    }
115
116    async fn remove(&self, id: &ContentId) -> Result<bool> {
117        Ok(self.items.write().await.remove(id).is_some())
118    }
119
120    async fn read_media(&self, path: &str) -> Result<Option<Bytes>> {
121        safe_relative(path)?;
122        Ok(self.media.read().await.get(path).cloned())
123    }
124
125    async fn write_media(&self, path: &str, bytes: Bytes) -> Result<()> {
126        safe_relative(path)?;
127        self.media.write().await.insert(path.to_string(), bytes);
128        Ok(())
129    }
130}
131
132/// The content repository on disk: `content/<kind>/<slug>/<language>.md` with media beside
133/// each item (spec 3.5 §7.8.2).
134///
135/// # Example
136///
137/// ```rust,no_run
138/// use adk_site::content::{ContentStore, FsContentStore};
139///
140/// # async fn demo() -> adk_site::Result<()> {
141/// let store = FsContentStore::new("./my-site");
142/// for item in store.list().await? {
143///     println!("{}", item.id);
144/// }
145/// # Ok(())
146/// # }
147/// ```
148#[derive(Debug, Clone)]
149pub struct FsContentStore {
150    root: PathBuf,
151    lock: Arc<RwLock<()>>,
152}
153
154impl FsContentStore {
155    /// A store over the repository at `root`.
156    pub fn new(root: impl Into<PathBuf>) -> Self {
157        Self { root: root.into(), lock: Arc::new(RwLock::new(())) }
158    }
159
160    /// The repository root.
161    pub fn root(&self) -> &Path {
162        &self.root
163    }
164
165    /// The file an item is stored in, relative to the repository root.
166    pub fn item_path(item: &ContentItem) -> String {
167        format!("{CONTENT_DIR}/{}/{}/{}.md", kind_directory(item.kind), item.slug, item.language)
168    }
169
170    fn scan(root: &Path) -> Result<Vec<(String, ContentItem)>> {
171        let content = root.join(CONTENT_DIR);
172        let mut found = Vec::new();
173        if !content.exists() {
174            return Ok(found);
175        }
176        let mut stack = vec![content.clone()];
177        while let Some(dir) = stack.pop() {
178            let entries = std::fs::read_dir(&dir).map_err(|e| SiteError::io(&dir, e))?;
179            for entry in entries {
180                let entry = entry.map_err(|e| SiteError::io(&dir, e))?;
181                let path = entry.path();
182                let file_type = entry.file_type().map_err(|e| SiteError::io(&path, e))?;
183                if file_type.is_dir() {
184                    stack.push(path);
185                    continue;
186                }
187                if path.extension().and_then(|e| e.to_str()) != Some("md") || !file_type.is_file() {
188                    continue;
189                }
190                let relative = path
191                    .strip_prefix(&content)
192                    .map_err(|_| SiteError::InvalidContent {
193                        path: path.display().to_string(),
194                        message: "outside content/".into(),
195                    })?
196                    .to_string_lossy()
197                    .replace('\\', "/");
198                let origin = format!("{CONTENT_DIR}/{relative}");
199                let text = std::fs::read_to_string(&path).map_err(|e| SiteError::io(&path, e))?;
200                let item = parse_content_file(&origin, &text)?;
201                found.push((origin, item));
202            }
203        }
204        found.sort_by(|a, b| a.1.id.cmp(&b.1.id));
205        Ok(found)
206    }
207
208    async fn blocking<T: Send + 'static>(
209        &self,
210        job: impl FnOnce(&Path) -> Result<T> + Send + 'static,
211    ) -> Result<T> {
212        let root = self.root.clone();
213        tokio::task::spawn_blocking(move || job(&root))
214            .await
215            .map_err(|e| SiteError::Pipeline(format!("content store task failed: {e}")))?
216    }
217}
218
219/// Reads the content file at `path`, relative to the repository root, as [`FsContentStore`]
220/// reads its own: `content/<kind>/<slug>/<language>.md`, front matter and a Markdown body
221/// (spec 3.5 §7.8.2 "Content model", "Files and git").
222///
223/// # Example
224///
225/// ```rust
226/// use adk_site::content::parse_content_file;
227/// use awp_types::ContentKind;
228///
229/// let item = parse_content_file("content/pages/hours/en.md", "---\ntitle: Hours\n---\nOpen daily.\n")?;
230/// assert_eq!((item.id.0.as_str(), item.kind), ("pages/hours/en", ContentKind::Page));
231/// assert!(parse_content_file("media/logo.png", "").is_err());
232/// # Ok::<(), adk_site::SiteError>(())
233/// ```
234///
235/// # Errors
236///
237/// [`SiteError::InvalidContent`] for a path outside that layout, an unknown kind directory, a
238/// file name that is not a language tag, or front matter that does not parse.
239pub fn parse_content_file(path: &str, text: &str) -> Result<ContentItem> {
240    let invalid = |message: &str| SiteError::InvalidContent {
241        path: path.to_string(),
242        message: message.into(),
243    };
244    let relative = path
245        .strip_prefix(CONTENT_DIR)
246        .and_then(|rest| rest.strip_prefix('/'))
247        .filter(|rest| rest.ends_with(".md"))
248        .ok_or_else(|| invalid("items live at content/<kind>/<slug>/<language>.md"))?;
249    let mut parts: Vec<&str> = relative.split('/').collect();
250    let file = parts.pop().unwrap_or_default();
251    if parts.len() < 2 || parts.iter().any(|part| part.is_empty() || *part == "." || *part == "..")
252    {
253        return Err(invalid("items live at content/<kind>/<slug>/<language>.md"));
254    }
255    let kind = kind_from_directory(parts[0]).ok_or_else(|| invalid("unknown kind directory"))?;
256    let slug = parts[1..].join("/");
257    let language: LanguageTag = file
258        .trim_end_matches(".md")
259        .parse()
260        .map_err(|_| invalid("the file name must be a language tag, such as en.md"))?;
261    let id = ContentId(format!("{}/{slug}/{language}", parts[0]));
262    parse_item(path, text, ItemDefaults { id, kind, slug, language })
263}
264
265pub(crate) fn write_atomic(path: &Path, bytes: &[u8]) -> Result<()> {
266    if let Some(parent) = path.parent() {
267        std::fs::create_dir_all(parent).map_err(|e| SiteError::io(parent, e))?;
268    }
269    let tmp = path.with_extension(format!(
270        "{}.tmp-{}",
271        path.extension().and_then(|e| e.to_str()).unwrap_or(""),
272        std::process::id()
273    ));
274    std::fs::write(&tmp, bytes).map_err(|e| SiteError::io(&tmp, e))?;
275    std::fs::rename(&tmp, path).map_err(|e| SiteError::io(path, e))
276}
277
278#[async_trait]
279impl ContentStore for FsContentStore {
280    async fn list(&self) -> Result<Vec<ContentItem>> {
281        let _guard = self.lock.read().await;
282        Ok(self.blocking(Self::scan).await?.into_iter().map(|(_, item)| item).collect())
283    }
284
285    async fn get(&self, id: &ContentId) -> Result<Option<ContentItem>> {
286        Ok(self.list().await?.into_iter().find(|item| &item.id == id))
287    }
288
289    async fn put(&self, item: &ContentItem) -> Result<()> {
290        let _guard = self.lock.write().await;
291        let target = Self::item_path(item);
292        safe_relative(&target)?;
293        let text = render_item(item)?;
294        let id = item.id.clone();
295        self.blocking(move |root| {
296            for (origin, existing) in Self::scan(root)? {
297                if existing.id == id && origin != target {
298                    let old = root.join(&origin);
299                    std::fs::remove_file(&old).map_err(|e| SiteError::io(&old, e))?;
300                }
301            }
302            write_atomic(&root.join(&target), text.as_bytes())
303        })
304        .await
305    }
306
307    async fn remove(&self, id: &ContentId) -> Result<bool> {
308        let _guard = self.lock.write().await;
309        let id = id.clone();
310        self.blocking(move |root| {
311            let mut removed = false;
312            for (origin, existing) in Self::scan(root)? {
313                if existing.id == id {
314                    let path = root.join(&origin);
315                    std::fs::remove_file(&path).map_err(|e| SiteError::io(&path, e))?;
316                    removed = true;
317                }
318            }
319            Ok(removed)
320        })
321        .await
322    }
323
324    async fn read_media(&self, path: &str) -> Result<Option<Bytes>> {
325        let full = self.root.join(safe_relative(path)?);
326        match tokio::fs::read(&full).await {
327            Ok(bytes) => Ok(Some(Bytes::from(bytes))),
328            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
329            Err(e) => Err(SiteError::io(full, e)),
330        }
331    }
332
333    async fn write_media(&self, path: &str, bytes: Bytes) -> Result<()> {
334        let full = self.root.join(safe_relative(path)?);
335        self.blocking(move |_| write_atomic(&full, &bytes)).await
336    }
337}
338
339/// The conformance suite every [`ContentStore`] runs: put, get, list order, replace,
340/// remove, media round trip and path confinement.
341///
342/// # Panics
343///
344/// Panics with the failed expectation.
345pub async fn content_store_conformance(store: &dyn ContentStore, sample: ContentItem) {
346    assert!(store.get(&sample.id).await.unwrap().is_none(), "store must start empty");
347    store.put(&sample).await.unwrap();
348    assert_eq!(store.get(&sample.id).await.unwrap().as_ref(), Some(&sample), "get after put");
349
350    let mut second = sample.clone();
351    second.id = ContentId(format!("{}-b", sample.id.0));
352    second.slug = format!("{}-b", sample.slug);
353    store.put(&second).await.unwrap();
354    let ids: Vec<ContentId> = store.list().await.unwrap().into_iter().map(|i| i.id).collect();
355    assert_eq!(ids, vec![sample.id.clone(), second.id.clone()], "list is sorted by id");
356
357    let mut changed = sample.clone();
358    changed.fields.insert("title".into(), "Changed".into());
359    store.put(&changed).await.unwrap();
360    assert_eq!(store.get(&sample.id).await.unwrap(), Some(changed), "put replaces");
361
362    assert!(store.remove(&second.id).await.unwrap());
363    assert!(!store.remove(&second.id).await.unwrap());
364    assert_eq!(store.list().await.unwrap().len(), 1, "remove deletes one item");
365
366    store.write_media("content/media/a.png", Bytes::from_static(b"png")).await.unwrap();
367    assert_eq!(
368        store.read_media("content/media/a.png").await.unwrap(),
369        Some(Bytes::from_static(b"png"))
370    );
371    assert_eq!(store.read_media("content/media/none.png").await.unwrap(), None);
372    assert!(store.write_media("../escape.png", Bytes::new()).await.is_err(), "no climbing out");
373    assert!(store.read_media("/etc/passwd").await.is_err(), "no absolute paths");
374}