use std::collections::HashMap;
use std::fmt;
use std::sync::{Arc, PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard};
use std::time::Duration;
use serde_json::Value;
use tokio::time::Instant;
use crate::envelope::Envelope;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Bucket {
Network,
Eeros,
Devices,
Profiles,
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CacheKey {
Account,
Networks,
Network {
network_id: String,
},
Eeros {
network_id: String,
},
Devices {
network_id: String,
},
Device {
network_id: String,
device_id: String,
},
Profiles {
network_id: String,
},
Profile {
network_id: String,
profile_id: String,
},
}
impl CacheKey {
pub fn network(network_id: impl Into<String>) -> Self {
Self::Network {
network_id: network_id.into(),
}
}
pub fn eeros(network_id: impl Into<String>) -> Self {
Self::Eeros {
network_id: network_id.into(),
}
}
pub fn devices(network_id: impl Into<String>) -> Self {
Self::Devices {
network_id: network_id.into(),
}
}
pub fn device(network_id: impl Into<String>, device_id: impl Into<String>) -> Self {
Self::Device {
network_id: network_id.into(),
device_id: device_id.into(),
}
}
pub fn profiles(network_id: impl Into<String>) -> Self {
Self::Profiles {
network_id: network_id.into(),
}
}
pub fn profile(network_id: impl Into<String>, profile_id: impl Into<String>) -> Self {
Self::Profile {
network_id: network_id.into(),
profile_id: profile_id.into(),
}
}
fn network_id(&self) -> Option<&str> {
match self {
Self::Account | Self::Networks => None,
Self::Network { network_id }
| Self::Eeros { network_id }
| Self::Devices { network_id }
| Self::Device { network_id, .. }
| Self::Profiles { network_id }
| Self::Profile { network_id, .. } => Some(network_id),
}
}
fn is_in_bucket(&self, bucket: Bucket, network_id: &str) -> bool {
let same_kind = matches!(
(bucket, self),
(Bucket::Network, Self::Network { .. })
| (Bucket::Eeros, Self::Eeros { .. })
| (Bucket::Devices, Self::Devices { .. } | Self::Device { .. })
| (
Bucket::Profiles,
Self::Profiles { .. } | Self::Profile { .. }
)
);
same_kind && self.network_id() == Some(network_id)
}
}
impl fmt::Display for CacheKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Account => write!(f, "account"),
Self::Networks => write!(f, "networks"),
Self::Network { network_id } => write!(f, "network[{network_id}]"),
Self::Eeros { network_id } => write!(f, "eeros[{network_id}_eeros]"),
Self::Devices { network_id } => write!(f, "devices[{network_id}_devices]"),
Self::Device {
network_id,
device_id,
} => write!(f, "devices[{network_id}_{device_id}]"),
Self::Profiles { network_id } => write!(f, "profiles[{network_id}_profiles]"),
Self::Profile {
network_id,
profile_id,
} => write!(f, "profiles[{network_id}_{profile_id}]"),
}
}
}
struct Entry {
value: Envelope,
inserted_at: Instant,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct CacheGeneration(u64);
struct Inner {
entries: HashMap<CacheKey, Entry>,
generation: u64,
}
impl Inner {
fn bump_generation(&mut self) {
self.generation = self.generation.wrapping_add(1);
}
}
pub struct Cache {
ttl: Duration,
inner: Arc<RwLock<Inner>>,
}
impl Cache {
#[must_use]
pub fn new(ttl: Duration) -> Self {
Self {
ttl,
inner: Arc::new(RwLock::new(Inner {
entries: HashMap::new(),
generation: 0,
})),
}
}
fn read(&self) -> RwLockReadGuard<'_, Inner> {
self.inner.read().unwrap_or_else(PoisonError::into_inner)
}
fn write(&self) -> RwLockWriteGuard<'_, Inner> {
self.inner.write().unwrap_or_else(PoisonError::into_inner)
}
fn is_expired(&self, entry: &Entry) -> bool {
entry.inserted_at.elapsed() >= self.ttl
}
#[must_use]
pub fn get(&self, key: &CacheKey) -> Option<Envelope> {
if self.ttl.is_zero() {
self.write().entries.remove(key);
return None;
}
{
let inner = self.read();
let entry = inner.entries.get(key)?;
if !self.is_expired(entry) {
if is_falsy(&entry.value) {
return None;
}
return Some(entry.value.clone());
}
}
let mut inner = self.write();
if inner
.entries
.get(key)
.is_some_and(|entry| self.is_expired(entry))
{
inner.entries.remove(key);
}
None
}
pub fn put(&self, key: CacheKey, value: Envelope) {
let mut inner = self.write();
inner.entries.insert(
key,
Entry {
value,
inserted_at: Instant::now(),
},
);
}
#[must_use]
pub(crate) fn generation(&self) -> CacheGeneration {
CacheGeneration(self.read().generation)
}
pub(crate) fn put_if_current(
&self,
key: CacheKey,
value: Envelope,
generation: CacheGeneration,
) -> bool {
if self.ttl.is_zero() {
return false;
}
let mut inner = self.write();
if inner.generation != generation.0 {
return false;
}
inner.entries.insert(
key,
Entry {
value,
inserted_at: Instant::now(),
},
);
true
}
pub fn invalidate(&self, key: &CacheKey) {
let mut inner = self.write();
inner.bump_generation();
inner.entries.remove(key);
}
pub fn invalidate_bucket(&self, bucket: Bucket, network_id: &str) {
let mut inner = self.write();
inner.bump_generation();
inner
.entries
.retain(|key, _| !key.is_in_bucket(bucket, network_id));
}
pub fn clear(&self) {
let mut inner = self.write();
inner.bump_generation();
inner.entries.clear();
}
#[must_use]
pub fn len(&self) -> usize {
self.read().entries.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
}
impl Clone for Cache {
fn clone(&self) -> Self {
Self {
ttl: self.ttl,
inner: Arc::clone(&self.inner),
}
}
}
impl Default for Cache {
fn default() -> Self {
Self::new(crate::consts::DEFAULT_CACHE_TTL)
}
}
impl fmt::Debug for Cache {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let inner = self.read();
let mut keys: Vec<String> = inner.entries.keys().map(ToString::to_string).collect();
keys.sort_unstable();
f.debug_struct("Cache")
.field("ttl", &self.ttl)
.field("len", &inner.entries.len())
.field("keys", &keys)
.finish_non_exhaustive()
}
}
fn is_falsy(value: &Envelope) -> bool {
match value.as_value() {
Value::Null => true,
Value::Bool(b) => !b,
Value::Number(n) => is_zero(n),
Value::String(s) => s.is_empty(),
Value::Array(items) => items.is_empty(),
Value::Object(map) => map.is_empty(),
}
}
fn is_zero(n: &serde_json::Number) -> bool {
if let Some(i) = n.as_i64() {
return i == 0;
}
if let Some(u) = n.as_u64() {
return u == 0;
}
n.as_f64().is_some_and(|f| f.abs() < f64::EPSILON)
}
#[cfg(test)]
mod tests {
use super::{Bucket, Cache, CacheKey};
use crate::envelope::Envelope;
use serde_json::json;
use std::time::Duration;
fn envelope(body: serde_json::Value) -> Envelope {
Envelope::from_value(body)
}
fn non_empty() -> Envelope {
envelope(json!({"meta": {"code": 200}, "data": {"name": "Home"}}))
}
#[test]
fn new_cache_starts_empty() {
let cache = Cache::new(Duration::from_secs(60));
assert_eq!(cache.len(), 0);
assert!(cache.is_empty());
}
#[test]
fn miss_on_a_key_that_was_never_written() {
let cache = Cache::new(Duration::from_secs(60));
assert!(cache.get(&CacheKey::Account).is_none());
}
#[tokio::test]
async fn hit_before_expiry() {
tokio::time::pause();
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, non_empty());
assert_eq!(cache.get(&CacheKey::Account), Some(non_empty()));
}
#[tokio::test]
async fn miss_after_expiry() {
tokio::time::pause();
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, non_empty());
tokio::time::advance(Duration::from_secs(61)).await;
assert!(cache.get(&CacheKey::Account).is_none());
}
#[tokio::test]
async fn miss_exactly_at_the_ttl_boundary() {
tokio::time::pause();
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, non_empty());
tokio::time::advance(Duration::from_secs(60)).await;
assert!(cache.get(&CacheKey::Account).is_none());
}
#[tokio::test]
async fn hit_just_before_the_ttl_boundary() {
tokio::time::pause();
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, non_empty());
tokio::time::advance(Duration::from_millis(59_999)).await;
assert!(cache.get(&CacheKey::Account).is_some());
}
#[test]
fn each_falsy_shape_is_treated_as_a_miss() {
let falsy_shapes = [
("null", json!(null)),
("empty object", json!({})),
("empty array", json!([])),
("zero", json!(0)),
("empty string", json!("")),
("false", json!(false)),
];
for (label, shape) in falsy_shapes {
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, envelope(shape.clone()));
assert!(
cache.get(&CacheKey::Account).is_none(),
"{label} ({shape:?}) must not be served from cache"
);
}
}
#[test]
fn non_falsy_shapes_of_the_same_json_types_are_hits() {
let truthy_shapes = [
json!({"data": {"name": "Home"}}),
json!([{"url": "/2.2/networks/1"}]),
json!(1),
json!("non-empty"),
json!(true),
];
for shape in truthy_shapes {
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, envelope(shape.clone()));
assert!(
cache.get(&CacheKey::Account).is_some(),
"{shape:?} must be served from cache"
);
}
}
#[test]
fn put_overwrites_an_existing_valid_entry() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(
CacheKey::Account,
envelope(json!({"data": {"name": "old"}})),
);
cache.put(
CacheKey::Account,
envelope(json!({"data": {"name": "new"}})),
);
let cached = cache.get(&CacheKey::Account).expect("hit");
assert_eq!(cached.data()["name"], json!("new"));
}
#[test]
fn zero_ttl_disables_reads_but_not_writes() {
let cache = Cache::new(Duration::ZERO);
cache.put(CacheKey::Account, non_empty());
assert_eq!(cache.len(), 1, "the write must still have happened");
assert!(cache.get(&CacheKey::Account).is_none());
}
#[test]
fn zero_ttl_read_removes_the_entry_it_is_asked_for() {
let cache = Cache::new(Duration::ZERO);
cache.put(CacheKey::Account, non_empty());
cache.put(CacheKey::Networks, non_empty());
assert!(cache.get(&CacheKey::Account).is_none());
assert_eq!(cache.len(), 1, "only the key that was read is pruned");
assert!(cache.get(&CacheKey::Networks).is_none());
assert_eq!(cache.len(), 0);
}
#[test]
fn zero_ttl_guarded_store_keeps_nothing() {
let cache = Cache::new(Duration::ZERO);
let generation = cache.generation();
let stored = cache.put_if_current(CacheKey::Account, non_empty(), generation);
assert!(!stored);
assert_eq!(cache.len(), 0, "an entry no read could serve is not kept");
}
#[test]
fn zero_ttl_does_not_prune_by_advancing_the_invalidation_counter() {
let cache = Cache::new(Duration::ZERO);
let generation = cache.generation();
cache.put(CacheKey::Account, non_empty());
let _ = cache.get(&CacheKey::Account);
assert_eq!(cache.generation(), generation);
}
#[test]
fn every_key_shape_round_trips_independently() {
let cache = Cache::new(Duration::from_secs(60));
let keys = [
CacheKey::Account,
CacheKey::Networks,
CacheKey::network("nid"),
CacheKey::eeros("nid"),
CacheKey::devices("nid"),
CacheKey::device("nid", "did"),
CacheKey::profiles("nid"),
CacheKey::profile("nid", "pid"),
];
for (i, key) in keys.iter().enumerate() {
cache.put(key.clone(), envelope(json!({"data": {"i": i}})));
}
for (i, key) in keys.iter().enumerate() {
let cached = cache.get(key).unwrap_or_else(|| panic!("miss for {key}"));
assert_eq!(cached.data()["i"], json!(i), "wrong value for {key}");
}
assert_eq!(cache.len(), keys.len());
}
#[test]
fn device_list_and_single_device_keys_do_not_collide() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(
CacheKey::devices("nid"),
envelope(json!({"data": {"which": "list"}})),
);
cache.put(
CacheKey::device("nid", "devices"),
envelope(json!({"data": {"which": "single"}})),
);
let list = cache.get(&CacheKey::devices("nid")).expect("list hit");
let single = cache
.get(&CacheKey::device("nid", "devices"))
.expect("single hit");
assert_eq!(list.data()["which"], json!("list"));
assert_eq!(single.data()["which"], json!("single"));
}
#[test]
fn key_display_matches_python_key_shapes() {
assert_eq!(CacheKey::Account.to_string(), "account");
assert_eq!(CacheKey::Networks.to_string(), "networks");
assert_eq!(CacheKey::network("nid").to_string(), "network[nid]");
assert_eq!(CacheKey::eeros("nid").to_string(), "eeros[nid_eeros]");
assert_eq!(CacheKey::devices("nid").to_string(), "devices[nid_devices]");
assert_eq!(
CacheKey::device("nid", "did").to_string(),
"devices[nid_did]"
);
assert_eq!(
CacheKey::profiles("nid").to_string(),
"profiles[nid_profiles]"
);
assert_eq!(
CacheKey::profile("nid", "pid").to_string(),
"profiles[nid_pid]"
);
}
#[test]
fn devices_for_different_networks_never_collide() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(
CacheKey::devices("net-1"),
envelope(json!({"data": {"network": "net-1", "kind": "list"}})),
);
cache.put(
CacheKey::devices("net-2"),
envelope(json!({"data": {"network": "net-2", "kind": "list"}})),
);
cache.put(
CacheKey::device("net-1", "shared-device-id"),
envelope(json!({"data": {"network": "net-1", "kind": "single"}})),
);
cache.put(
CacheKey::device("net-2", "shared-device-id"),
envelope(json!({"data": {"network": "net-2", "kind": "single"}})),
);
assert_eq!(
cache.get(&CacheKey::devices("net-1")).unwrap().data()["network"],
json!("net-1")
);
assert_eq!(
cache.get(&CacheKey::devices("net-2")).unwrap().data()["network"],
json!("net-2")
);
assert_eq!(
cache
.get(&CacheKey::device("net-1", "shared-device-id"))
.unwrap()
.data()["network"],
json!("net-1")
);
assert_eq!(
cache
.get(&CacheKey::device("net-2", "shared-device-id"))
.unwrap()
.data()["network"],
json!("net-2")
);
assert_eq!(
cache.len(),
4,
"all four entries must coexist independently"
);
}
#[test]
fn clear_removes_values_and_timestamps() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, non_empty());
cache.put(CacheKey::network("nid"), non_empty());
cache.clear();
assert_eq!(cache.len(), 0);
assert!(cache.get(&CacheKey::Account).is_none());
assert!(cache.get(&CacheKey::network("nid")).is_none());
}
#[test]
fn invalidate_drops_exactly_one_key() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::device("nid", "did"), non_empty());
cache.put(CacheKey::devices("nid"), non_empty());
cache.invalidate(&CacheKey::device("nid", "did"));
assert!(cache.get(&CacheKey::device("nid", "did")).is_none());
assert!(
cache.get(&CacheKey::devices("nid")).is_some(),
"the sibling list key must survive"
);
}
#[test]
fn invalidate_bucket_drops_only_that_bucket_kind() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::network("nid"), non_empty());
cache.put(CacheKey::eeros("nid"), non_empty());
cache.put(CacheKey::Account, non_empty());
cache.invalidate_bucket(Bucket::Eeros, "nid");
assert!(cache.get(&CacheKey::eeros("nid")).is_none());
assert!(cache.get(&CacheKey::network("nid")).is_some());
assert!(cache.get(&CacheKey::Account).is_some());
}
#[test]
fn invalidate_bucket_drops_only_the_targeted_networks_entries() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::devices("net-1"), non_empty());
cache.put(CacheKey::device("net-1", "shared-id"), non_empty());
cache.put(CacheKey::devices("net-2"), non_empty());
cache.put(CacheKey::device("net-2", "shared-id"), non_empty());
cache.invalidate_bucket(Bucket::Devices, "net-1");
assert!(cache.get(&CacheKey::devices("net-1")).is_none());
assert!(cache.get(&CacheKey::device("net-1", "shared-id")).is_none());
assert!(
cache.get(&CacheKey::devices("net-2")).is_some(),
"network-2's device list must survive"
);
assert!(
cache.get(&CacheKey::device("net-2", "shared-id")).is_some(),
"network-2's device entry must survive, even sharing a device id with network-1"
);
}
#[test]
fn invalidate_bucket_drops_every_profile_entry_for_one_network() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::profiles("net-1"), non_empty());
cache.put(CacheKey::profile("net-1", "p1"), non_empty());
cache.put(CacheKey::profile("net-1", "p2"), non_empty());
cache.put(CacheKey::profiles("net-2"), non_empty());
cache.put(CacheKey::profile("net-2", "p1"), non_empty());
cache.invalidate_bucket(Bucket::Profiles, "net-1");
assert!(cache.get(&CacheKey::profiles("net-1")).is_none());
assert!(cache.get(&CacheKey::profile("net-1", "p1")).is_none());
assert!(cache.get(&CacheKey::profile("net-1", "p2")).is_none());
assert!(cache.get(&CacheKey::profiles("net-2")).is_some());
assert!(cache.get(&CacheKey::profile("net-2", "p1")).is_some());
}
#[test]
fn generation_advances_on_invalidate_even_when_the_key_is_absent() {
let cache = Cache::new(Duration::from_secs(60));
let before = cache.generation();
cache.invalidate(&CacheKey::device("n1", "never-cached"));
assert_ne!(cache.generation(), before);
}
#[test]
fn generation_advances_on_invalidate_bucket_and_clear_of_an_empty_cache() {
let cache = Cache::new(Duration::from_secs(60));
let start = cache.generation();
cache.invalidate_bucket(Bucket::Devices, "n1");
let after_bucket = cache.generation();
assert_ne!(after_bucket, start);
cache.clear();
assert_ne!(cache.generation(), after_bucket);
}
#[test]
fn generation_advances_when_an_invalidation_removes_an_entry() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, non_empty());
let before = cache.generation();
cache.invalidate(&CacheKey::Account);
assert_ne!(cache.generation(), before);
}
#[test]
fn put_does_not_advance_generation() {
let cache = Cache::new(Duration::from_secs(60));
let before = cache.generation();
cache.put(CacheKey::Account, non_empty());
cache.put(CacheKey::Account, non_empty());
assert_eq!(cache.generation(), before);
}
#[test]
fn generation_is_shared_between_clones() {
let cache = Cache::new(Duration::from_secs(60));
let clone = cache.clone();
let before = cache.generation();
clone.invalidate(&CacheKey::Networks);
assert_ne!(cache.generation(), before);
assert_eq!(cache.generation(), clone.generation());
}
#[test]
fn an_unrelated_invalidation_still_advances_the_generation() {
let cache = Cache::new(Duration::from_secs(60));
let captured_for_net_2_profile = cache.generation();
cache.invalidate_bucket(Bucket::Devices, "net-1");
assert!(!cache.put_if_current(
CacheKey::profile("net-2", "p1"),
non_empty(),
captured_for_net_2_profile
));
assert!(cache.get(&CacheKey::profile("net-2", "p1")).is_none());
}
#[test]
fn put_if_current_stores_when_nothing_was_invalidated() {
let cache = Cache::new(Duration::from_secs(60));
let generation = cache.generation();
assert!(cache.put_if_current(CacheKey::Account, non_empty(), generation));
assert_eq!(cache.get(&CacheKey::Account), Some(non_empty()));
}
#[test]
fn put_if_current_stores_after_unguarded_puts() {
let cache = Cache::new(Duration::from_secs(60));
let generation = cache.generation();
cache.put(CacheKey::Networks, non_empty());
assert!(cache.put_if_current(CacheKey::Account, non_empty(), generation));
}
#[test]
fn put_if_current_refuses_after_every_kind_of_invalidation() {
type Invalidator = fn(&Cache);
let invalidators: [(&str, Invalidator); 3] = [
("invalidate", |cache| {
cache.invalidate(&CacheKey::device("n1", "d1"));
}),
("invalidate_bucket", |cache| {
cache.invalidate_bucket(Bucket::Devices, "n1");
}),
("clear", Cache::clear),
];
for (label, invalidate) in invalidators {
for previously_present in [false, true] {
let cache = Cache::new(Duration::from_secs(60));
let key = CacheKey::device("n1", "d1");
if previously_present {
cache.put(key.clone(), envelope(json!({"data": {"which": "old"}})));
}
let generation = cache.generation();
invalidate(&cache);
assert!(
!cache.put_if_current(
key.clone(),
envelope(json!({"data": {"which": "stale"}})),
generation
),
"{label} (previously present: {previously_present}) must reject the store"
);
assert!(
cache.get(&key).is_none(),
"{label} (previously present: {previously_present}) left an entry behind"
);
}
}
}
#[test]
fn a_fresh_generation_taken_after_an_invalidation_is_accepted() {
let cache = Cache::new(Duration::from_secs(60));
cache.clear();
let generation = cache.generation();
assert!(cache.put_if_current(CacheKey::Account, non_empty(), generation));
}
#[tokio::test]
async fn an_expired_entry_is_removed_when_it_is_read() {
tokio::time::pause();
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::device("n1", "d1"), non_empty());
cache.put(CacheKey::device("n1", "d2"), non_empty());
tokio::time::advance(Duration::from_secs(61)).await;
cache.put(CacheKey::device("n1", "d2"), non_empty());
assert!(cache.get(&CacheKey::device("n1", "d1")).is_none());
assert_eq!(cache.len(), 1, "only the refreshed d2 entry is left");
assert!(cache.get(&CacheKey::device("n1", "d2")).is_some());
}
#[tokio::test]
async fn an_expired_single_entry_key_is_removed_when_it_is_read() {
tokio::time::pause();
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, non_empty());
cache.put(CacheKey::Networks, non_empty());
tokio::time::advance(Duration::from_secs(61)).await;
assert!(cache.get(&CacheKey::Account).is_none());
assert_eq!(
cache.len(),
1,
"the account entry is gone, networks is not read"
);
assert!(cache.get(&CacheKey::Networks).is_none());
assert!(cache.is_empty());
}
#[tokio::test]
async fn fresh_entries_are_left_alone_by_a_read() {
tokio::time::pause();
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, non_empty());
cache.put(CacheKey::device("n1", "d1"), non_empty());
tokio::time::advance(Duration::from_secs(59)).await;
assert!(cache.get(&CacheKey::Account).is_some());
assert!(cache.get(&CacheKey::device("n1", "d1")).is_some());
assert!(cache.get(&CacheKey::device("n1", "absent")).is_none());
assert_eq!(cache.len(), 2);
}
#[tokio::test]
async fn reading_a_pruned_key_again_is_a_plain_miss() {
tokio::time::pause();
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::device("n1", "d1"), non_empty());
tokio::time::advance(Duration::from_secs(61)).await;
assert!(cache.get(&CacheKey::device("n1", "d1")).is_none());
assert!(cache.get(&CacheKey::device("n1", "d1")).is_none());
assert!(cache.is_empty());
}
#[tokio::test]
async fn an_expired_entry_is_replaced_by_the_next_write() {
tokio::time::pause();
let cache = Cache::new(Duration::from_secs(60));
cache.put(
CacheKey::Account,
envelope(json!({"data": {"name": "old"}})),
);
tokio::time::advance(Duration::from_secs(61)).await;
assert!(cache.get(&CacheKey::Account).is_none());
cache.put(
CacheKey::Account,
envelope(json!({"data": {"name": "new"}})),
);
let cached = cache
.get(&CacheKey::Account)
.expect("fresh entry is served");
assert_eq!(cached.data()["name"], json!("new"));
}
#[test]
fn a_fresh_falsy_entry_is_not_pruned() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, envelope(json!({})));
assert!(cache.get(&CacheKey::Account).is_none());
assert_eq!(
cache.len(),
1,
"a falsy entry is not served but is not expired either"
);
}
#[tokio::test]
async fn pruning_does_not_advance_the_generation() {
tokio::time::pause();
let cache = Cache::new(Duration::from_secs(60));
cache.put(CacheKey::Account, non_empty());
let generation = cache.generation();
tokio::time::advance(Duration::from_secs(61)).await;
assert!(cache.get(&CacheKey::Account).is_none());
assert_eq!(cache.generation(), generation);
assert!(cache.put_if_current(CacheKey::Account, non_empty(), generation));
}
#[test]
fn debug_does_not_leak_a_cached_password_but_does_show_the_key() {
let cache = Cache::new(Duration::from_secs(60));
cache.put(
CacheKey::network("nid"),
envelope(json!({
"data": {"name": "Home", "guest_network": {"password": "super-secret-wifi-pw"}}
})),
);
let rendered = format!("{cache:?}");
assert!(!rendered.contains("super-secret-wifi-pw"));
assert!(rendered.contains("network[nid]"));
assert!(
rendered.contains('1'),
"entry count should be visible: {rendered}"
);
}
}