Skip to main content

git_internal/internal/pack/
cache_object.rs

1//! Cache object representation plus disk-backed serialization helpers used by the pack decoder to
2//! bound memory while still serving delta reconstruction quickly.
3
4use 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
39// static CACHE_OBJS_MEM_SIZE: AtomicUsize = AtomicUsize::new(0);
40
41/// file load&store trait
42pub 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    /// load object from file
74    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/// Represents the metadata of a cache object, indicating whether it is a delta or not.
91#[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    /// The object is one of the four basic types:
104    /// [`ObjectType::Blob`], [`ObjectType::Tree`], [`ObjectType::Commit`], or [`ObjectType::Tag`].
105    /// The metadata contains the [`ObjectType`] and the [`ObjectHash`] hash of the object.
106    BaseObject(ObjectType, ObjectHash),
107    /// The object is an offset delta with a specified offset delta [`usize`],
108    /// and the size of the expanded object (previously `delta_final_size`).
109    OffsetDelta(usize, usize),
110    /// Similar to [`OffsetDelta`], but delta algorithm is `zstd`.
111    OffsetZstdelta(usize, usize),
112    /// The object is a hash delta with a specified [`ObjectHash`] hash,
113    /// and the size of the expanded object (previously `delta_final_size`).
114    HashDelta(ObjectHash, usize),
115}
116
117impl CacheObjectInfo {
118    /// Get the [`ObjectType`] of the object.
119    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/// Represents a cached object in memory, which may be a delta or a base object.
130#[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>>, // record mem-size of all CacheObjects of a Pack
137    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
220// ! used by lru_mem to calculate the size of the object, limit the memory usage.
221// ! the implementation of HeapSize is not accurate, only calculate the size of the data_decompress
222// Note that: mem_size == value_size + heap_size, and we only need to impl HeapSize because value_size is known
223impl HeapSize for CacheObject {
224    /// If a [`CacheObject`] is [`ObjectType::HashDelta`] or [`ObjectType::OffsetDelta`],
225    /// it will expand to another [`CacheObject`] of other types. To prevent potential OOM,
226    /// we record the size of the expanded object as well as that of the object itself.
227    ///
228    /// Base objects, *i.e.*, [`ObjectType::Blob`], [`ObjectType::Tree`], [`ObjectType::Commit`],
229    /// and [`ObjectType::Tag`], will not be expanded, so the heap-size of the object is the same
230    /// as the size of the data.
231    ///
232    /// See [Comment in PR #755](https://github.com/web3infra-foundation/mega/pull/755#issuecomment-2543100481) for more details.
233    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                // To those who are concerned about why these two values are added,
240                // let's consider the lifetime of two `CacheObject`s, say `delta_obj`
241                // and `final_obj` in the function `Pack::rebuild_delta`.
242                //
243                // `delta_obj` is dropped only after `Pack::rebuild_delta` returns,
244                // but the space for `final_obj` is allocated in that function.
245                //
246                // Therefore, during the execution of `Pack::rebuild_delta`, both `delta_obj`
247                // and `final_obj` coexist. The maximum memory usage is the sum of the memory
248                // usage of `delta_obj` and `final_obj`.
249                self.data_decompressed.heap_size() + delta_final_size
250            }
251        }
252    }
253}
254
255impl Drop for CacheObject {
256    // Check: the heap-size subtracted when Drop is equal to the heap-size recorded
257    // (cannot change the heap-size during life cycle)
258    fn drop(&mut self) {
259        // (&*self).heap_size() != self.heap_size()
260        if let Some(mem_recorder) = &self.mem_recorder {
261            mem_recorder.fetch_sub((*self).mem_size(), Ordering::Release);
262        }
263    }
264}
265
266/// Heap-size recorder for a class(struct)
267/// <br> You should use a static Var to record mem-size
268/// and record mem-size after construction & minus it in `drop()`
269/// <br> So, variable-size fields in object should NOT be modified to keep heap-size stable.
270/// <br> Or, you can record the initial mem-size in this object
271/// <br> Or, update it (not impl)
272pub trait MemSizeRecorder: MemSize {
273    fn record_mem_size(&self);
274    fn set_mem_recorder(&mut self, mem_size: Arc<AtomicUsize>);
275    // fn get_mem_size() -> usize;
276}
277
278impl MemSizeRecorder for CacheObject {
279    /// record the mem-size of this `CacheObj` in a `static` `var`
280    /// <br> since that, DO NOT modify `CacheObj` after recording
281    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    // fn get_mem_size() -> usize {
292    //     CACHE_OBJS_MEM_SIZE.load(Ordering::Acquire)
293    // }
294}
295
296impl CacheObject {
297    /// Create a new base CacheObject whose ID is computed with an explicit repository
298    /// `kind` (never the thread-local); fails closed for delta types.
299    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    /// Create a new CacheObject which is neither [`ObjectType::OffsetDelta`] nor [`ObjectType::HashDelta`].
319    ///
320    /// Uses the thread-local [`HashKind`]; see [`CacheObject::new_for_undeltified_with_kind`].
321    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    /// Get the [`ObjectType`] of the object.
340    pub fn object_type(&self) -> ObjectType {
341        self.info.object_type()
342    }
343
344    /// Get the [`ObjectHash`] hash of the object.
345    ///
346    /// If the object is a delta object, return [`None`].
347    pub fn base_object_hash(&self) -> Option<ObjectHash> {
348        match &self.info {
349            CacheObjectInfo::BaseObject(_, hash) => Some(*hash),
350            _ => None,
351        }
352    }
353
354    /// Get the offset delta of the object.
355    ///
356    /// If the object is not an offset delta, return [`None`].
357    pub fn offset_delta(&self) -> Option<usize> {
358        match &self.info {
359            CacheObjectInfo::OffsetDelta(offset, _) => Some(*offset),
360            _ => None,
361        }
362    }
363
364    /// Get the hash delta of the object.
365    ///
366    /// If the object is not a hash delta, return [`None`].
367    pub fn hash_delta(&self) -> Option<ObjectHash> {
368        match &self.info {
369            CacheObjectInfo::HashDelta(hash, _) => Some(*hash),
370            _ => None,
371        }
372    }
373
374    /// transform the CacheObject to Entry
375    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    /// transform the CacheObject to MetaAttached<Entry, EntryMeta>
390    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_id:Some(pack_id),
401                    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    /// transform the CacheObject to MetaAttached<Entry, EntryMeta> without cloning object data
416    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
447/// trait alias for simple use
448pub trait ArcWrapperBounds: HeapSize + FileLoadStore + Send + Sync + 'static {}
449// You must impl `Alias Trait` for all the `T` satisfying Constraints
450// Or, `T` will not satisfy `Alias Trait` even if it satisfies the Original traits
451impl<T: HeapSize + FileLoadStore + Send + Sync + 'static> ArcWrapperBounds for T {}
452
453/// Implementing encapsulation of Arc to enable third-party Trait HeapSize implementation for the Arc type
454/// Because of use Arc in LruCache, the LruCache is not clear whether a pointer will drop the referenced
455/// content when it is ejected from the cache, the actual memory usage is not accurate
456pub 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>, // path to store when drop
461}
462impl<T: ArcWrapperBounds> ArcWrapper<T> {
463    /// Create a new ArcWrapper
464    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    /// Sets the file path where this object will be persisted when evicted from cache.
473    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    /// clone won't clone the store_path
486    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    // `drop` will be called in `lru_cache.insert()` when cache full & eject the LRU
504    // `lru_cache.insert()` is protected by Mutex
505    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                    // block entire process, wait for IO, Control Memory
515                    // queue size will influence the Memory usage
516                    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    /// Helper to build a base CacheObject with the given size.
549    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 that the memory size recording works correctly for CacheObject.
562    #[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 that the heap size of CacheObject and ArcWrapper are the same.
578    #[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 that the LRU cache correctly ejects the least recently used object when capacity is exceeded.
591    #[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"); // whatever different hash
612            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                    // expected
631                } 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    /// test that the Drop trait is called when an object is ejected from the LRU cache
650    #[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        // Try to remove parent .cache_temp directory if it's empty
779        let _ = fs::remove_dir(".cache_temp");
780    }
781
782    #[test]
783    /// test warpper can't correctly store the data when lru eject it
784    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        // insert a, a not ejected
792        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        // insert b, a should be ejected
810        {
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        // Try to remove parent .cache_temp directory if it's empty
824        let _ = fs::remove_dir(".cache_temp");
825        // should pass even b's path not exists
826    }
827}