use crate::cache::{Cache, CacheKey, CacheState, CacheValue};
use crate::transport::{BoxFuture, ResourceHold, Transport};
use crate::types::ResourceId;
use futures_core::Stream;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use tokio_stream::wrappers::WatchStream;
pub(crate) trait Source<T>: Send + Sync {
fn fresh(&self) -> BoxFuture<'static, Result<T, Arc<dyn std::error::Error + Send + Sync>>>;
fn watch(&self) -> Observed<T>;
fn invalidate(&self);
}
pub struct Cached<T> {
source: Box<dyn Source<T>>,
}
impl<T> Cached<T> {
pub(crate) fn of(source: impl Source<T> + 'static) -> Cached<T> {
Cached {
source: Box::new(source),
}
}
pub async fn fresh(&self) -> Result<T, Arc<dyn std::error::Error + Send + Sync>> {
self.source.fresh().await
}
pub fn watch(&self) -> Observed<T> {
self.source.watch()
}
pub fn invalidate(&self) {
self.source.invalidate();
}
}
pub struct Observed<T> {
states: Pin<Box<dyn Stream<Item = CacheState<T>> + Send>>,
_scope: Option<ResourceHold>,
}
impl<T> Observed<T> {
pub(crate) fn new(
states: impl Stream<Item = CacheState<T>> + Send + 'static,
scope: Option<ResourceHold>,
) -> Observed<T> {
Observed {
states: Box::pin(states),
_scope: scope,
}
}
pub async fn next(&mut self) -> Option<CacheState<T>> {
std::future::poll_fn(|cx| self.states.as_mut().poll_next(cx)).await
}
}
impl<T> Stream for Observed<T> {
type Item = CacheState<T>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.states.as_mut().poll_next(cx)
}
}
pub(crate) struct Keyed<K: CacheKey, V: CacheValue, T> {
pub cache: Cache<K, V>,
pub key: K,
pub view: fn(V) -> T,
pub scope: Option<(Arc<dyn Transport>, ResourceId)>,
}
struct Viewed<V, T> {
states: WatchStream<CacheState<V>>,
view: fn(V) -> T,
}
impl<V: CacheValue, T> Stream for Viewed<V, T> {
type Item = CacheState<T>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let view = self.view;
Pin::new(&mut self.states)
.poll_next(cx)
.map(|state| state.map(|state| state.map(view)))
}
}
impl<K, V, T> Source<T> for Keyed<K, V, T>
where
K: CacheKey,
V: CacheValue,
T: 'static,
{
fn fresh(&self) -> BoxFuture<'static, Result<T, Arc<dyn std::error::Error + Send + Sync>>> {
let fetching = self.cache.fetch(&self.key);
let view = self.view;
Box::pin(async move { fetching.await.map(view) })
}
fn watch(&self) -> Observed<T> {
let scope = self
.scope
.as_ref()
.map(|(transport, resource_id)| transport.subscribe_to_resource(resource_id));
Observed::new(
Viewed {
states: self.cache.observe(&self.key),
view: self.view,
},
scope,
)
}
fn invalidate(&self) {
self.cache.invalidate(&self.key);
}
}