about summary refs log tree commit diff
path: root/splorm/src/connector/mod.rs
blob: 9322279db8f720230d0423c5558e2c70b8888de1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//! 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<T: Clone> {
	item: Mutex<Option<T>>,
	time: Mutex<OffsetDateTime>,
	timeout: Duration,
}

impl<T: Clone> CacheItem<T> {
	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<T> {
		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()
	}
}