use std::{fmt::Debug, marker::PhantomData, rc::Rc};
use crate::{
Computed, Context, DomNode, Instant, JsJsonDeserialize, RequestResponse, Resource, ToComputed,
dev::SsrFetchRequest,
driver_module::api::{api_fetch, api_fetch_cache},
fetch::{
api_response::{ApiResponse, Payload},
cache_value::CacheValue,
},
get_driver,
struct_mut::ValueMut,
transaction,
};
use super::request_builder::{RequestBody, RequestBuilder};
type MapResponse<T> = Option<Result<T, String>>;
fn get_unique_id() -> u64 {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(1);
COUNTER.fetch_add(1, Ordering::Relaxed)
}
pub struct LazyCache<T: PartialEq + 'static> {
cache: Cache,
_type: PhantomData<Rc<T>>,
}
impl<T: PartialEq + 'static> Debug for LazyCache<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LazyCache")
.field("queued", &self.cache.queued)
.finish()
}
}
impl<T: PartialEq> Clone for LazyCache<T> {
fn clone(&self) -> Self {
LazyCache {
cache: self.cache.clone(),
_type: PhantomData,
}
}
}
impl<T: PartialEq> LazyCache<T> {
pub fn new(
request: RequestBuilder,
map_response: impl Fn(u32, RequestBody) -> MapResponse<T> + 'static,
) -> Self {
let map_response =
move |status, body| map_response(status, body).map(|value| value.map(Payload::new));
Self {
cache: Cache::new(request, Rc::new(map_response)),
_type: PhantomData,
}
}
}
impl<T: PartialEq> LazyCache<T> {
pub fn get(&self, context: &Context) -> Resource<Rc<T>> {
typed(self.cache.get(context))
}
pub fn forget(&self) {
self.cache.forget();
}
pub fn force_update(&self, with_loading: bool) {
self.cache.update(with_loading, true)
}
pub fn optimistically_set(&self, value: T) {
self.cache.set_ready(Payload::new(value));
}
pub fn optimistically_change(&self, modify: impl FnOnce(&mut T))
where
T: Clone,
{
if let Resource::Ready(current_value) = typed::<T>(self.cache.current()) {
let mut new_value = (*current_value).clone();
modify(&mut new_value);
self.cache.set_ready(Payload::new(new_value));
}
}
pub fn update(&self, with_loading: bool, force: bool) {
self.cache.update(with_loading, force)
}
pub fn refresh(&self) -> impl Future<Output = ()> {
self.cache.refresh()
}
}
fn typed<T: 'static>(resource: Resource<Payload>) -> Resource<Rc<T>> {
match resource {
Resource::Ready(payload) => match payload.downcast() {
Some(value) => Resource::Ready(value),
None => Resource::Error(wrong_type()),
},
Resource::Loading => Resource::Loading,
Resource::Error(message) => Resource::Error(message),
}
}
fn wrong_type() -> String {
"vertigo: LazyCache holds a value of another type".to_string()
}
#[derive(Clone)]
struct Cache {
id: u64,
value: CacheValue,
queued: Rc<ValueMut<bool>>,
request: Rc<RequestBuilder>,
map_response: Rc<dyn Fn(u32, RequestBody) -> MapResponse<Payload>>,
}
impl Cache {
fn new(
request: RequestBuilder,
map_response: Rc<dyn Fn(u32, RequestBody) -> MapResponse<Payload>>,
) -> Self {
let init_value = match cached_response(&request) {
Some((response, expiry)) => {
ApiResponse::new(into_resource(response.into(map_response.as_ref())), expiry)
}
None => ApiResponse::Uninitialized,
};
Self {
id: get_unique_id(),
value: CacheValue::new(init_value, request.get_bearer_auth()),
queued: Rc::new(ValueMut::new(false)),
request: Rc::new(request),
map_response,
}
}
fn get(&self, context: &Context) -> Resource<Payload> {
let api_response = self.value.get(context);
if !self.queued.get() && api_response.needs_update() {
self.update(false, false);
}
api_response.get_value()
}
fn current(&self) -> Resource<Payload> {
transaction(|context| self.value.get(context)).get_value()
}
fn forget(&self) {
self.value.set(ApiResponse::Uninitialized);
}
fn set_ready(&self, value: Payload) {
self.value
.set(ApiResponse::new(Resource::Ready(value), None));
}
fn update(&self, with_loading: bool, force: bool) {
if self.queued.get() {
return;
}
self.queued.set(true);
let self_clone = self.clone();
get_driver().spawn(async move {
if !self_clone.queued.get() {
log::error!("force_update_spawn: queued.get() in spawn -> expected false");
return;
}
let api_response = transaction(|context| self_clone.value.get(context));
if force || api_response.needs_update() {
self_clone.fetch(with_loading).await;
}
self_clone.queued.set(false);
});
}
async fn refresh(&self) {
let locked = !self.queued.get();
if locked {
self.queued.set(true);
}
self.fetch(false).await;
if locked {
self.queued.set(false);
}
}
async fn fetch(&self, with_loading: bool) {
if with_loading {
self.value.set(ApiResponse::new_loading());
}
let (response, expiry) = fetch_response(&self.request).await;
let new_value = into_resource(response.into(self.map_response.as_ref()));
self.value.set(ApiResponse::new(new_value, expiry));
}
}
fn cached_response(request: &RequestBuilder) -> Option<(RequestResponse, Option<Instant>)> {
let ssr_request = as_sent(request);
let response = api_fetch_cache().get_response(&ssr_request)?;
Some((RequestResponse::new(ssr_request, response), expiry(request)))
}
async fn fetch_response(request: &RequestBuilder) -> (RequestResponse, Option<Instant>) {
let ssr_request = as_sent(request);
let result = api_fetch().fetch(ssr_request.clone()).await;
(RequestResponse::new(ssr_request, result), expiry(request))
}
fn as_sent(request: &RequestBuilder) -> SsrFetchRequest {
transaction(|context| request.clone().to_request_context(context))
}
fn expiry(request: &RequestBuilder) -> Option<Instant> {
request
.get_ttl()
.map(|ttl| get_driver().now().add_duration(ttl))
}
fn into_resource(value: Result<Payload, String>) -> Resource<Payload> {
match value {
Ok(value) => Resource::Ready(value),
Err(message) => Resource::Error(message),
}
}
impl<T: Clone + PartialEq> ToComputed<Resource<Rc<T>>> for LazyCache<T> {
fn to_computed(&self) -> Computed<Resource<Rc<T>>> {
Computed::from({
let state = self.clone();
move |context| state.get(context)
})
}
}
impl<T: Clone + PartialEq> LazyCache<T> {
pub fn to_computed(&self) -> Computed<Resource<Rc<T>>> {
<Self as ToComputed<Resource<Rc<T>>>>::to_computed(self)
}
}
impl<T: PartialEq> PartialEq for LazyCache<T> {
fn eq(&self, other: &Self) -> bool {
self.cache.id == other.cache.id
}
}
impl<T: PartialEq + Clone> LazyCache<T> {
pub fn render(&self, render: impl Fn(Rc<T>) -> DomNode + 'static) -> DomNode {
crate::render::render_value(self.to_computed(), move |value| match value {
Resource::Ready(value) => render(value),
Resource::Loading => {
use crate as vertigo;
vertigo::dom! {
<div>
"Loading ..."
</div>
}
}
Resource::Error(error) => {
use crate as vertigo;
vertigo::dom! {
<div>
"error = "
{error}
</div>
}
}
})
}
}
impl<T: PartialEq + JsJsonDeserialize> LazyCache<T> {
pub fn new_resource(api: &str, path: &str, ttl: u64) -> Self {
let url = [api, path].concat();
LazyCache::new(
get_driver().request_get(url).ttl_seconds(ttl),
|status, body| {
if status == 200 {
Some(body.into::<T>())
} else {
None
}
},
)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dev::{SsrFetchResponse, SsrFetchResponseContent};
use crate::driver_module::api::api_timers;
use crate::{JsJson, Value};
#[tokio::test]
async fn test_lazy_cache_optimistically_set() {
let cache = RequestBuilder::get("https://test.com/api").lazy_cache(|status, body| {
if status == 200 {
Some(body.into::<String>())
} else {
None
}
});
transaction(|context| {
assert_eq!(cache.get(context), Resource::Loading);
});
cache.optimistically_set("optimistic".to_string());
transaction(|context| {
assert_eq!(
cache.get(context),
Resource::Ready(Rc::new("optimistic".to_string()))
);
});
tokio::task::yield_now().await;
transaction(|context| {
assert_eq!(
cache.get(context),
Resource::Ready(Rc::new("optimistic".to_string()))
);
});
}
#[tokio::test]
async fn test_lazy_cache_optimistically_change() {
let cache = RequestBuilder::get("https://test.com/api").lazy_cache(|status, body| {
if status == 200 {
Some(body.into::<Vec<String>>())
} else {
None
}
});
transaction(|context| {
assert_eq!(cache.get(context), Resource::Loading);
});
cache.optimistically_set(vec!["first".to_string()]);
transaction(|context| {
assert_eq!(
cache.get(context),
Resource::Ready(Rc::new(vec!["first".to_string()]))
);
});
cache.optimistically_change(|data| {
data.push("second".to_string());
});
transaction(|context| {
assert_eq!(
cache.get(context),
Resource::Ready(Rc::new(vec!["first".to_string(), "second".to_string()]))
);
});
}
#[tokio::test]
async fn test_lazy_cache_initial_state() {
let cache = RequestBuilder::get("https://test.com/api").lazy_cache(|status, body| {
if status == 200 {
Some(body.into::<String>())
} else {
None
}
});
transaction(|context| {
let result = cache.get(context);
assert_eq!(result, Resource::Loading);
});
}
#[tokio::test]
async fn test_lazy_cache_starts_with_ssr_response_in_first_render_only() {
use crate::{driver_module::api::ssr_fetched, exports::in_first_render};
const URL: &str = "https://test.com/api";
fn make_cache() -> LazyCache<String> {
RequestBuilder::get(URL).lazy_cache(|status, body| {
if status == 200 {
Some(body.into::<String>())
} else {
None
}
})
}
ssr_fetched(URL, 200, JsJson::String("from server".to_string()));
let created_in_first_render = in_first_render(make_cache);
transaction(|context| {
assert_eq!(
created_in_first_render.get(context),
Resource::Ready(Rc::new("from server".to_string()))
);
});
let after = make_cache();
transaction(|context| assert_eq!(after.get(context), Resource::Loading));
}
#[tokio::test]
async fn test_lazy_cache_with_bearer_token_starts_with_ssr_response() {
use crate::{driver_module::api::ssr_fetched_request, exports::in_first_render};
const URL: &str = "https://test.com/api/private";
ssr_fetched_request(
RequestBuilder::get(URL).to_request(Some("member".to_string())),
200,
JsJson::String("the member's".to_string()),
);
let member = in_first_render(|| {
RequestBuilder::get(URL)
.bearer_auth(Some("member".to_string()))
.lazy_cache(|status, body| (status == 200).then(|| body.into::<String>()))
});
transaction(|context| {
assert_eq!(
member.get(context),
Resource::Ready(Rc::new("the member's".to_string()))
);
});
}
#[tokio::test]
async fn test_lazy_cache_with_bearer_token_skips_ssr_response_of_a_guest() {
use crate::{driver_module::api::ssr_fetched, exports::in_first_render};
const URL: &str = "https://test.com/api/private";
ssr_fetched(URL, 200, JsJson::String("a guest's".to_string()));
let member = in_first_render(|| {
RequestBuilder::get(URL)
.bearer_auth(Some("member".to_string()))
.lazy_cache(|status, body| (status == 200).then(|| body.into::<String>()))
});
transaction(|context| assert_eq!(member.get(context), Resource::Loading));
}
#[tokio::test]
async fn test_lazy_cache_refresh_waits_for_the_new_value() {
let calls = Rc::new(std::cell::Cell::new(0));
api_fetch().set_mock_handler({
let calls = calls.clone();
move |_request| {
calls.set(calls.get() + 1);
SsrFetchResponse::Ok {
status: 200,
response: SsrFetchResponseContent::Json(JsJson::String(format!(
"response {}",
calls.get()
))),
}
}
});
let cache = RequestBuilder::get("https://test.com/api")
.lazy_cache(|status, body| (status == 200).then(|| body.into::<String>()));
cache.optimistically_set("old".to_string());
for expected in ["response 1", "response 2"] {
cache.refresh().await;
transaction(|context| {
assert_eq!(
cache.get(context),
Resource::Ready(Rc::new(expected.to_string()))
);
});
}
assert_eq!(calls.get(), 2);
}
#[tokio::test]
async fn test_lazy_cache_refresh_in_a_transaction_reads_the_new_value() {
use std::task::{Context as TaskContext, Poll, Waker};
api_fetch().set_mock_handler(|_request| SsrFetchResponse::Ok {
status: 200,
response: SsrFetchResponseContent::Json(JsJson::String("new".to_string())),
});
let cache = RequestBuilder::get("https://test.com/api")
.lazy_cache(|status, body| (status == 200).then(|| body.into::<String>()));
cache.optimistically_set("old".to_string());
transaction(|context| cache.get(context));
let mut task = std::pin::pin!(async {
cache.refresh().await;
transaction(|context| cache.get(context))
});
let read = transaction(|_| {
task.as_mut()
.poll(&mut TaskContext::from_waker(Waker::noop()))
});
assert_eq!(
read,
Poll::Ready(Resource::Ready(Rc::new("new".to_string())))
);
}
#[tokio::test]
async fn test_lazy_cache_changes_in_one_transaction_build_on_each_other() {
let cache = RequestBuilder::get("https://test.com/api")
.lazy_cache(|status, body| (status == 200).then(|| body.into::<Vec<String>>()));
cache.optimistically_set(Vec::new());
transaction(|context| cache.get(context));
transaction(|_| {
cache.optimistically_change(|list| list.push("first".to_string()));
cache.optimistically_change(|list| list.push("second".to_string()));
});
transaction(|context| {
assert_eq!(
cache.get(context),
Resource::Ready(Rc::new(vec!["first".to_string(), "second".to_string()]))
);
});
}
#[tokio::test]
async fn test_lazy_cache_to_computed() {
let cache = RequestBuilder::get("https://test.com/api").lazy_cache(|status, body| {
if status == 200 {
Some(body.into::<String>())
} else {
None
}
});
let computed = cache.to_computed();
transaction(|context| {
let result = computed.get(context);
assert_eq!(result, Resource::Loading);
});
}
#[tokio::test]
async fn test_lazy_cache_token_revalidation() {
let local = tokio::task::LocalSet::new();
local
.run_until(async {
api_timers().set_mock_handler(|duration, callback_id, _kind| {
if duration == 0 {
tokio::task::spawn_local(async move {
api_timers().callback_timeout(callback_id);
});
}
});
let token = Value::new(Some("token1".to_string()));
let cache = RequestBuilder::get("https://test.com/api")
.bearer_auth(token.to_computed())
.lazy_cache(|status, body| {
if status == 200 {
Some(body.into::<String>())
} else {
None
}
});
let api = api_fetch();
let call_count = Rc::new(crate::dev::ValueMut::new(0));
{
let call_count = call_count.clone();
api.set_mock_handler(move |request| {
call_count.change(|val| *val += 1);
let auth = request
.headers
.get("Authorization")
.cloned()
.unwrap_or_default();
SsrFetchResponse::Ok {
status: 200,
response: SsrFetchResponseContent::Json(JsJson::String(format!(
"response for {}",
auth
))),
}
});
}
let _drop = cache.to_computed().subscribe(|_| {});
transaction(|context| {
let res = cache.get(context);
assert_eq!(res, Resource::Loading);
});
tokio::task::yield_now().await;
transaction(|context| {
let res = cache.get(context);
if let Resource::Ready(val) = res {
assert_eq!(val.as_str(), "response for Bearer token1");
} else {
panic!("Expected Ready, got {:?}", res);
}
});
assert_eq!(call_count.get(), 1);
transaction(|_| {
token.set(Some("token2".to_string()));
});
tokio::task::yield_now().await;
tokio::task::yield_now().await;
transaction(|context| {
let res = cache.get(context);
if let Resource::Ready(val) = res {
assert_eq!(val.as_str(), "response for Bearer token2");
} else {
panic!("Expected Ready after token change, got {:?}", res);
}
});
assert_eq!(call_count.get(), 2);
})
.await;
}
#[tokio::test]
async fn test_lazy_cache_set_same_computed_token() {
let local = tokio::task::LocalSet::new();
local
.run_until(async {
api_timers().set_mock_handler(|duration, callback_id, _kind| {
if duration == 0 {
tokio::task::spawn_local(async move {
api_timers().callback_timeout(callback_id);
});
}
});
let token_val = Value::new(Some("token1".to_string()));
let token_computed = token_val.to_computed();
let rb =
RequestBuilder::get("https://test.com/api").bearer_auth(token_computed.clone());
let call_count = Rc::new(crate::dev::ValueMut::new(0));
{
let call_count = call_count.clone();
api_fetch().set_mock_handler(move |request| {
call_count.change(|val| *val += 1);
let auth = request
.headers
.get("Authorization")
.cloned()
.unwrap_or_default();
SsrFetchResponse::Ok {
status: 200,
response: SsrFetchResponseContent::Json(JsJson::String(format!(
"resp:{}",
auth
))),
}
});
}
let cache = rb.clone().lazy_cache(|status, body| {
if status == 200 {
Some(body.into::<String>())
} else {
None
}
});
let _drop = cache.to_computed().subscribe(|_| {});
tokio::task::yield_now().await;
tokio::task::yield_now().await;
transaction(|context| {
let res = cache.get(context);
if let Resource::Ready(val) = res {
assert_eq!(val.as_str(), "resp:Bearer token1");
} else {
panic!("Expected Ready, got {:?}", res);
}
});
assert_eq!(call_count.get(), 1);
let _ = rb.bearer_auth(token_computed.clone());
tokio::task::yield_now().await;
tokio::task::yield_now().await;
assert_eq!(call_count.get(), 1);
transaction(|_| {
token_val.set(Some("token2".to_string()));
});
tokio::task::yield_now().await;
tokio::task::yield_now().await;
transaction(|context| {
let res = cache.get(context);
if let Resource::Ready(val) = res {
assert_eq!(val.as_str(), "resp:Bearer token2");
} else {
panic!("Expected Ready after token change, got {:?}", res);
}
});
assert_eq!(call_count.get(), 2);
})
.await;
}
#[tokio::test]
async fn test_lazy_cache_left_page_does_not_react_when_the_address_is_written_first() {
use std::cell::{Cell, RefCell};
let local = tokio::task::LocalSet::new();
local
.run_until(async {
api_timers().set_mock_handler(|duration, callback_id, _kind| {
if duration == 0 {
tokio::task::spawn_local(async move {
api_timers().callback_timeout(callback_id);
});
}
});
let calls = Rc::new(Cell::new(0));
api_fetch().set_mock_handler({
let calls = calls.clone();
move |_request| {
calls.set(calls.get() + 1);
SsrFetchResponse::Ok {
status: 200,
response: SsrFetchResponseContent::Json(JsJson::String(
"fetched".to_string(),
)),
}
}
});
let cache = RequestBuilder::get("https://test.com/api")
.lazy_cache(|status, body| (status == 200).then(|| body.into::<String>()));
cache.optimistically_set("shown".to_string());
let route = Value::new(1u32);
let route_read = route
.to_computed()
.when_connect(|| crate::DropResource::new(|| {}));
let seen: Rc<RefCell<Vec<Resource<Rc<String>>>>> =
Rc::new(RefCell::new(Vec::new()));
let page: Rc<RefCell<Option<crate::DropResource>>> = Rc::new(RefCell::new(None));
let _router = route_read.subscribe({
let cache = cache.clone();
let seen = seen.clone();
let page = page.clone();
move |route| {
let new_page = (route == 1).then(|| {
let seen = seen.clone();
cache
.to_computed()
.subscribe(move |value| seen.borrow_mut().push(value))
});
let old = page.replace(new_page);
drop(old);
}
});
assert_eq!(
*seen.borrow(),
vec![Resource::Ready(Rc::new("shown".to_string()))]
);
seen.borrow_mut().clear();
transaction(|_| {
route.set(2);
cache.forget();
});
for _ in 0..5 {
tokio::task::yield_now().await;
}
assert_eq!(
*seen.borrow(),
Vec::<Resource<Rc<String>>>::new(),
"the page left reacted"
);
assert_eq!(calls.get(), 0, "fetched for the page left");
})
.await;
}
}