1use 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#[async_trait]
21pub trait ContentStore: Send + Sync {
22 async fn list(&self) -> Result<Vec<ContentItem>>;
28
29 async fn get(&self, id: &ContentId) -> Result<Option<ContentItem>>;
35
36 async fn put(&self, item: &ContentItem) -> Result<()>;
42
43 async fn remove(&self, id: &ContentId) -> Result<bool>;
49
50 async fn read_media(&self, path: &str) -> Result<Option<Bytes>>;
56
57 async fn write_media(&self, path: &str, bytes: Bytes) -> Result<()>;
63}
64
65pub(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#[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#[derive(Debug, Clone)]
149pub struct FsContentStore {
150 root: PathBuf,
151 lock: Arc<RwLock<()>>,
152}
153
154impl FsContentStore {
155 pub fn new(root: impl Into<PathBuf>) -> Self {
157 Self { root: root.into(), lock: Arc::new(RwLock::new(())) }
158 }
159
160 pub fn root(&self) -> &Path {
162 &self.root
163 }
164
165 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
219pub 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
339pub 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}