Skip to main content

flippico_cache/
lib.rs

1use crate::types::provider::{Provider, ProviderEither};
2
3pub mod core;
4pub mod providers;
5pub mod types;
6
7pub struct Cache {
8    provider: ProviderEither,
9}
10
11impl Cache {
12    pub fn new() -> Self {
13        Self {
14            provider: Provider::Redis.create_provider(),
15        }
16    }
17
18    pub fn pub_sub(
19        self,
20    ) -> Result<
21        Box<
22            dyn types::provider::ConnectablePubSubProvider<
23                    Channels = types::channels::SubscriptionChannel,
24                > + Send
25                + Sync,
26        >,
27        &'static str,
28    > {
29        self.provider.pub_sub()
30    }
31
32    pub fn fifo(
33        self,
34    ) -> Result<Box<dyn types::provider::ConnectableFifoProvider + Send + Sync>, &'static str> {
35        self.provider.fifo()
36    }
37
38    pub fn cache(
39        self,
40    ) -> Result<Box<dyn types::provider::ConnectableCacheProvider + Send + Sync>, &'static str>
41    {
42        self.provider.cache()
43    }
44
45    pub fn sorted_set(
46        self,
47    ) -> Result<Box<dyn types::provider::ConnectableSortedSetProvider + Send + Sync>, &'static str>
48    {
49        self.provider.sorted_set()
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use crate::types::channels::{
56        CacheSpace, ChannelMessage, ListChannel, ListMessage, SubscriptionChannel,
57    };
58    use std::sync::Arc;
59
60    use super::*;
61
62    fn get_test_msg() -> ChannelMessage {
63        ChannelMessage {
64            channel: SubscriptionChannel::BajkomatApi,
65            meta: None,
66            body: None,
67        }
68    }
69
70    fn get_test_list_msg() -> ListMessage {
71        ListMessage {
72            meta: None,
73            body: serde_json::json!({"body": "test"}).into(),
74        }
75    }
76
77    #[tokio::test]
78    async fn fifo_test() {
79        let cache = Arc::new(Cache::new().fifo().unwrap());
80        let cache_clone = cache.clone();
81        cache.push(
82            ListChannel::BajkomatApi,
83            "job_key",
84            serde_json::json!({"body": "test"}),
85        );
86        let fifo_value = cache_clone.pop(ListChannel::BajkomatApi, "job_key");
87        let msg2 = get_test_list_msg();
88        assert_eq!(fifo_value.unwrap(), msg2);
89    }
90
91    #[test]
92    fn publish_test() {
93        let mut cache = Cache::new().pub_sub().unwrap();
94        cache.publish(SubscriptionChannel::BajkomatApi, get_test_msg());
95    }
96
97    #[test]
98    fn cache_test_set() {
99        let cache = Cache::new().cache().unwrap();
100        let test_data = serde_json::json!({"data": "test"});
101        cache.set(CacheSpace::Shopify, "SomeKey", test_data, None);
102        let value = cache.get(CacheSpace::Shopify, "SomeKey", None);
103        assert_eq!("{\"meta\":null,\"value\":{\"data\":\"test\"}}", value);
104    }
105
106    #[test]
107    fn cache_test_del() {
108        let cache = Cache::new().cache().unwrap();
109        let test_data = serde_json::json!({"data": "test"});
110        cache.set(CacheSpace::Shopify, "SomeKey", test_data, None);
111        let value = cache.get(CacheSpace::Shopify, "SomeKey", None);
112        assert_eq!("{\"meta\":null,\"value\":{\"data\":\"test\"}}", value);
113        cache.delete(CacheSpace::Shopify, "SomeKey", None);
114        let value = cache.get(CacheSpace::Shopify, "SomeKey", None);
115        assert_eq!("", value);
116    }
117
118    // #[tokio::test]
119    // async fn subscribe_test() {
120    //     let subscriber_cache = Cache::new().pub_sub().unwrap();
121    //     let mut publisher_cache = Cache::new().pub_sub().unwrap();
122
123    //     // Use a channel to signal when the callback is executed
124    //     let (tx, rx) = tokio::sync::oneshot::channel();
125    //     let tx = std::sync::Arc::new(std::sync::Mutex::new(Some(tx)));
126
127    //     let sub_clbk = move |msg: ChannelMessage| {
128    //         let tx_clone = tx.clone();
129    //         Box::pin(async move {
130    //             let msg2 = get_test_msg();
131    //             assert_eq!(msg, msg2);
132    //             if let Ok(mut tx_guard) = tx_clone.lock() {
133    //                 if let Some(sender) = tx_guard.take() {
134    //                     let _ = sender.send(());
135    //                 }
136    //             }
137    //         }) as Pin<Box<dyn std::future::Future<Output = ()> + Send + Sync>>
138    //     };
139
140    //     // Start the subscription task by moving the cache into the spawned task
141    //     let _handle = tokio::spawn(async move {
142    //         let subscription_task =
143    //             subscriber_cache.subscribe(Box::new(sub_clbk), SubscriptionChannel::BajkomatApi);
144    //         let _ = subscription_task.await;
145    //     });
146
147    //     // Wait a moment for subscription to be established
148    //     tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
149
150    //     // Publish the message
151    //     publisher_cache.publish(SubscriptionChannel::BajkomatApi, get_test_msg());
152
153    //     // Wait for the callback to be executed with timeout
154    //     let timeout_result = tokio::time::timeout(tokio::time::Duration::from_secs(10), rx).await;
155    //     match timeout_result {
156    //         Ok(Ok(())) => {
157    //             // Test passed
158    //         }
159    //         Ok(Err(e)) => {
160    //             panic!("Callback channel error: {:?}", e);
161    //         }
162    //         Err(_error) => {
163    //             // Check if Redis is available - if not, skip the test
164    //             println!("Test timed out - Redis may not be available, skipping test");
165    //             return;
166    //         }
167    //     }
168    // }
169}