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,
}
pub struct Cache {
ttl: Duration,
inner: Arc<RwLock<HashMap<CacheKey, Entry>>>,
}
impl Cache {
#[must_use]
pub fn new(ttl: Duration) -> Self {
Self {
ttl,
inner: Arc::new(RwLock::new(HashMap::new())),
}
}
fn read(&self) -> RwLockReadGuard<'_, HashMap<CacheKey, Entry>> {
self.inner.read().unwrap_or_else(PoisonError::into_inner)
}
fn write(&self) -> RwLockWriteGuard<'_, HashMap<CacheKey, Entry>> {
self.inner.write().unwrap_or_else(PoisonError::into_inner)
}
#[must_use]
pub fn get(&self, key: &CacheKey) -> Option<Envelope> {
if self.ttl.is_zero() {
return None;
}
let entries = self.read();
let entry = entries.get(key)?;
if entry.inserted_at.elapsed() >= self.ttl {
return None;
}
if is_falsy(&entry.value) {
return None;
}
Some(entry.value.clone())
}
pub fn put(&self, key: CacheKey, value: Envelope) {
let mut entries = self.write();
entries.insert(
key,
Entry {
value,
inserted_at: Instant::now(),
},
);
}
pub fn invalidate(&self, key: &CacheKey) {
self.write().remove(key);
}
pub fn invalidate_bucket(&self, bucket: Bucket, network_id: &str) {
self.write()
.retain(|key, _| !key.is_in_bucket(bucket, network_id));
}
pub fn clear(&self) {
self.write().clear();
}
#[must_use]
pub fn len(&self) -> usize {
self.read().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 entries = self.read();
let mut keys: Vec<String> = entries.keys().map(ToString::to_string).collect();
keys.sort_unstable();
f.debug_struct("Cache")
.field("ttl", &self.ttl)
.field("len", &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!(cache.get(&CacheKey::Account).is_none());
assert_eq!(cache.len(), 1, "the write must still have happened");
}
#[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 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}"
);
}
}