Skip to main content

loco_rs/cache/drivers/
mod.rs

1//! # Cache Drivers Module
2//!
3//! This module defines traits and implementations for cache drivers.
4use std::time::Duration;
5
6use async_trait::async_trait;
7
8use super::CacheResult;
9
10#[cfg(feature = "cache_inmem")]
11pub mod inmem;
12pub mod null;
13#[cfg(feature = "cache_redis")]
14pub mod redis;
15
16/// Trait representing a cache driver.
17#[async_trait]
18pub trait CacheDriver: Sync + Send {
19    /// Pings the cache to check if it is reachable.
20    ///
21    /// # Errors
22    ///
23    /// Returns a [`super::CacheError`] if there is an error during the
24    /// operation.
25    async fn ping(&self) -> CacheResult<()>;
26
27    /// Checks if a key exists in the cache.
28    ///
29    /// # Errors
30    ///
31    /// Returns a [`super::CacheError`] if there is an error during the
32    /// operation.
33    async fn contains_key(&self, key: &str) -> CacheResult<bool>;
34
35    /// Retrieves a value from the cache based on the provided key.
36    ///
37    /// # Errors
38    ///
39    /// Returns a [`super::CacheError`] if there is an error during the
40    /// operation.
41    async fn get(&self, key: &str) -> CacheResult<Option<String>>;
42
43    /// Inserts a key-value pair into the cache.
44    ///
45    /// # Errors
46    ///
47    /// Returns a [`super::CacheError`] if there is an error during the
48    /// operation.
49    async fn insert(&self, key: &str, value: &str) -> CacheResult<()>;
50
51    /// Inserts a key-value pair into the cache that expires after the
52    /// specified duration.
53    ///
54    /// # Errors
55    ///
56    /// Returns a [`super::CacheError`] if there is an error during the
57    /// operation.
58    async fn insert_with_expiry(
59        &self,
60        key: &str,
61        value: &str,
62        duration: Duration,
63    ) -> CacheResult<()>;
64
65    /// Removes a key-value pair from the cache.
66    ///
67    /// # Errors
68    ///
69    /// Returns a [`super::CacheError`] if there is an error during the
70    /// operation.
71    async fn remove(&self, key: &str) -> CacheResult<()>;
72
73    /// Clears all key-value pairs from the cache.
74    ///
75    /// # Errors
76    ///
77    /// Returns a [`super::CacheError`] if there is an error during the
78    /// operation.
79    async fn clear(&self) -> CacheResult<()>;
80}