memory.rs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. use std::time::Duration;
  2. use moka::future::Cache;
  3. use crate::cache::{HttpCacheKey, HttpCacheStorage, DEFAULT_TTI_SECS, DEFAULT_TTL_SECS};
  4. /// In memory cache storage for the HTTP cache.
  5. ///
  6. /// This is the default cache storage backend, which is used if no other storage
  7. /// backend is provided, or if the provided storage backend is `None`.
  8. ///
  9. /// The cache is limited to 10,000 entries and it is not shared between
  10. /// instances nor persisted.
  11. pub struct InMemoryHttpCache(pub Cache<HttpCacheKey, Vec<u8>>);
  12. impl Default for InMemoryHttpCache {
  13. fn default() -> Self {
  14. InMemoryHttpCache(
  15. Cache::builder()
  16. .max_capacity(10_000)
  17. .time_to_live(Duration::from_secs(DEFAULT_TTL_SECS))
  18. .time_to_idle(Duration::from_secs(DEFAULT_TTI_SECS))
  19. .build(),
  20. )
  21. }
  22. }
  23. #[async_trait::async_trait]
  24. impl HttpCacheStorage for InMemoryHttpCache {
  25. fn set_expiration_times(&mut self, cache_ttl: Duration, cache_tti: Duration) {
  26. self.0 = Cache::builder()
  27. .max_capacity(10_000)
  28. .time_to_live(cache_ttl)
  29. .time_to_idle(cache_tti)
  30. .build();
  31. }
  32. async fn get(&self, key: &HttpCacheKey) -> Option<Vec<u8>> {
  33. self.0.get(key).await
  34. }
  35. async fn set(&self, key: HttpCacheKey, value: Vec<u8>) {
  36. self.0.insert(key, value).await;
  37. }
  38. }