use std::{
any::Any,
collections::HashMap,
fmt::Debug,
future::Future,
sync::{LazyLock, Mutex},
time::{Duration, Instant},
};
use futures::future::{FutureExt, Shared};
use super::options::BoxFuture;
struct Memoized {
future: Box<dyn Any + Send + Sync>,
scope: MemoScope,
made: Instant,
}
impl Memoized {
fn is_expired(&self) -> bool {
matches!(self.scope, MemoScope::For(ttl) if self.made.elapsed() >= ttl)
}
}
static MEMO: LazyLock<Mutex<HashMap<String, Memoized>>> = LazyLock::new(Mutex::default);
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum MemoScope {
#[default]
App,
Navigation,
For(Duration),
}
pub type MemoFuture<T> = Shared<BoxFuture<T>>;
pub fn memoize<T, Fut>(key: String, make: impl FnOnce() -> Fut) -> MemoFuture<T>
where
T: Clone + Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
memoize_in(key, MemoScope::App, make)
}
pub fn memoize_in<T, Fut>(
key: String,
scope: MemoScope,
make: impl FnOnce() -> Fut,
) -> MemoFuture<T>
where
T: Clone + Send + Sync + 'static,
Fut: Future<Output = T> + Send + 'static,
{
let mut memo = MEMO
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(future) = memo
.get(&key)
.filter(|cached| !cached.is_expired())
.and_then(|cached| cached.future.downcast_ref::<MemoFuture<T>>())
{
return future.clone();
}
let boxed: BoxFuture<T> = Box::pin(make());
let future = boxed.shared();
memo.insert(
key,
Memoized {
future: Box::new(future.clone()),
scope,
made: Instant::now(),
},
);
future
}
pub fn end_navigation() {
MEMO.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.retain(|_, cached| cached.scope != MemoScope::Navigation);
}
#[doc(hidden)]
pub fn key(path: &str, name: &str, arguments: &impl Debug) -> String {
format!("{path}::{name}{arguments:?}")
}
pub fn invalidate(prefix: &str) {
MEMO.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.retain(|key, _| !key.starts_with(prefix));
}
pub fn clear() {
MEMO.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
}