1use crate::errors::{Git2DBError, Git2DBResult};
6use git2::Repository;
7use std::path::{Path, PathBuf};
8use std::sync::Arc;
9use std::time::{Duration, Instant};
10
11#[derive(Debug, Clone)]
16pub struct RepositoryCache {
17 path: PathBuf,
18 created_at: Instant,
19 access_count: Arc<parking_lot::Mutex<u64>>,
20}
21
22impl RepositoryCache {
23 pub(crate) fn new(_repository: Repository, path: PathBuf) -> Self {
24 Self {
25 path,
26 created_at: Instant::now(),
27 access_count: Arc::new(parking_lot::Mutex::new(1)),
28 }
29 }
30
31 pub fn open(&self) -> Git2DBResult<Repository> {
33 let mut count = self.access_count.lock();
34 *count += 1;
35
36 Repository::open(&self.path).map_err(|e| {
37 Git2DBError::repository(&self.path, format!("Failed to open repository: {e}"))
38 })
39 }
40
41 pub fn read(&self) -> Git2DBResult<Repository> {
43 self.open()
44 }
45
46 pub fn write(&self) -> Git2DBResult<Repository> {
48 self.open()
49 }
50
51 pub fn path(&self) -> &Path {
53 &self.path
54 }
55
56 pub fn created_at(&self) -> Instant {
58 self.created_at
59 }
60
61 pub fn access_count(&self) -> u64 {
63 *self.access_count.lock()
64 }
65
66 pub fn is_expired(&self, ttl: Duration) -> bool {
68 self.created_at.elapsed() > ttl
69 }
70}
71
72#[derive(Debug, Clone)]
74pub struct CacheStats {
75 pub total_entries: usize,
76 pub total_accesses: u64,
77 pub oldest_created: Instant,
78 pub newest_created: Instant,
79 pub oldest_accessed: Instant,
80 pub newest_accessed: Instant,
81}
82
83impl CacheStats {
84 pub fn oldest_entry_age(&self) -> Duration {
86 self.oldest_created.elapsed()
87 }
88
89 pub fn newest_entry_age(&self) -> Duration {
91 self.newest_created.elapsed()
92 }
93
94 pub fn oldest_access_age(&self) -> Duration {
96 self.oldest_accessed.elapsed()
97 }
98
99 pub fn average_accesses_per_entry(&self) -> f64 {
101 if self.total_entries == 0 {
102 0.0
103 } else {
104 self.total_accesses as f64 / self.total_entries as f64
105 }
106 }
107}