use super::*;
use crate::test_metrics::{registry, value};
use std::{
future::{pending, poll_fn},
task::Poll,
};
#[tokio::test]
async fn records_each_started_request_before_any_result() {
let (metrics_registry, registry) = registry();
let cache = Cache {
inner: Arc::new(CacheInner {
key_hasher: ObjectKeyHasher::new().unwrap(),
config: Cache::builder()
.disk_capacity(4 << 20)
.memory_capacity(1024)
.resolve_config()
.unwrap(),
memory: MemoryCache::with_metrics(1024, MemoryMetrics::new(®istry)),
metrics: LookupMetrics::new(®istry),
pending_fetches: PendingFetches::default(),
memory_admission_filter: None,
}),
access_trace: None,
};
let history = cache.inner.memory.access_histories();
let key = "object";
let fetch_history = history.clone();
let result = cache
.get_or_fetch(key, move || async move {
assert_eq!(fetch_history.request_count(), 1);
Err::<Bytes, _>("source failed")
})
.await;
assert_eq!(result, Err(GetOrFetchError::Callback("source failed")));
let mut pending = Box::pin(cache.get_or_fetch(key, pending::<Result<Bytes, &str>>));
assert_eq!(
history.request_count(),
1,
"an unpolled future has not started a request"
);
assert!(poll_fn(|cx| Poll::Ready(pending.as_mut().poll(cx))).await.is_pending());
assert_eq!(
history.request_count(),
2,
"recorded while the request is still pending"
);
drop(pending);
assert_eq!(history.request_count(), 2, "cancellation does not erase demand");
let fetch_history = history.clone();
cache
.get_or_fetch(key, move || async move {
assert_eq!(fetch_history.request_count(), 3);
Ok::<_, &str>(Bytes::from_static(b"x"))
})
.await
.unwrap();
cache
.get_or_fetch(key, || async { Err::<Bytes, &str>("memory hit must not fetch") })
.await
.unwrap();
assert_eq!(history.request_count(), 4, "success paths do not double-count");
assert_eq!(
value(&metrics_registry, "feuer_lookup_total", &[("outcome", "memory_hit")]),
1.0
);
assert_eq!(
value(&metrics_registry, "feuer_lookup_bytes_total", &[("source", "memory")]),
1.0
);
assert!(history.decayed_request_count(&cache.hash_key(key)) > 3.0);
}