breez_sdk_core/persist/
cache.rs

1use serde_json::Value;
2
3use crate::models::NodeState;
4
5use super::{db::SqliteStorage, error::PersistResult};
6
7const KEY_GL_CREDENTIALS: &str = "gl_credentials";
8const KEY_LAST_BACKUP_TIME: &str = "last_backup_time";
9const KEY_SYNC_STATE: &str = "sync_state";
10const KEY_NODE_STATE: &str = "node_state";
11const KEY_STATIC_BACKUP: &str = "static_backup";
12const KEY_WEBHOOK_URL: &str = "webhook_url";
13const KEY_MEMPOOLSPACE_BASE_URLS: &str = "mempoolspace_base_urls";
14
15impl SqliteStorage {
16    pub fn get_cached_item(&self, key: &str) -> PersistResult<Option<String>> {
17        let res = self.get_connection()?.query_row(
18            "SELECT value FROM cached_items WHERE key = ?1",
19            [key],
20            |row| row.get(0),
21        );
22        Ok(res.ok())
23    }
24
25    pub fn update_cached_item(&self, key: &str, value: String) -> PersistResult<()> {
26        self.get_connection()?.execute(
27            "INSERT OR REPLACE INTO cached_items (key, value) VALUES (?1,?2)",
28            (key, value),
29        )?;
30        Ok(())
31    }
32
33    #[allow(dead_code)]
34    pub fn delete_cached_item(&self, key: &str) -> PersistResult<()> {
35        self.get_connection()?
36            .execute("DELETE FROM cached_items WHERE key = ?1", [key])?;
37        Ok(())
38    }
39
40    pub fn set_node_state(&self, state: &NodeState) -> PersistResult<()> {
41        let serialized_state = serde_json::to_string(state)?;
42        self.update_cached_item(KEY_NODE_STATE, serialized_state)
43    }
44
45    pub fn get_node_state(&self) -> PersistResult<Option<NodeState>> {
46        let state_str = self.get_cached_item(KEY_NODE_STATE)?;
47        Ok(match state_str {
48            Some(str) => serde_json::from_str(str.as_str())?,
49            None => None,
50        })
51    }
52
53    pub fn set_last_backup_time(&self, t: u64) -> PersistResult<()> {
54        self.update_cached_item(KEY_LAST_BACKUP_TIME, t.to_string())
55    }
56
57    pub fn get_last_backup_time(&self) -> PersistResult<Option<u64>> {
58        let state_str = self.get_cached_item(KEY_LAST_BACKUP_TIME)?;
59        Ok(match state_str {
60            Some(str) => str.as_str().parse::<u64>().ok(),
61            None => None,
62        })
63    }
64
65    pub fn set_sync_state(&self, t: &Value) -> PersistResult<()> {
66        self.update_cached_item(KEY_SYNC_STATE, t.to_string())
67    }
68
69    pub fn get_sync_state(&self) -> PersistResult<Option<Value>> {
70        let state_str = self.get_cached_item(KEY_SYNC_STATE)?;
71        Ok(match state_str {
72            Some(str) => serde_json::from_str(&str)?,
73            None => None,
74        })
75    }
76
77    pub fn set_gl_credentials(&self, creds: Vec<u8>) -> PersistResult<()> {
78        self.update_cached_item(KEY_GL_CREDENTIALS, hex::encode(creds))
79    }
80
81    pub fn get_gl_credentials(&self) -> PersistResult<Option<Vec<u8>>> {
82        match self.get_cached_item(KEY_GL_CREDENTIALS)? {
83            Some(str) => Ok(Some(hex::decode(str)?)),
84            None => Ok(None),
85        }
86    }
87
88    pub fn set_static_backup(&self, backup: Vec<String>) -> PersistResult<()> {
89        let serialized_state = serde_json::to_string(&backup)?;
90        self.update_cached_item(KEY_STATIC_BACKUP, serialized_state)
91    }
92
93    pub fn get_static_backup(&self) -> PersistResult<Option<Vec<String>>> {
94        let backup_str = self.get_cached_item(KEY_STATIC_BACKUP)?;
95        Ok(match backup_str {
96            Some(str) => serde_json::from_str(str.as_str())?,
97            None => None,
98        })
99    }
100
101    pub fn set_webhook_url(&self, webhook_url: String) -> PersistResult<()> {
102        self.update_cached_item(KEY_WEBHOOK_URL, webhook_url)
103    }
104
105    #[allow(dead_code)]
106    pub fn remove_webhook_url(&self) -> PersistResult<()> {
107        self.delete_cached_item(KEY_WEBHOOK_URL)
108    }
109
110    #[allow(dead_code)]
111    pub fn get_webhook_url(&self) -> PersistResult<Option<String>> {
112        self.get_cached_item(KEY_WEBHOOK_URL)
113    }
114
115    pub fn set_mempoolspace_base_urls(
116        &self,
117        mempool_space_endpoints: Vec<String>,
118    ) -> PersistResult<()> {
119        let serialized = serde_json::to_string(&mempool_space_endpoints)?;
120        self.update_cached_item(KEY_MEMPOOLSPACE_BASE_URLS, serialized)
121    }
122
123    pub fn get_mempoolspace_base_urls(&self) -> PersistResult<Vec<String>> {
124        let res = match self.get_cached_item(KEY_MEMPOOLSPACE_BASE_URLS)? {
125            Some(str) => serde_json::from_str(str.as_str())?,
126            None => vec![],
127        };
128
129        Ok(res)
130    }
131}
132
133#[test]
134fn test_cached_items() {
135    use crate::persist::test_utils;
136
137    let storage = SqliteStorage::new(test_utils::create_test_sql_dir());
138
139    storage.init().unwrap();
140    storage
141        .update_cached_item("key1", "val1".to_string())
142        .unwrap();
143    let item_value = storage.get_cached_item("key1").unwrap();
144    assert_eq!(item_value, Some("val1".to_string()));
145
146    storage.delete_cached_item("key1").unwrap();
147    let item_value = storage.get_cached_item("key1").unwrap();
148    assert_eq!(item_value, None);
149}