1use std::{
5 borrow::Cow,
6 fs, io,
7 io::Write,
8 ops::Deref,
9 path::{Path, PathBuf},
10 sync::{
11 Arc,
12 atomic::{AtomicBool, AtomicUsize, Ordering},
13 },
14};
15
16use lru_mem::{HeapSize, MemSize};
17use rkyv::{
18 Archive, Deserialize as RkyvDeserialize, Serialize as RkyvSerialize,
19 api::high::{HighSerializer, HighValidator},
20 bytecheck::CheckBytes,
21 de::Pool,
22 rancor::{Error as RkyvError, Strategy},
23 ser::allocator::ArenaHandle,
24 util::AlignedVec,
25};
26use tempfile::NamedTempFile;
27use threadpool::ThreadPool;
28
29use crate::{
30 errors::GitError,
31 hash::{HashKind, ObjectHash},
32 internal::{
33 metadata::{EntryMeta, MetaAttached},
34 object::types::ObjectType,
35 pack::{entry::Entry, utils},
36 },
37};
38
39pub trait FileLoadStore: Sized {
43 fn f_load(path: &Path) -> Result<Self, io::Error>;
44 fn f_save(&self, path: &Path) -> Result<(), io::Error>;
45}
46
47fn write_bytes_atomically(path: &Path, data: &[u8]) -> Result<(), io::Error> {
48 if path.exists() {
49 return Ok(());
50 }
51 let dir = path
52 .parent()
53 .filter(|parent| !parent.as_os_str().is_empty())
54 .unwrap_or_else(|| Path::new("."));
55
56 let mut temp_file = NamedTempFile::new_in(dir)?;
57 temp_file.write_all(data)?;
58
59 match temp_file.persist_noclobber(path) {
60 Ok(_persisted) => Ok(()),
61 Err(err) if err.error.kind() == io::ErrorKind::AlreadyExists && path.exists() => Ok(()),
62 Err(err) => Err(err.error),
63 }
64}
65
66impl<T> FileLoadStore for T
67where
68 T: Archive,
69 T: for<'a> RkyvSerialize<HighSerializer<AlignedVec, ArenaHandle<'a>, RkyvError>>,
70 T::Archived: for<'a> CheckBytes<HighValidator<'a, RkyvError>>
71 + RkyvDeserialize<T, Strategy<Pool, RkyvError>>,
72{
73 fn f_load(path: &Path) -> Result<T, io::Error> {
75 let data = fs::read(path)?;
76 let obj = rkyv::from_bytes::<T, RkyvError>(&data).map_err(io::Error::other)?;
77 Ok(obj)
78 }
79
80 fn f_save(&self, path: &Path) -> Result<(), io::Error> {
81 if path.exists() {
82 return Ok(());
83 }
84
85 let data = rkyv::to_bytes::<RkyvError>(self).map_err(io::Error::other)?;
86 write_bytes_atomically(path, &data)
87 }
88}
89
90#[derive(
92 PartialEq,
93 Eq,
94 Clone,
95 Debug,
96 serde::Serialize,
97 serde::Deserialize,
98 rkyv::Archive,
99 rkyv::Serialize,
100 rkyv::Deserialize,
101)]
102pub(crate) enum CacheObjectInfo {
103 BaseObject(ObjectType, ObjectHash),
107 OffsetDelta(usize, usize),
110 OffsetZstdelta(usize, usize),
112 HashDelta(ObjectHash, usize),
115}
116
117impl CacheObjectInfo {
118 pub(crate) fn object_type(&self) -> ObjectType {
120 match self {
121 CacheObjectInfo::BaseObject(obj_type, _) => *obj_type,
122 CacheObjectInfo::OffsetDelta(_, _) => ObjectType::OffsetDelta,
123 CacheObjectInfo::OffsetZstdelta(_, _) => ObjectType::OffsetZstdelta,
124 CacheObjectInfo::HashDelta(_, _) => ObjectType::HashDelta,
125 }
126 }
127}
128
129#[derive(Debug)]
131pub struct CacheObject {
132 pub(crate) info: CacheObjectInfo,
133 pub offset: usize,
134 pub crc32: u32,
135 pub data_decompressed: Vec<u8>,
136 pub mem_recorder: Option<Arc<AtomicUsize>>, pub is_delta_in_pack: bool,
138 pub(crate) known_hash: Option<ObjectHash>,
139}
140
141#[derive(Debug, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)]
142struct CacheObjectOnDisk {
143 info: CacheObjectInfo,
144 offset: usize,
145 crc32: u32,
146 data_decompressed: Vec<u8>,
147 is_delta_in_pack: bool,
148}
149
150#[derive(Debug, rkyv::Archive, rkyv::Serialize)]
151struct CacheObjectOnDiskRef<'a> {
152 #[rkyv(with = rkyv::with::AsOwned)]
153 info: Cow<'a, CacheObjectInfo>,
154 offset: usize,
155 crc32: u32,
156 #[rkyv(with = rkyv::with::AsOwned)]
157 data_decompressed: Cow<'a, [u8]>,
158 is_delta_in_pack: bool,
159}
160
161impl<'a> From<&'a CacheObject> for CacheObjectOnDiskRef<'a> {
162 fn from(value: &'a CacheObject) -> Self {
163 Self {
164 info: Cow::Borrowed(&value.info),
165 offset: value.offset,
166 crc32: value.crc32,
167 data_decompressed: Cow::Borrowed(value.data_decompressed.as_slice()),
168 is_delta_in_pack: value.is_delta_in_pack,
169 }
170 }
171}
172
173impl From<CacheObjectOnDisk> for CacheObject {
174 fn from(value: CacheObjectOnDisk) -> Self {
175 Self {
176 info: value.info,
177 offset: value.offset,
178 crc32: value.crc32,
179 data_decompressed: value.data_decompressed,
180 mem_recorder: None,
181 is_delta_in_pack: value.is_delta_in_pack,
182 known_hash: None,
183 }
184 }
185}
186
187impl FileLoadStore for CacheObject {
188 fn f_load(path: &Path) -> Result<Self, io::Error> {
189 let obj = CacheObjectOnDisk::f_load(path)?;
190 Ok(obj.into())
191 }
192
193 fn f_save(&self, path: &Path) -> Result<(), io::Error> {
194 if path.exists() {
195 return Ok(());
196 }
197
198 let data = rkyv::to_bytes::<RkyvError>(&CacheObjectOnDiskRef::from(self))
199 .map_err(io::Error::other)?;
200 write_bytes_atomically(path, &data)
201 }
202}
203
204impl Clone for CacheObject {
205 fn clone(&self) -> Self {
206 let obj = CacheObject {
207 info: self.info.clone(),
208 offset: self.offset,
209 crc32: self.crc32,
210 data_decompressed: self.data_decompressed.clone(),
211 mem_recorder: self.mem_recorder.clone(),
212 is_delta_in_pack: self.is_delta_in_pack,
213 known_hash: self.known_hash,
214 };
215 obj.record_mem_size();
216 obj
217 }
218}
219
220impl HeapSize for CacheObject {
224 fn heap_size(&self) -> usize {
234 match &self.info {
235 CacheObjectInfo::BaseObject(_, _) => self.data_decompressed.heap_size(),
236 CacheObjectInfo::OffsetDelta(_, delta_final_size)
237 | CacheObjectInfo::OffsetZstdelta(_, delta_final_size)
238 | CacheObjectInfo::HashDelta(_, delta_final_size) => {
239 self.data_decompressed.heap_size() + delta_final_size
250 }
251 }
252 }
253}
254
255impl Drop for CacheObject {
256 fn drop(&mut self) {
259 if let Some(mem_recorder) = &self.mem_recorder {
261 mem_recorder.fetch_sub((*self).mem_size(), Ordering::Release);
262 }
263 }
264}
265
266pub trait MemSizeRecorder: MemSize {
273 fn record_mem_size(&self);
274 fn set_mem_recorder(&mut self, mem_size: Arc<AtomicUsize>);
275 }
277
278impl MemSizeRecorder for CacheObject {
279 fn record_mem_size(&self) {
282 if let Some(mem_recorder) = &self.mem_recorder {
283 mem_recorder.fetch_add(self.mem_size(), Ordering::Release);
284 }
285 }
286
287 fn set_mem_recorder(&mut self, mem_recorder: Arc<AtomicUsize>) {
288 self.mem_recorder = Some(mem_recorder);
289 }
290
291 }
295
296impl CacheObject {
297 pub fn new_for_undeltified_with_kind(
300 kind: HashKind,
301 obj_type: ObjectType,
302 data: Vec<u8>,
303 offset: usize,
304 crc32: u32,
305 ) -> Result<Self, GitError> {
306 let hash = utils::calculate_object_hash_for_kind(kind, obj_type, &data)?;
307 Ok(CacheObject {
308 info: CacheObjectInfo::BaseObject(obj_type, hash),
309 offset,
310 crc32,
311 data_decompressed: data,
312 mem_recorder: None,
313 is_delta_in_pack: false,
314 known_hash: None,
315 })
316 }
317
318 pub fn new_for_undeltified(
322 obj_type: ObjectType,
323 data: Vec<u8>,
324 offset: usize,
325 crc32: u32,
326 ) -> Self {
327 let hash = utils::calculate_object_hash(obj_type, &data);
328 CacheObject {
329 info: CacheObjectInfo::BaseObject(obj_type, hash),
330 offset,
331 crc32,
332 data_decompressed: data,
333 mem_recorder: None,
334 is_delta_in_pack: false,
335 known_hash: None,
336 }
337 }
338
339 pub fn object_type(&self) -> ObjectType {
341 self.info.object_type()
342 }
343
344 pub fn base_object_hash(&self) -> Option<ObjectHash> {
348 match &self.info {
349 CacheObjectInfo::BaseObject(_, hash) => Some(*hash),
350 _ => None,
351 }
352 }
353
354 pub fn offset_delta(&self) -> Option<usize> {
358 match &self.info {
359 CacheObjectInfo::OffsetDelta(offset, _) => Some(*offset),
360 _ => None,
361 }
362 }
363
364 pub fn hash_delta(&self) -> Option<ObjectHash> {
368 match &self.info {
369 CacheObjectInfo::HashDelta(hash, _) => Some(*hash),
370 _ => None,
371 }
372 }
373
374 pub fn to_entry(&self) -> Entry {
376 match self.info {
377 CacheObjectInfo::BaseObject(obj_type, hash) => Entry {
378 obj_type,
379 data: self.data_decompressed.clone(),
380 hash,
381 chain_len: 0,
382 },
383 _ => {
384 unreachable!("delta object should not persist!")
385 }
386 }
387 }
388
389 pub fn to_entry_metadata(&self) -> MetaAttached<Entry, EntryMeta> {
391 match self.info {
392 CacheObjectInfo::BaseObject(obj_type, hash) => {
393 let entry = Entry {
394 obj_type,
395 data: self.data_decompressed.clone(),
396 hash,
397 chain_len: 0,
398 };
399 let meta = EntryMeta {
400 pack_offset: Some(self.offset),
402 crc32: Some(self.crc32),
403 is_delta: Some(self.is_delta_in_pack),
404 ..Default::default()
405 };
406 MetaAttached { inner: entry, meta }
407 }
408
409 _ => {
410 unreachable!("delta object should not persist!")
411 }
412 }
413 }
414
415 pub fn into_entry_metadata(mut self) -> MetaAttached<Entry, EntryMeta> {
417 let recorded_size = self.mem_size();
418 if let Some(mem_recorder) = self.mem_recorder.take() {
419 mem_recorder.fetch_sub(recorded_size, Ordering::Release);
420 }
421
422 match self.info {
423 CacheObjectInfo::BaseObject(obj_type, hash) => {
424 let data = std::mem::take(&mut self.data_decompressed);
425 let entry = Entry {
426 obj_type,
427 data,
428 hash,
429 chain_len: 0,
430 };
431 let meta = EntryMeta {
432 pack_offset: Some(self.offset),
433 crc32: Some(self.crc32),
434 is_delta: Some(self.is_delta_in_pack),
435 ..Default::default()
436 };
437 MetaAttached { inner: entry, meta }
438 }
439
440 _ => {
441 unreachable!("delta object should not persist!")
442 }
443 }
444 }
445}
446
447pub trait ArcWrapperBounds: HeapSize + FileLoadStore + Send + Sync + 'static {}
449impl<T: HeapSize + FileLoadStore + Send + Sync + 'static> ArcWrapperBounds for T {}
452
453pub struct ArcWrapper<T: ArcWrapperBounds> {
457 pub data: Arc<T>,
458 complete_signal: Arc<AtomicBool>,
459 pool: Option<Arc<ThreadPool>>,
460 pub store_path: Option<PathBuf>, }
462impl<T: ArcWrapperBounds> ArcWrapper<T> {
463 pub fn new(data: Arc<T>, share_flag: Arc<AtomicBool>, pool: Option<Arc<ThreadPool>>) -> Self {
465 ArcWrapper {
466 data,
467 complete_signal: share_flag,
468 pool,
469 store_path: None,
470 }
471 }
472 pub fn set_store_path(&mut self, path: PathBuf) {
474 self.store_path = Some(path);
475 }
476}
477
478impl<T: ArcWrapperBounds> HeapSize for ArcWrapper<T> {
479 fn heap_size(&self) -> usize {
480 self.data.heap_size()
481 }
482}
483
484impl<T: ArcWrapperBounds> Clone for ArcWrapper<T> {
485 fn clone(&self) -> Self {
487 ArcWrapper {
488 data: self.data.clone(),
489 complete_signal: self.complete_signal.clone(),
490 pool: self.pool.clone(),
491 store_path: None,
492 }
493 }
494}
495
496impl<T: ArcWrapperBounds> Deref for ArcWrapper<T> {
497 type Target = Arc<T>;
498 fn deref(&self) -> &Self::Target {
499 &self.data
500 }
501}
502impl<T: ArcWrapperBounds> Drop for ArcWrapper<T> {
503 fn drop(&mut self) {
506 if !self.complete_signal.load(Ordering::Acquire)
507 && let Some(path) = &self.store_path
508 {
509 match &self.pool {
510 Some(pool) => {
511 let data_copy = self.data.clone();
512 let path_copy = path.clone();
513 let complete_signal = self.complete_signal.clone();
514 while pool.queued_count() > 2000 {
517 std::thread::yield_now();
518 }
519 pool.execute(move || {
520 if !complete_signal.load(Ordering::Acquire) {
521 let res = data_copy.f_save(&path_copy);
522 if let Err(e) = res {
523 println!("[f_save] {path_copy:?} error: {e:?}");
524 }
525 }
526 });
527 }
528 None => {
529 let res = self.data.f_save(path);
530 if let Err(e) = res {
531 println!("[f_save] {path:?} error: {e:?}");
532 }
533 }
534 }
535 }
536 }
537}
538#[cfg(test)]
539mod test {
540 use std::{fs, sync::Mutex};
541
542 use lru_mem::LruCache;
543 use tempfile::tempdir;
544
545 use super::*;
546 use crate::hash::{HashKind, set_hash_kind_for_test};
547
548 fn make_obj(size: usize) -> CacheObject {
550 CacheObject {
551 info: CacheObjectInfo::BaseObject(ObjectType::Blob, ObjectHash::default()),
552 offset: 0,
553 crc32: 0,
554 data_decompressed: vec![0; size],
555 mem_recorder: None,
556 is_delta_in_pack: false,
557 known_hash: None,
558 }
559 }
560
561 #[test]
563 fn test_heap_size_record() {
564 for (kind, size) in [(HashKind::Sha1, 1024usize), (HashKind::Sha256, 2048usize)] {
565 let _guard = set_hash_kind_for_test(kind);
566 let mut obj = make_obj(size);
567 let mem = Arc::new(AtomicUsize::default());
568 assert_eq!(mem.load(Ordering::Relaxed), 0);
569 obj.set_mem_recorder(mem.clone());
570 obj.record_mem_size();
571 assert_eq!(mem.load(Ordering::Relaxed), obj.mem_size());
572 drop(obj);
573 assert_eq!(mem.load(Ordering::Relaxed), 0);
574 }
575 }
576
577 #[test]
579 fn test_cache_object_with_same_size() {
580 for (kind, size) in [(HashKind::Sha1, 1024usize), (HashKind::Sha256, 2048usize)] {
581 let _guard = set_hash_kind_for_test(kind);
582 let a = make_obj(size);
583 assert_eq!(a.heap_size(), size);
584
585 let b = ArcWrapper::new(Arc::new(a.clone()), Arc::new(AtomicBool::new(false)), None);
586 assert_eq!(b.heap_size(), size);
587 }
588 }
589
590 #[test]
592 fn test_cache_object_with_lru() {
593 for (kind, cap, size_a, size_b) in [
594 (
595 HashKind::Sha1,
596 2048usize,
597 1024usize,
598 (1024.0 * 1.5) as usize,
599 ),
600 (
601 HashKind::Sha256,
602 4096usize,
603 2048usize,
604 (2048.0 * 1.5) as usize,
605 ),
606 ] {
607 let _guard = set_hash_kind_for_test(kind);
608 let mut cache = LruCache::new(cap);
609
610 let hash_a = ObjectHash::default();
611 let hash_b = ObjectHash::new(b"b"); let a = make_obj(size_a);
613 let b = make_obj(size_b);
614
615 {
616 let r = cache.insert(
617 hash_a.to_string(),
618 ArcWrapper::new(Arc::new(a.clone()), Arc::new(AtomicBool::new(true)), None),
619 );
620 assert!(r.is_ok());
621 }
622
623 {
624 let r = cache.try_insert(
625 hash_b.to_string(),
626 ArcWrapper::new(Arc::new(b.clone()), Arc::new(AtomicBool::new(true)), None),
627 );
628 assert!(r.is_err());
629 if let Err(lru_mem::TryInsertError::WouldEjectLru { .. }) = r {
630 } else {
632 panic!("Expected WouldEjectLru error");
633 }
634
635 let r = cache.insert(
636 hash_b.to_string(),
637 ArcWrapper::new(Arc::new(b.clone()), Arc::new(AtomicBool::new(true)), None),
638 );
639 assert!(r.is_ok());
640 }
641
642 {
643 let r = cache.get(&hash_a.to_string());
644 assert!(r.is_none());
645 }
646 }
647 }
648
649 #[derive(
651 serde::Serialize, serde::Deserialize, rkyv::Archive, rkyv::Serialize, rkyv::Deserialize,
652 )]
653 struct Test {
654 a: usize,
655 }
656 impl Drop for Test {
657 fn drop(&mut self) {
658 println!("drop Test");
659 }
660 }
661 impl HeapSize for Test {
662 fn heap_size(&self) -> usize {
663 self.a
664 }
665 }
666 #[test]
667 fn test_lru_drop() {
668 println!("insert a");
669 let cache = LruCache::new(2048);
670 let cache = Arc::new(Mutex::new(cache));
671 {
672 let mut c = cache.as_ref().lock().unwrap();
673 let _ = c.insert(
674 "a",
675 ArcWrapper::new(
676 Arc::new(Test { a: 1024 }),
677 Arc::new(AtomicBool::new(true)),
678 None,
679 ),
680 );
681 }
682 println!("insert b, a should be ejected");
683 {
684 let mut c = cache.as_ref().lock().unwrap();
685 let _ = c.insert(
686 "b",
687 ArcWrapper::new(
688 Arc::new(Test { a: 1200 }),
689 Arc::new(AtomicBool::new(true)),
690 None,
691 ),
692 );
693 }
694 let b = {
695 let mut c = cache.as_ref().lock().unwrap();
696 c.get("b").cloned()
697 };
698 println!("insert c, b should not be ejected");
699 {
700 let mut c = cache.as_ref().lock().unwrap();
701 let _ = c.insert(
702 "c",
703 ArcWrapper::new(
704 Arc::new(Test { a: 1200 }),
705 Arc::new(AtomicBool::new(true)),
706 None,
707 ),
708 );
709 }
710 println!("user b: {}", b.as_ref().unwrap().a);
711 println!("test over, enject all");
712 }
713
714 #[test]
715 fn test_cache_object_serialize() {
716 for (kind, size) in [(HashKind::Sha1, 1024usize), (HashKind::Sha256, 2048usize)] {
717 let _guard = set_hash_kind_for_test(kind);
718 let a = make_obj(size);
719 let s = rkyv::to_bytes::<RkyvError>(&CacheObjectOnDiskRef::from(&a)).unwrap();
720 let b: CacheObject = rkyv::from_bytes::<CacheObjectOnDisk, RkyvError>(&s)
721 .unwrap()
722 .into();
723 assert_eq!(a.info, b.info);
724 assert_eq!(a.data_decompressed, b.data_decompressed);
725 assert_eq!(a.offset, b.offset);
726 assert!(b.mem_recorder.is_none());
727 }
728 }
729
730 #[test]
731 fn test_write_bytes_atomically_creates_file_when_missing() {
732 let dir = tempdir().unwrap();
733 let path = dir.path().join("object");
734
735 write_bytes_atomically(&path, b"fresh").unwrap();
736
737 assert_eq!(fs::read(&path).unwrap(), b"fresh");
738 }
739
740 #[test]
741 fn test_write_bytes_atomically_returns_when_target_exists() {
742 let dir = tempdir().unwrap();
743 let path = dir.path().join("object");
744
745 fs::write(&path, b"existing").unwrap();
746 write_bytes_atomically(&path, b"new-data").unwrap();
747
748 assert_eq!(fs::read(&path).unwrap(), b"existing");
749 }
750
751 #[test]
752 fn test_cache_object_file_roundtrip() {
753 let dir = tempdir().unwrap();
754 let path = dir.path().join("object");
755 let a = make_obj(1024);
756
757 a.f_save(&path).unwrap();
758 let b = CacheObject::f_load(&path).unwrap();
759
760 assert_eq!(a.info, b.info);
761 assert_eq!(a.data_decompressed, b.data_decompressed);
762 assert_eq!(a.offset, b.offset);
763 assert!(b.mem_recorder.is_none());
764 }
765
766 #[test]
767 fn test_arc_wrapper_drop_store() {
768 let mut path = PathBuf::from(".cache_temp/test_arc_wrapper_drop_store");
769 fs::create_dir_all(&path).unwrap();
770 path.push("test_obj");
771 let mut a = ArcWrapper::new(Arc::new(1024), Arc::new(AtomicBool::new(false)), None);
772 a.set_store_path(path.clone());
773 drop(a);
774
775 assert!(path.exists());
776 path.pop();
777 fs::remove_dir_all(&path).unwrap();
778 let _ = fs::remove_dir(".cache_temp");
780 }
781
782 #[test]
783 fn test_arc_wrapper_with_lru() {
785 let mut cache = LruCache::new(1500);
786 let path = PathBuf::from(".cache_temp/test_arc_wrapper_with_lru");
787 let _ = fs::remove_dir_all(&path);
788 fs::create_dir_all(&path).unwrap();
789 let shared_flag = Arc::new(AtomicBool::new(false));
790
791 let a_path = path.join("a");
793 {
794 let mut a = ArcWrapper::new(Arc::new(Test { a: 1024 }), shared_flag.clone(), None);
795 a.set_store_path(a_path.clone());
796 let b = ArcWrapper::new(Arc::new(1024), shared_flag.clone(), None);
797 assert!(b.store_path.is_none());
798
799 println!("insert a with heap size: {:?}", a.heap_size());
800 let rt = cache.insert("a", a);
801 if let Err(e) = rt {
802 panic!("{}", format!("insert a failed: {:?}", e.to_string()));
803 }
804 println!("after insert a, cache used = {}", cache.current_size());
805 }
806 assert!(!a_path.exists());
807
808 let b_path = path.join("b");
809 {
811 let mut b = ArcWrapper::new(Arc::new(Test { a: 996 }), shared_flag.clone(), None);
812 b.set_store_path(b_path.clone());
813 let rt = cache.insert("b", b);
814 if let Err(e) = rt {
815 panic!("{}", format!("insert a failed: {:?}", e.to_string()));
816 }
817 println!("after insert b, cache used = {}", cache.current_size());
818 }
819 assert!(a_path.exists());
820 assert!(!b_path.exists());
821 shared_flag.store(true, Ordering::Release);
822 fs::remove_dir_all(path).unwrap();
823 let _ = fs::remove_dir(".cache_temp");
825 }
827}