Skip to main content

cloudillo_blob_adapter_fs/
lib.rs

1// SPDX-FileCopyrightText: Szilárd Hajba
2// SPDX-License-Identifier: MPL-2.0
3
4use std::{
5	fmt::Debug,
6	path::{Path, PathBuf},
7	pin::Pin,
8};
9
10use async_trait::async_trait;
11use futures_core::Stream;
12use tokio::{
13	fs::{
14		File, copy, create_dir_all, hard_link, metadata, read_dir, remove_dir_all, remove_file,
15		rename,
16	},
17	io::{AsyncRead, AsyncReadExt, AsyncWriteExt},
18};
19use tokio_util::{bytes::Bytes, io::ReaderStream};
20
21use cloudillo_types::{blob_adapter, hasher, prelude::*, snapshot::SnapshotPart};
22
23/// Validates that a file_id hash portion contains only safe characters (base64url alphabet)
24fn validate_hash(hash: &str) -> ClResult<()> {
25	if !hash.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') {
26		return Err(Error::ValidationError("invalid characters in file_id hash".into()));
27	}
28	Ok(())
29}
30
31/// Calculates the path of the directory for a blob
32fn obj_dir(base_dir: &Path, tn_id: TnId, file_id: &str) -> ClResult<PathBuf> {
33	let hash_start = file_id.find('~').ok_or(Error::Parse)? + 1;
34	if file_id.len() < hash_start + 4 {
35		Err(Error::Parse)?;
36	}
37	validate_hash(&file_id[hash_start..])?;
38
39	Ok(PathBuf::from(base_dir)
40		.join(tn_id.to_string())
41		.join(&file_id[hash_start..hash_start + 2])
42		.join(&file_id[hash_start + 2..hash_start + 4]))
43}
44
45fn obj_file_path(base_dir: &Path, tn_id: TnId, file_id: &str) -> ClResult<PathBuf> {
46	let hash_start = file_id.find('~').ok_or(Error::Parse)? + 1;
47	if file_id.len() < hash_start + 5 {
48		Err(Error::Parse)?;
49	}
50	validate_hash(&file_id[hash_start..])?;
51
52	Ok(PathBuf::from(base_dir)
53		.join(tn_id.to_string())
54		.join(&file_id[hash_start..hash_start + 2])
55		.join(&file_id[hash_start + 2..hash_start + 4])
56		.join(file_id))
57}
58
59fn obj_tmp_file_path(base_dir: &Path, tn_id: TnId, file_id: &str) -> ClResult<PathBuf> {
60	let tmp_id = format!("tmp-{}", cloudillo_types::utils::random_id()?);
61	let hash_start = file_id.find('~').ok_or(Error::Parse)? + 1;
62	if file_id.len() < hash_start + 5 {
63		Err(Error::Parse)?;
64	}
65	validate_hash(&file_id[hash_start..])?;
66
67	Ok(PathBuf::from(base_dir).join(tn_id.to_string()).join(&tmp_id))
68}
69
70#[derive(Debug)]
71pub struct BlobAdapterFs {
72	base_dir: Box<Path>,
73}
74
75impl BlobAdapterFs {
76	pub async fn new(base_dir: Box<Path>) -> Result<Self, Error> {
77		create_dir_all(&base_dir).await?;
78		Ok(Self { base_dir })
79	}
80}
81
82#[async_trait]
83impl blob_adapter::BlobAdapter for BlobAdapterFs {
84	/// Creates a new blob from a buffer
85	async fn create_blob_buf(
86		&self,
87		tn_id: TnId,
88		file_id: &str,
89		data: &[u8],
90		_opts: &blob_adapter::CreateBlobOptions,
91	) -> ClResult<()> {
92		info!("create_blob_buf: {:?}", obj_file_path(&self.base_dir, tn_id, file_id)?);
93		create_dir_all(obj_dir(&self.base_dir, tn_id, file_id)?).await?;
94
95		// tmp+rename: a fresh inode, so hard-linked snapshots keep the old bytes
96		let tmp_path = obj_tmp_file_path(&self.base_dir, tn_id, file_id)?;
97		let res = async {
98			let mut file = File::create(&tmp_path).await?;
99			file.write_all(data).await?;
100			file.sync_all().await?;
101			rename(&tmp_path, obj_file_path(&self.base_dir, tn_id, file_id)?).await?;
102			Ok::<(), Error>(())
103		}
104		.await;
105		if let Err(e) = res {
106			let _ = remove_file(&tmp_path).await;
107			return Err(e);
108		}
109
110		Ok(())
111	}
112
113	/// Creates a new blob using a stream
114	async fn create_blob_stream(
115		&self,
116		tn_id: TnId,
117		file_id: &str,
118		stream: &mut (dyn AsyncRead + Send + Unpin),
119	) -> ClResult<()> {
120		create_dir_all(obj_dir(&self.base_dir, tn_id, file_id)?).await?;
121
122		let tmp_path = obj_tmp_file_path(&self.base_dir, tn_id, file_id)?;
123		info!("  attachment tmpfile: {:?}", &tmp_path);
124		let mut file = File::create(&tmp_path).await?;
125		let mut hasher = hasher::Hasher::new();
126		let mut buf = [0u8; 8192];
127
128		let res = async {
129			loop {
130				let n = stream.read(&mut buf).await?;
131				if n == 0 {
132					break;
133				}
134				file.write_all(&buf[0..n]).await?;
135				hasher.update(&buf[0..n]);
136			}
137			let id = hasher.finalize("b");
138
139			if id != file_id {
140				return Err(Error::ValidationError(format!(
141					"blob hash mismatch: expected {}, got {}",
142					file_id, id
143				)));
144			}
145			rename(&tmp_path, obj_file_path(&self.base_dir, tn_id, &id)?).await?;
146			info!("  attachment downloaded: {}", &id);
147			Ok::<(), Error>(())
148		}
149		.await;
150		if let Err(e) = res {
151			info!("  attachment download failed, removing tmpfile: {:?}", &tmp_path);
152			let _ = remove_file(&tmp_path).await;
153			return Err(e);
154		}
155
156		Ok(())
157	}
158
159	/// Checks if a blob exists, returns its size and mtime
160	async fn stat_blob(&self, tn_id: TnId, blob_id: &str) -> Option<blob_adapter::BlobStat> {
161		let path = obj_file_path(&self.base_dir, tn_id, blob_id).ok()?;
162		let file_metadata = metadata(&path).await.ok()?;
163		let modified_at = file_metadata
164			.modified()
165			.ok()
166			.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
167			.and_then(|d| i64::try_from(d.as_secs()).ok())
168			.unwrap_or(0);
169		Some(blob_adapter::BlobStat { size: file_metadata.len(), modified_at })
170	}
171
172	/// Reads a blob
173	async fn read_blob_buf(&self, tn_id: TnId, blob_id: &str) -> ClResult<Box<[u8]>> {
174		let mut file = File::open(obj_file_path(&self.base_dir, tn_id, blob_id)?).await?;
175		let mut buf: Vec<u8> = Vec::new();
176		file.read_to_end(&mut buf).await?;
177
178		Ok(buf.into_boxed_slice())
179	}
180
181	/// Reads a byte range from a blob as a stream (no full buffering).
182	async fn read_blob_range_stream(
183		&self,
184		tn_id: TnId,
185		blob_id: &str,
186		offset: u64,
187		length: u64,
188	) -> ClResult<Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>>> {
189		use tokio::io::AsyncSeekExt;
190
191		let mut file = File::open(obj_file_path(&self.base_dir, tn_id, blob_id)?)
192			.await
193			.map_err(|_| Error::NotFound)?;
194		file.seek(std::io::SeekFrom::Start(offset))
195			.await
196			.map_err(|e| Error::Internal(format!("blob range seek failed: {e}")))?;
197		let stream = ReaderStream::new(file.take(length));
198		Ok(Box::pin(stream))
199	}
200
201	/// Reads a blob
202	async fn read_blob_stream(
203		&self,
204		tn_id: TnId,
205		blob_id: &str,
206	) -> ClResult<Pin<Box<dyn Stream<Item = Result<Bytes, std::io::Error>> + Send>>> {
207		debug!("path: {:?}", obj_file_path(&self.base_dir, tn_id, blob_id)?);
208		let file = File::open(obj_file_path(&self.base_dir, tn_id, blob_id)?)
209			.await
210			.map_err(|_| Error::NotFound)?;
211		let stream = ReaderStream::new(file);
212
213		Ok(Box::pin(stream))
214	}
215
216	async fn create_blob_from_path(
217		&self,
218		tn_id: TnId,
219		file_id: &str,
220		source: &Path,
221		_opts: &blob_adapter::CreateBlobOptions,
222	) -> ClResult<()> {
223		create_dir_all(obj_dir(&self.base_dir, tn_id, file_id)?).await?;
224
225		// tmp+rename, as in `create_blob_buf`: copying straight onto the target would
226		// rewrite an inode that backup snapshots may hard-link.
227		let tmp_path = obj_tmp_file_path(&self.base_dir, tn_id, file_id)?;
228		let res = async {
229			copy(source, &tmp_path).await?;
230			File::open(&tmp_path).await?.sync_all().await?;
231			rename(&tmp_path, obj_file_path(&self.base_dir, tn_id, file_id)?).await?;
232			Ok::<(), Error>(())
233		}
234		.await;
235		if let Err(e) = res {
236			let _ = remove_file(&tmp_path).await;
237			return Err(e);
238		}
239		Ok(())
240	}
241
242	async fn delete_tenant_blobs(&self, tn_id: TnId) -> ClResult<()> {
243		let tenant_dir = PathBuf::from(self.base_dir.as_ref()).join(tn_id.to_string());
244
245		match remove_dir_all(&tenant_dir).await {
246			Ok(()) => Ok(()),
247			Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
248			Err(e) => Err(Error::from(e)),
249		}
250	}
251
252	async fn delete_blob(&self, tn_id: TnId, blob_id: &str) -> ClResult<()> {
253		let path = obj_file_path(&self.base_dir, tn_id, blob_id)?;
254		match remove_file(&path).await {
255			Ok(()) => {
256				// Best-effort prune of now-empty shard dirs. `remove_dir` fails
257				// with `DirectoryNotEmpty` (or, on some platforms, `Other` /
258				// `ENOTEMPTY`) when siblings still exist; we ignore every
259				// error here — leaving an empty dir is harmless, and racing
260				// with a concurrent `create_dir_all` is fine because the
261				// next blob write will recreate the path.
262				if let (Some(leaf), Some(mid)) =
263					(path.parent(), path.parent().and_then(|p| p.parent()))
264				{
265					let _ = tokio::fs::remove_dir(leaf).await;
266					let _ = tokio::fs::remove_dir(mid).await;
267				}
268				Ok(())
269			}
270			Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
271			Err(e) => Err(Error::from(e)),
272		}
273	}
274
275	async fn cleanup_tmp_files(&self, tn_id: TnId, cutoff_secs: i64) -> ClResult<u64> {
276		let tenant_dir = PathBuf::from(self.base_dir.as_ref()).join(tn_id.to_string());
277		let mut rd = match read_dir(&tenant_dir).await {
278			Ok(rd) => rd,
279			Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),
280			Err(e) => return Err(Error::from(e)),
281		};
282		let mut removed: u64 = 0;
283		while let Some(entry) = rd.next_entry().await.map_err(Error::from)? {
284			let name = entry.file_name();
285			let Some(name) = name.to_str() else {
286				continue;
287			};
288			if !name.starts_with("tmp-") {
289				continue;
290			}
291			let ft = entry.file_type().await.map_err(Error::from)?;
292			if !ft.is_file() {
293				continue;
294			}
295			let Ok(md) = entry.metadata().await else {
296				continue;
297			};
298			let mtime = md
299				.modified()
300				.ok()
301				.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
302				.and_then(|d| i64::try_from(d.as_secs()).ok())
303				.unwrap_or(0);
304			if mtime > cutoff_secs {
305				continue;
306			}
307			match remove_file(entry.path()).await {
308				Ok(()) => removed += 1,
309				Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
310				Err(e) => warn!("blob-gc: tmp cleanup failed for {:?}: {}", entry.path(), e),
311			}
312		}
313		Ok(removed)
314	}
315
316	async fn list_blobs(
317		&self,
318		tn_id: TnId,
319	) -> ClResult<Pin<Box<dyn Stream<Item = ClResult<String>> + Send>>> {
320		let tenant_dir = PathBuf::from(self.base_dir.as_ref()).join(tn_id.to_string());
321		let stream = async_stream::try_stream! {
322			let mut outer = match read_dir(&tenant_dir).await {
323				Ok(rd) => rd,
324				Err(e) if e.kind() == std::io::ErrorKind::NotFound => return,
325				Err(e) => Err(Error::from(e))?,
326			};
327			while let Some(lvl1) = outer.next_entry().await.map_err(Error::from)? {
328				if !lvl1.file_type().await.map_err(Error::from)?.is_dir() {
329					continue;
330				}
331				let mut inner = read_dir(lvl1.path()).await.map_err(Error::from)?;
332				while let Some(lvl2) = inner.next_entry().await.map_err(Error::from)? {
333					if !lvl2.file_type().await.map_err(Error::from)?.is_dir() {
334						continue;
335					}
336					let mut leaf = read_dir(lvl2.path()).await.map_err(Error::from)?;
337					while let Some(entry) = leaf.next_entry().await.map_err(Error::from)? {
338						if !entry.file_type().await.map_err(Error::from)?.is_file() {
339							continue;
340						}
341						if let Some(name) = entry.file_name().to_str() {
342							// `tmp-*` artifacts live above the shard dirs
343							// (see `create_blob_stream`), not at the leaf, so
344							// they cannot reach this loop — the previous skip
345							// here was dead code. `cleanup_tmp_files` handles
346							// those separately.
347							yield name.to_string();
348						}
349					}
350				}
351			}
352		};
353		Ok(Box::pin(stream))
354	}
355
356	async fn snapshot(&self, dest: &Path, prev: Option<&Path>) -> ClResult<SnapshotPart> {
357		let mut part = SnapshotPart::default();
358		// Relative directories still to walk; the empty path is the store root.
359		let mut dirs = vec![PathBuf::new()];
360		while let Some(dir) = dirs.pop() {
361			// A directory may vanish under us (tenant purge): skip it, not the run.
362			let mut rd = match read_dir(self.base_dir.join(&dir)).await {
363				Ok(rd) => rd,
364				Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
365				Err(e) => return Err(Error::from(e)),
366			};
367			while let Some(entry) = rd.next_entry().await? {
368				let name = entry.file_name();
369				// In-progress uploads, see `obj_tmp_file_path`.
370				if name.to_str().is_some_and(|n| n.starts_with("tmp-")) {
371					continue;
372				}
373				let rel = dir.join(&name);
374				let ft = entry.file_type().await?;
375				if ft.is_dir() {
376					create_dir_all(dest.join(&rel)).await?;
377					dirs.push(rel);
378					continue;
379				}
380				if !ft.is_file() {
381					continue;
382				}
383				let to = dest.join(&rel);
384				// A hard link to the live file: an unchanged blob is the same inode as in
385				// the previous snapshot, so it dedups, and a rewritten one (tmp+rename) is a
386				// new inode, so the snapshot gets the new bytes.
387				let mut linked = hard_link(entry.path(), &to).await.is_ok();
388				// Cross-device: reuse the previous snapshot's copy when the size matches and
389				// the live file is not newer than it. Writes are tmp+rename, never in place,
390				// so a rewrite after the previous snapshot has a later mtime and gets copied.
391				// An unreadable mtime means no reuse.
392				if !linked && let Some(prev) = prev {
393					let prev_file = prev.join(&rel);
394					if let (Ok(a), Ok(b)) = (metadata(&prev_file).await, entry.metadata().await)
395						&& a.len() == b.len()
396						&& let (Ok(pm), Ok(lm)) = (a.modified(), b.modified())
397						&& lm <= pm
398					{
399						linked = hard_link(prev_file, &to).await.is_ok();
400					}
401				}
402				if !linked {
403					match copy(entry.path(), &to).await {
404						Ok(_) => {}
405						// Deleted by GC since the directory was listed.
406						Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
407						Err(e) => return Err(Error::from(e)),
408					}
409				}
410				part.bytes += metadata(&to).await?.len();
411				part.files.push(rel);
412			}
413		}
414		Ok(part)
415	}
416}
417
418#[cfg(test)]
419mod test {
420	use std::path::{Path, PathBuf};
421
422	use crate::obj_dir;
423	use cloudillo_types::types::TnId;
424
425	#[test]
426	fn test_obj_dir() {
427		let file_id = "f1~1234567890";
428		let dir = obj_dir(Path::new("some_dir"), TnId(42), file_id).unwrap_or_default();
429		assert_eq!(dir, PathBuf::from("some_dir/42/12/34"));
430	}
431
432	#[test]
433	fn test_path_traversal_rejected() {
434		let malicious_id = "f1~../../etc/passwd";
435		assert!(obj_dir(Path::new("some_dir"), TnId(42), malicious_id).is_err());
436	}
437
438	#[test]
439	fn test_slash_in_hash_rejected() {
440		let malicious_id = "f1~ab/cd/evil";
441		assert!(obj_dir(Path::new("some_dir"), TnId(42), malicious_id).is_err());
442	}
443
444	#[tokio::test]
445	async fn test_read_blob_range_stream() {
446		use crate::BlobAdapterFs;
447		use cloudillo_types::blob_adapter::{BlobAdapter, CreateBlobOptions};
448		use futures::TryStreamExt;
449
450		let dir = tempfile::tempdir().unwrap();
451		let adapter = BlobAdapterFs::new(dir.path().into()).await.unwrap();
452
453		let blob_id = "b1~abcdefghij";
454		let data: Vec<u8> = (0u8..32).collect();
455		adapter
456			.create_blob_buf(TnId(7), blob_id, &data, &CreateBlobOptions::default())
457			.await
458			.unwrap();
459
460		// Read bytes [4, 12) — offset 4, length 8.
461		let chunks: Vec<_> = adapter
462			.read_blob_range_stream(TnId(7), blob_id, 4, 8)
463			.await
464			.unwrap()
465			.try_collect()
466			.await
467			.unwrap();
468		let read: Vec<u8> = chunks.concat();
469		assert_eq!(read, data[4..12]);
470	}
471}
472
473// vim: ts=4