Skip to main content

cratefield_runtime_native/ports/
blob.rs

1//! A directory-backed [`Blob`] adapter (issue #105): small media on the local
2//! filesystem for a self-hosted deployment. Each object is a file under a base
3//! directory, and its content type is a sibling `.__ct` file. There are no
4//! presigned URLs, so `signed_url` reports [`BlobError::Unsupported`] — serve
5//! the bytes through the harness with [`Blob::get`], or reach for an
6//! S3-compatible adapter when direct downloads matter.
7
8use std::path::PathBuf;
9use std::sync::Arc;
10use std::time::Duration;
11
12use async_trait::async_trait;
13use cratefield_core::{Blob, BlobError, BlobObject};
14
15/// Stores blobs as files under `base`.
16pub struct DirBlob {
17    base: PathBuf,
18}
19
20impl DirBlob {
21    /// A store rooted at `base`. The directory is created on first write.
22    #[must_use]
23    pub fn new(base: impl Into<PathBuf>) -> Self {
24        Self { base: base.into() }
25    }
26
27    /// The store as an `Arc<dyn Blob>`, for `Native::blob_arc`.
28    #[must_use]
29    pub fn arc(base: impl Into<PathBuf>) -> Arc<dyn Blob> {
30        Arc::new(Self::new(base))
31    }
32
33    /// The object path for `key`, refusing an empty, absolute, or escaping key
34    /// (defence in depth — the harness's `ScopedBlob` already prefixes and
35    /// checks, but the adapter must be safe on its own).
36    fn object_path(&self, key: &str) -> Result<PathBuf, BlobError> {
37        if key.is_empty() {
38            return Err(BlobError::BadKey("a blob key cannot be empty".to_owned()));
39        }
40        if key.starts_with('/') {
41            return Err(BlobError::BadKey(format!("key `{key}` must be relative")));
42        }
43        if key
44            .split('/')
45            .any(|segment| segment == ".." || segment == ".")
46        {
47            return Err(BlobError::BadKey(format!(
48                "key `{key}` must not contain `.` or `..` segments"
49            )));
50        }
51        Ok(self.base.join(key))
52    }
53
54    fn content_type_path(path: &std::path::Path) -> PathBuf {
55        PathBuf::from(format!("{}.__ct", path.display()))
56    }
57
58    fn io_err(err: &std::io::Error) -> BlobError {
59        BlobError::Operation(err.to_string())
60    }
61}
62
63#[async_trait]
64impl Blob for DirBlob {
65    async fn put(&self, key: &str, bytes: &[u8], content_type: &str) -> Result<(), BlobError> {
66        let path = self.object_path(key)?;
67        if let Some(parent) = path.parent() {
68            tokio::fs::create_dir_all(parent)
69                .await
70                .map_err(|err| Self::io_err(&err))?;
71        }
72        tokio::fs::write(&path, bytes)
73            .await
74            .map_err(|err| Self::io_err(&err))?;
75        tokio::fs::write(Self::content_type_path(&path), content_type.as_bytes())
76            .await
77            .map_err(|err| Self::io_err(&err))?;
78        Ok(())
79    }
80
81    async fn get(&self, key: &str) -> Result<Option<BlobObject>, BlobError> {
82        let path = self.object_path(key)?;
83        let bytes = match tokio::fs::read(&path).await {
84            Ok(bytes) => bytes,
85            Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
86            Err(err) => return Err(Self::io_err(&err)),
87        };
88        let content_type = tokio::fs::read_to_string(Self::content_type_path(&path))
89            .await
90            .unwrap_or_else(|_| "application/octet-stream".to_owned());
91        Ok(Some(BlobObject {
92            bytes,
93            content_type,
94        }))
95    }
96
97    async fn delete(&self, key: &str) -> Result<(), BlobError> {
98        let path = self.object_path(key)?;
99        for target in [path.clone(), Self::content_type_path(&path)] {
100            match tokio::fs::remove_file(&target).await {
101                Ok(()) => {}
102                Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
103                Err(err) => return Err(Self::io_err(&err)),
104            }
105        }
106        Ok(())
107    }
108
109    async fn signed_url(&self, _key: &str, _ttl: Duration) -> Result<String, BlobError> {
110        Err(BlobError::Unsupported(
111            "a directory store has no presigned URLs; serve the bytes through the harness \
112             or use an S3-compatible adapter"
113                .to_owned(),
114        ))
115    }
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121
122    fn temp_dir() -> PathBuf {
123        std::env::temp_dir().join(format!("cf-blob-{}", uuid_like()))
124    }
125
126    fn uuid_like() -> String {
127        use std::time::{SystemTime, UNIX_EPOCH};
128        format!(
129            "{}",
130            SystemTime::now()
131                .duration_since(UNIX_EPOCH)
132                .unwrap()
133                .as_nanos()
134        )
135    }
136
137    #[tokio::test]
138    async fn round_trips_bytes_and_content_type() {
139        let base = temp_dir();
140        let blob = DirBlob::new(&base);
141        blob.put("cms/hero.png", b"\x89PNG", "image/png")
142            .await
143            .unwrap();
144        let got = blob.get("cms/hero.png").await.unwrap().expect("present");
145        assert_eq!(got.bytes, b"\x89PNG");
146        assert_eq!(got.content_type, "image/png");
147        assert!(blob.get("cms/missing.png").await.unwrap().is_none());
148        let _ = std::fs::remove_dir_all(&base);
149    }
150
151    #[tokio::test]
152    async fn delete_is_idempotent_and_removes_both_files() {
153        let base = temp_dir();
154        let blob = DirBlob::new(&base);
155        blob.put("a/b.txt", b"hi", "text/plain").await.unwrap();
156        blob.delete("a/b.txt").await.unwrap();
157        assert!(blob.get("a/b.txt").await.unwrap().is_none());
158        // A second delete is a no-op, not an error.
159        blob.delete("a/b.txt").await.unwrap();
160        let _ = std::fs::remove_dir_all(&base);
161    }
162
163    #[tokio::test]
164    async fn an_escaping_key_is_refused() {
165        let blob = DirBlob::new(temp_dir());
166        for bad in ["", "/etc/passwd", "../x", "a/../../b", "."] {
167            assert!(matches!(
168                blob.get(bad).await.unwrap_err(),
169                BlobError::BadKey(_)
170            ));
171        }
172    }
173}