gadget_sdk/store/
mod.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
use crate::error::Error;
use alloc::boxed::Box;
use serde::de::DeserializeOwned;
use serde::Serialize;
use sp_core::ecdsa::Pair as EcdsaPair;
use sp_core::sr25519::Pair as Sr25519Pair;
use sp_core::Pair;

use parking_lot::RwLock;
use sqlx::sqlite::SqlitePoolOptions;
use sqlx::{Pool, Row, Sqlite};

use std::collections::HashMap;
use std::sync::Arc;

use crate::network::{deserialize, serialize};

mod local_database;
pub use local_database::LocalDatabase;

#[async_trait::async_trait]
pub trait KeyValueStoreBackend: Clone + Send + Sync + 'static {
    async fn get<T: DeserializeOwned>(&self, key: &[u8; 32]) -> Result<Option<T>, Error>;
    async fn set<T: Serialize + Send>(&self, key: &[u8; 32], value: T) -> Result<(), Error>;
}

pub type ECDSAKeyStore<BE> = GenericKeyStore<BE, EcdsaPair>;
pub type Sr25519KeyStore<BE> = GenericKeyStore<BE, Sr25519Pair>;

#[derive(Clone, Debug)]
pub struct GenericKeyStore<BE: KeyValueStoreBackend, P: Pair> {
    backend: BE,
    pair: P,
}

#[cfg(feature = "std")]
impl<P: Pair> GenericKeyStore<InMemoryBackend, P> {
    pub fn in_memory(pair: P) -> Self {
        GenericKeyStore {
            backend: InMemoryBackend::new(),
            pair,
        }
    }
}

#[cfg(feature = "std")]
impl<P: Pair> GenericKeyStore<SqliteBackend, P> {
    pub async fn sqlite_in_memory(pair: P) -> Result<Self, Box<dyn std::error::Error>> {
        let backend = SqliteBackend::in_memory().await?;
        Ok(GenericKeyStore { backend, pair })
    }
}

impl<P: Pair, Backend: KeyValueStoreBackend> GenericKeyStore<Backend, P> {
    pub fn new(backend: Backend, pair: P) -> Self {
        GenericKeyStore { backend, pair }
    }
}

impl<P: Pair, BE: KeyValueStoreBackend> GenericKeyStore<BE, P> {
    pub fn pair(&self) -> &P {
        &self.pair
    }
}

impl<P: Pair, BE: KeyValueStoreBackend> GenericKeyStore<BE, P> {
    pub async fn get<T: DeserializeOwned>(&self, key: &[u8; 32]) -> Result<Option<T>, Error> {
        self.backend.get(key).await
    }

    pub async fn set<T: Serialize + Send>(&self, key: &[u8; 32], value: T) -> Result<(), Error> {
        self.backend.set(key, value).await
    }
}

#[derive(Clone, Debug)]
#[cfg(feature = "std")]
pub struct InMemoryBackend {
    map: Arc<RwLock<HashMap<[u8; 32], Vec<u8>>>>,
}

#[cfg(feature = "std")]
impl Default for InMemoryBackend {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(feature = "std")]
impl InMemoryBackend {
    pub fn new() -> Self {
        Self {
            map: Arc::new(RwLock::new(HashMap::new())),
        }
    }
}

#[async_trait::async_trait]
#[cfg(feature = "std")]
impl KeyValueStoreBackend for InMemoryBackend {
    async fn get<T: DeserializeOwned>(&self, key: &[u8; 32]) -> Result<Option<T>, Error> {
        if let Some(bytes) = self.map.read().get(key).cloned() {
            let value: T = deserialize(&bytes).map_err(|rr| Error::Store {
                reason: format!("Failed to deserialize value: {:?}", rr),
            })?;
            Ok(Some(value))
        } else {
            Ok(None)
        }
    }

    async fn set<T: Serialize + Send>(&self, key: &[u8; 32], value: T) -> Result<(), Error> {
        let serialized = serialize(&value).map_err(|rr| Error::Store {
            reason: format!("Failed to serialize value: {:?}", rr),
        })?;
        let _ = self.map.write().insert(*key, serialized);
        Ok(())
    }
}

#[derive(Clone, Debug)]
#[cfg(feature = "std")]
pub struct SqliteBackend {
    pool: Pool<Sqlite>,
}
#[cfg(feature = "std")]
impl SqliteBackend {
    pub async fn in_memory() -> Result<Self, Box<dyn std::error::Error>> {
        Self::new("sqlite://:memory:").await
    }

    // Initialize a new key-value store with a SqlitePool
    pub async fn new(database_url: &str) -> Result<Self, Box<dyn std::error::Error>> {
        let pool = SqlitePoolOptions::new().connect(database_url).await?;

        // Ensure the table exists
        let _ = sqlx::query(
            r"CREATE TABLE IF NOT EXISTS key_value_store (
                key TEXT PRIMARY KEY,
                value BLOB NOT NULL
              )",
        )
        .execute(&pool)
        .await?;

        Ok(Self { pool })
    }
}

#[async_trait::async_trait]
#[cfg(all(feature = "std", not(target_family = "wasm")))]
impl KeyValueStoreBackend for SqliteBackend {
    async fn get<T: DeserializeOwned>(&self, key: &[u8; 32]) -> Result<Option<T>, Error> {
        let key = key_to_string(key);
        let result = sqlx::query("SELECT value FROM key_value_store WHERE key = ?")
            .bind(key)
            .fetch_optional(&self.pool)
            .await
            .map_err(|err| Error::Store {
                reason: format!("Failed to fetch value: {:?}", err),
            })?;

        match result {
            Some(row) => {
                let value: Vec<u8> = row.get("value");
                let value: T = deserialize(&value).map_err(|rr| Error::Store {
                    reason: format!("Failed to deserialize value: {:?}", rr),
                })?;
                Ok(Some(value))
            }
            None => Ok(None),
        }
    }

    async fn set<T: Serialize + Send>(&self, key: &[u8; 32], value: T) -> Result<(), Error> {
        let key = key_to_string(key);
        let value = serialize(&value).map_err(|rr| Error::Store {
            reason: format!("Failed to serialize value: {:?}", rr),
        })?;

        let _ = sqlx::query("INSERT INTO key_value_store (key, value) VALUES (?, ?)")
            .bind(key)
            .bind(value)
            .execute(&self.pool)
            .await
            .map_err(|err| Error::Store {
                reason: format!("Failed to insert value: {:?}", err),
            })?;
        Ok(())
    }
}

#[cfg(all(feature = "std", not(target_family = "wasm")))]
fn key_to_string(key: &[u8; 32]) -> String {
    hex::encode(key)
}

#[allow(clippy::needless_return)]
#[cfg(test)]
#[cfg(not(target_family = "wasm"))]
mod tests {
    use crate::store::KeyValueStoreBackend;
    use gadget_io::tokio;

    #[gadget_io::tokio::test]
    #[cfg(feature = "std")]
    async fn test_in_memory_kv_store() {
        let store = super::SqliteBackend::in_memory().await.unwrap();
        let key = [0u8; 32];
        let value = "hello".to_string();
        store.set(&key, value.clone()).await.unwrap();
        let result: String = store.get(&key).await.unwrap().unwrap();
        assert_eq!(value, result);
    }
}