//! Connectors to external things //! //! External services or APIs have structres here that allow access. //! //! All connector structs should have a suffic of `Connector`. mod gatherer; use std::ops::DerefMut; #[doc(hidden)] pub use gatherer::{GathererCommand, GathererConnector, GathererData}; use timeparse::{Duration, OffsetDateTime}; use tokio::sync::Mutex; /// cache management structure struct CacheItem { item: Mutex>, time: Mutex, timeout: Duration, } impl CacheItem { pub fn new(timeout: Duration) -> Self { Self { item: Mutex::new(None), time: Mutex::new(timeparse::now_utc()), timeout, } } pub fn new_with_item(item: T, timeout: Duration) -> Self { Self { item: Mutex::new(Some(item)), time: Mutex::new(timeparse::now_utc()), timeout, } } pub async fn get(&self) -> Option { if self.duration_since_cache().await > self.timeout { let _ = self.item.lock().await.take(); None } else { let item = self.item.lock().await.clone(); item } } pub async fn store(&self, item: T) { let mut item_lock = self.item.lock().await; let mut time_lock = self.time.lock().await; *item_lock.deref_mut() = Some(item); *time_lock.deref_mut() = timeparse::now_utc(); } pub async fn duration_since_cache(&self) -> Duration { let time_lock = self.time.lock().await; *time_lock - timeparse::now_utc() } }