1use std::collections::{BTreeMap, HashSet};
10use std::path::{Path, PathBuf};
11
12use sha1::{Digest, Sha1};
13use thiserror::Error;
14use tokio::fs::File;
15use tokio::io::{AsyncReadExt, AsyncSeekExt, SeekFrom};
16
17#[derive(Debug, Error)]
18pub enum CasError {
19 #[error("io error: {0}")]
20 Io(#[from] std::io::Error),
21 #[error("destination already exists: {}", .0.display())]
22 DestinationExists(PathBuf),
23}
24
25#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct IngestResult {
29 pub hash: String,
30 pub already_existed: bool,
31}
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum LinkKind {
36 Hardlink,
37 Junction,
38 Symlink,
39 Copy,
40}
41
42#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
45pub struct DedupeReport {
46 pub scanned_files: usize,
47 pub deduplicated_files: usize,
48 pub linked_count: usize,
49 pub bytes_reclaimed: u64,
50}
51
52#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]
54pub struct GcReport {
55 pub reclaimed_bytes: u64,
56 pub removed_blobs: usize,
57}
58
59#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
61pub struct CasStats {
62 pub blob_count: usize,
63 pub total_size_bytes: u64,
64}
65
66pub fn blob_path(cas_root: &Path, hash: &str) -> PathBuf {
67 let (prefix, rest) = hash.split_at(2);
68 cas_root.join("sha1").join(prefix).join(rest)
69}
70
71pub fn cas_stats(cas_root: &Path) -> Result<CasStats, std::io::Error> {
73 let mut stack = vec![cas_root.join("sha1")];
74 let mut stats = CasStats::default();
75 while let Some(dir) = stack.pop() {
76 let entries = match std::fs::read_dir(&dir) {
77 Ok(e) => e,
78 Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
79 Err(e) => return Err(e),
80 };
81 for entry in entries {
82 let entry = entry?;
83 let path = entry.path();
84 if path.is_dir() {
85 stack.push(path);
86 } else {
87 let meta = entry.metadata()?;
88 if meta.is_file() {
89 stats.blob_count += 1;
90 stats.total_size_bytes += meta.len();
91 }
92 }
93 }
94 }
95 Ok(stats)
96}
97
98pub async fn ingest_file<P, Q>(cas_root: P, src: Q) -> Result<IngestResult, CasError>
102where
103 P: AsRef<Path>,
104 Q: AsRef<Path>,
105{
106 let src = src.as_ref();
107 let mut reader = File::open(src).await?;
108 let hash = sha1_stream(&mut reader).await?;
109 reader.seek(SeekFrom::Start(0)).await?;
110
111 let blob = blob_path(cas_root.as_ref(), &hash);
112 if tokio::fs::try_exists(&blob).await? {
113 return Ok(IngestResult {
114 hash,
115 already_existed: true,
116 });
117 }
118
119 let parent = blob
120 .parent()
121 .ok_or_else(|| std::io::Error::other("blob path has no parent"))?;
122 tokio::fs::create_dir_all(parent).await?;
123 let tmp = parent.join(format!(
124 ".{}.{}.tmp",
125 blob.file_name()
126 .map(|n| n.to_string_lossy())
127 .unwrap_or_default(),
128 std::process::id()
129 ));
130 let mut out = File::create(&tmp).await?;
131 tokio::io::copy(&mut reader, &mut out).await?;
132 out.sync_all().await?;
133 drop(out);
134
135 match std::fs::rename(&tmp, &blob) {
136 Ok(()) => Ok(IngestResult {
137 hash,
138 already_existed: false,
139 }),
140 Err(_) => {
141 let already = tokio::fs::try_exists(&blob).await?;
142 let _ = tokio::fs::remove_file(&tmp).await;
143 Ok(IngestResult {
144 hash,
145 already_existed: already,
146 })
147 }
148 }
149}
150
151async fn sha1_stream<R: AsyncReadExt + Unpin>(mut reader: R) -> Result<String, std::io::Error> {
152 let mut hasher = Sha1::new();
153 let mut buf = vec![0u8; 64 * 1024];
154 loop {
155 let n = reader.read(&mut buf).await?;
156 if n == 0 {
157 break;
158 }
159 hasher.update(&buf[..n]);
160 }
161 Ok(hasher
162 .finalize()
163 .iter()
164 .map(|b| format!("{b:02x}"))
165 .collect())
166}
167
168fn try_exists(path: &Path) -> std::io::Result<bool> {
169 match std::fs::metadata(path) {
170 Ok(_) => Ok(true),
171 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),
172 Err(e) => Err(e),
173 }
174}
175
176pub async fn link_or_copy(cas_blob: &Path, dest: &Path) -> Result<LinkKind, CasError> {
181 if try_exists(dest)? {
182 return Err(CasError::DestinationExists(dest.to_path_buf()));
183 }
184
185 if std::fs::hard_link(cas_blob, dest).is_ok() {
187 return Ok(LinkKind::Hardlink);
188 }
189
190 #[cfg(windows)]
192 {
193 let cmdline = format!(
194 "mklink /J \"{}\" \"{}\"",
195 dest.display(),
196 cas_blob.display()
197 );
198 let status = std::process::Command::new("cmd")
199 .args(["/C", &cmdline])
200 .current_dir(dest.parent().map(Path::to_path_buf).unwrap_or_default())
201 .stdout(std::process::Stdio::null())
202 .stderr(std::process::Stdio::null())
203 .status();
204 if status.is_ok_and(|s| s.success()) && try_exists(dest)? {
205 return Ok(LinkKind::Junction);
206 }
207 }
208
209 #[cfg(unix)]
211 if std::os::unix::fs::symlink(cas_blob, dest).is_ok() {
212 return Ok(LinkKind::Symlink);
213 }
214 #[cfg(windows)]
215 if std::os::windows::fs::symlink_file(cas_blob, dest).is_ok() {
216 return Ok(LinkKind::Symlink);
217 }
218
219 if let Some(parent) = dest.parent() {
221 tokio::fs::create_dir_all(parent).await?;
222 }
223 tokio::fs::copy(cas_blob, dest).await?;
224 Ok(LinkKind::Copy)
225}
226
227async fn collect_files(
230 dir: &Path,
231 extensions: Option<&[&str]>,
232) -> Result<Vec<PathBuf>, std::io::Error> {
233 let mut files = Vec::new();
234 let mut stack = vec![dir.to_path_buf()];
235 while let Some(current) = stack.pop() {
236 let mut entries = match tokio::fs::read_dir(¤t).await {
237 Ok(entries) => entries,
238 Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,
239 Err(e) => return Err(e),
240 };
241 while let Some(entry) = entries.next_entry().await? {
242 let path = entry.path();
243 if path.is_dir() {
244 stack.push(path);
245 } else {
246 if extensions.is_none()
247 || path
248 .extension()
249 .and_then(|e| e.to_str())
250 .is_some_and(|ext| {
251 extensions.is_some_and(|list| {
252 list.iter().any(|want| ext.eq_ignore_ascii_case(want))
253 })
254 })
255 {
256 files.push(path);
257 }
258 }
259 }
260 }
261 files.sort();
262 Ok(files)
263}
264
265pub async fn deduplicate_dirs(
269 dirs: &[PathBuf],
270 cas_root: &Path,
271 extensions: Option<&[&str]>,
272) -> Result<DedupeReport, CasError> {
273 let mut report = DedupeReport::default();
274 let mut hashes: BTreeMap<String, Vec<PathBuf>> = BTreeMap::new();
275
276 for dir in dirs {
277 for file in collect_files(dir, extensions).await? {
278 let Some(meta) = file.metadata().ok().filter(|m| m.is_file()) else {
279 continue; };
281 if meta.len() == 0 {
282 continue;
283 }
284 report.scanned_files += 1;
285 let result = ingest_file(cas_root, &file).await?;
286 hashes.entry(result.hash).or_default().push(file);
287 }
288 }
289
290 for dups in hashes.values() {
291 if dups.len() < 2 {
292 continue;
293 }
294 let Some(hash) = hashes
296 .iter()
297 .find_map(|(h, list)| (list.as_slice() == dups.as_slice()).then_some(h.clone()))
298 else {
299 continue;
300 };
301 let blob = blob_path(cas_root, &hash);
302 for dest in &dups[1..] {
303 let Ok(meta) = dest.metadata() else {
304 continue; };
306 if try_exists(dest)? {
307 tokio::fs::remove_file(dest).await?;
308 }
309 if link_or_copy(&blob, dest).await.is_err() {
310 tokio::fs::copy(&blob, dest).await?;
311 }
312 report.deduplicated_files += 1;
313 report.linked_count += 1;
314 report.bytes_reclaimed = report.bytes_reclaimed.saturating_add(meta.len());
315 }
316 }
317
318 Ok(report)
319}
320
321async fn referenced_hashes(active_dirs: &[PathBuf]) -> Result<HashSet<String>, CasError> {
323 let mut out = HashSet::new();
324 for dir in active_dirs {
325 for file in collect_files(dir, None).await? {
326 if let Ok(meta) = file.metadata()
327 && meta.is_file()
328 && meta.len() > 0
329 {
330 let mut reader = File::open(&file).await?;
331 out.insert(sha1_stream(&mut reader).await?);
332 }
333 }
334 }
335 Ok(out)
336}
337
338pub async fn cas_garbage_collect_dirs(
342 cas_root: &Path,
343 active_dirs: &[PathBuf],
344) -> Result<GcReport, CasError> {
345 let referenced = referenced_hashes(active_dirs).await?;
346 let mut report = GcReport::default();
347 for entry in collect_files(&cas_root.join("sha1"), None).await? {
348 let name = entry
350 .file_name()
351 .map(|n| n.to_string_lossy().into_owned())
352 .unwrap_or_default();
353 let hash = entry
354 .parent()
355 .and_then(|p| p.file_name())
356 .map(|n| format!("{}{}", n.to_string_lossy(), name))
357 .unwrap_or_default();
358 if referenced.contains(&hash) {
359 continue;
360 }
361 let meta = entry.metadata().map_err(CasError::from)?;
362 if !meta.is_file() {
363 continue;
364 }
365 report.reclaimed_bytes = report.reclaimed_bytes.saturating_add(meta.len());
366 tokio::fs::remove_file(&entry).await?;
367 report.removed_blobs += 1;
368 }
369 Ok(report)
370}
371
372#[cfg(test)]
373mod tests {
374 use super::*;
375
376 fn fixture_root(tag: &str) -> PathBuf {
377 let dir = std::env::temp_dir().join(format!("cas-test-{tag}-{}", std::process::id()));
378 let _ = std::fs::remove_dir_all(&dir);
379 dir
380 }
381
382 fn write_file(dir: &Path, name: &str, content: &[u8]) {
383 std::fs::create_dir_all(dir).unwrap();
384 std::fs::write(dir.join(name), content).unwrap();
385 }
386
387 #[test]
388 fn sha1_hash_matches_known_vector() {
389 let mut hasher = Sha1::new();
390 hasher.update(b"abc");
391 let hex: String = hasher
392 .finalize()
393 .iter()
394 .map(|b| format!("{b:02x}"))
395 .collect();
396 assert_eq!(hex, "a9993e364706816aba3e25717850c26c9cd0d89d");
397 }
398
399 #[tokio::test]
400 async fn ingest_is_idempotent_and_reuses_blobs() {
401 let cas = fixture_root("ingest").join("cas");
402 let src = fixture_root("ingest").join("dup.jar");
403 write_file(src.parent().unwrap(), "dup.jar", b"duplicate jar bytes");
404
405 let first = ingest_file(&cas, &src).await.unwrap();
406 let second = ingest_file(&cas, &src).await.unwrap();
407 assert_eq!(first.hash, second.hash);
408 assert!(!first.already_existed);
409 assert!(second.already_existed);
410 assert!(blob_path(&cas, &first.hash).is_file());
411 std::fs::remove_dir_all(fixture_root("ingest")).ok();
412 }
413
414 #[tokio::test]
415 async fn hardlink_cascade_reports_hardlink() {
416 let base = fixture_root("link");
417 let blob = base.join("cas/sha1/aa/bbccddee");
418 write_file(
419 blob.parent().unwrap(),
420 blob.file_name().unwrap().to_string_lossy().as_ref(),
421 b"blob",
422 );
423 let dest = base.join("dest.bin");
424 let kind = link_or_copy(&blob, &dest).await.unwrap();
425 assert_eq!(kind, LinkKind::Hardlink);
426 assert_eq!(std::fs::read(&dest).unwrap(), b"blob");
427 std::fs::remove_dir_all(&base).ok();
428 }
429
430 #[tokio::test]
431 async fn link_or_copy_refuses_existing_dest() {
432 let base = fixture_root("exists");
433 let blob = base.join("cas/sha1/aa/bb");
434 write_file(blob.parent().unwrap(), "bb", b"blob");
435 let dest = base.join("dest.bin");
436 write_file(dest.parent().unwrap(), "dest.bin", b"occupied");
437 assert!(link_or_copy(&blob, &dest).await.is_err());
438 std::fs::remove_dir_all(&base).ok();
439 }
440
441 #[tokio::test]
442 async fn deduplicate_replaces_duplicate_copies_with_links() {
443 let base = fixture_root("dedup");
444 let cas = base.join("cas");
445 let a = base.join("a");
446 let b = base.join("b");
447 write_file(&a, "dup.bin", b"identical mod bytes");
448 write_file(&b, "dup.bin", b"identical mod bytes");
449
450 let report = deduplicate_dirs(&[a.clone(), b.clone()], &cas, Some(&["bin"]))
451 .await
452 .unwrap();
453 assert!(report.scanned_files >= 2);
454 assert!(report.deduplicated_files >= 1);
455 assert!(report.bytes_reclaimed >= b"identical mod bytes".len() as u64);
456 assert_eq!(
457 std::fs::read(a.join("dup.bin")).unwrap(),
458 b"identical mod bytes"
459 );
460 assert_eq!(
461 std::fs::read(b.join("dup.bin")).unwrap(),
462 b"identical mod bytes"
463 );
464 std::fs::remove_dir_all(&base).ok();
465 }
466
467 #[tokio::test]
468 async fn gc_removes_only_orphaned_blobs() {
469 let base = fixture_root("gc");
470 let cas = base.join("cas");
471 let active = base.join("active");
472 write_file(&active, "kept.bin", b"kept");
473 let referenced = ingest_file(&cas, active.join("kept.bin")).await.unwrap();
474 let orphan = blob_path(&cas, "ff0000000000000000000000000000000000000aa");
475 write_file(
476 orphan.parent().unwrap(),
477 orphan.file_name().unwrap().to_string_lossy().as_ref(),
478 b"orphan",
479 );
480
481 let report = cas_garbage_collect_dirs(&cas, std::slice::from_ref(&active))
482 .await
483 .unwrap();
484 assert!(!orphan.exists(), "orphan blob must be removed");
485 assert!(
486 blob_path(&cas, &referenced.hash).exists(),
487 "referenced blob must stay"
488 );
489 assert_eq!(report.removed_blobs, 1);
490 assert!(report.reclaimed_bytes >= 6);
491 std::fs::remove_dir_all(&base).ok();
492 }
493}