use crate::ssh::SshConfig;
use std::time::{Duration, Instant, SystemTime};
#[derive(Debug, Clone)]
#[cfg_attr(test, allow(dead_code))]
pub(crate) struct CacheEntry {
pub(super) config: SshConfig,
pub(super) cached_at: Instant,
pub(super) file_mtime: SystemTime,
pub(super) access_count: u64,
pub(super) last_accessed: Instant,
}
impl CacheEntry {
pub fn new(config: SshConfig, file_mtime: SystemTime) -> Self {
let now = Instant::now();
Self {
config,
cached_at: now,
file_mtime,
access_count: 0,
last_accessed: now,
}
}
pub fn is_expired(&self, ttl: Duration) -> bool {
self.cached_at.elapsed() > ttl
}
pub fn is_stale(&self, current_mtime: SystemTime) -> bool {
self.file_mtime != current_mtime
}
pub fn access(&mut self) -> &SshConfig {
self.access_count += 1;
self.last_accessed = Instant::now();
&self.config
}
pub fn age(&self) -> Duration {
self.cached_at.elapsed()
}
pub fn time_since_last_access(&self) -> Duration {
self.last_accessed.elapsed()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_cache_entry_expiration() {
let config = SshConfig::new();
let mtime = SystemTime::now();
let mut entry = CacheEntry::new(config, mtime);
assert!(!entry.is_expired(Duration::from_secs(300)));
entry.cached_at = Instant::now() - Duration::from_secs(400);
assert!(entry.is_expired(Duration::from_secs(300)));
}
#[test]
fn test_cache_entry_staleness() {
let config = SshConfig::new();
let old_mtime = SystemTime::UNIX_EPOCH;
let new_mtime = SystemTime::now();
let entry = CacheEntry::new(config, old_mtime);
assert!(!entry.is_stale(old_mtime));
assert!(entry.is_stale(new_mtime));
}
#[test]
fn test_cache_entry_access() {
let config = SshConfig::new();
let mtime = SystemTime::now();
let mut entry = CacheEntry::new(config, mtime);
assert_eq!(entry.access_count, 0);
let _ = entry.access();
assert_eq!(entry.access_count, 1);
let _ = entry.access();
assert_eq!(entry.access_count, 2);
}
}