mocra_core/cacheable/cache_service/
service.rs1use super::backend::CacheBackend;
2use super::local_backend::LocalBackend;
3use crate::errors::CacheError;
4use std::sync::Arc;
5use std::time::Duration;
6
7pub struct CacheService {
8 pub(crate) backend: Arc<dyn CacheBackend>,
9 pub(crate) namespace: String,
10 pub(crate) default_ttl: Option<Duration>,
11 pub(crate) serialize_blocking_threshold: usize,
12}
13
14impl CacheService {
15 pub fn new(
21 namespace: String,
22 default_ttl: Option<Duration>,
23 compression_threshold: Option<usize>,
24 ) -> Self {
25 let _ = compression_threshold;
26 CacheService {
27 backend: Arc::new(LocalBackend::new()),
28 namespace,
29 default_ttl,
30 serialize_blocking_threshold: 64 * 1024,
31 }
32 }
33
34 pub async fn set_nx(
35 &self,
36 key: &str,
37 value: &[u8],
38 ttl: Option<Duration>,
39 ) -> Result<bool, CacheError> {
40 self.backend.set_nx(key, value, ttl).await
41 }
42
43 pub fn namespace(&self) -> &str {
44 &self.namespace
45 }
46
47 pub async fn zadd(&self, key: &str, score: f64, member: &[u8]) -> Result<i64, CacheError> {
48 self.backend.zadd(key, score, member).await
49 }
50
51 pub async fn zrangebyscore(
52 &self,
53 key: &str,
54 min: f64,
55 max: f64,
56 ) -> Result<Vec<Vec<u8>>, CacheError> {
57 self.backend.zrangebyscore(key, min, max).await
58 }
59
60 pub async fn zremrangebyscore(&self, key: &str, min: f64, max: f64) -> Result<i64, CacheError> {
61 self.backend.zremrangebyscore(key, min, max).await
62 }
63
64 pub async fn set_nx_batch(
65 &self,
66 keys: &[&str],
67 value: &[u8],
68 ttl: Option<Duration>,
69 ) -> Result<Vec<bool>, CacheError> {
70 self.backend.set_nx_batch(keys, value, ttl).await
71 }
72
73 pub async fn mget(&self, keys: &[&str]) -> Result<Vec<Option<Vec<u8>>>, CacheError> {
74 self.backend.mget(keys).await
75 }
76
77 pub async fn incr(&self, key: &str, delta: i64) -> Result<i64, CacheError> {
78 self.backend.incr(key, delta).await
79 }
80
81 pub async fn set(
82 &self,
83 key: &str,
84 value: &[u8],
85 ttl: Option<Duration>,
86 ) -> Result<(), CacheError> {
87 self.backend.set(key, value, ttl).await
88 }
89
90 pub async fn del(&self, key: &str) -> Result<(), CacheError> {
91 self.backend.del(key).await
92 }
93
94 pub async fn del_batch(&self, keys: &[&str]) -> Result<u64, CacheError> {
95 self.backend.del_batch(keys).await
96 }
97
98 pub async fn keys(&self, pattern: &str) -> Result<Vec<String>, CacheError> {
99 self.backend.keys(pattern).await
100 }
101
102 pub async fn keys_with_limit(
103 &self,
104 pattern: &str,
105 limit: usize,
106 ) -> Result<Vec<String>, CacheError> {
107 self.backend.keys_with_limit(pattern, limit).await
108 }
109
110 pub async fn get(&self, key: &str) -> Result<Option<Vec<u8>>, CacheError> {
111 self.backend.get(key).await
112 }
113
114 pub async fn ping(&self) -> Result<(), CacheError> {
115 self.backend.ping().await
116 }
117
118 pub fn default_ttl(&self) -> Option<Duration> {
119 self.default_ttl
120 }
121}