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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Implements [`crate::store::KeyValueStore`] in memory.

use std::{
    collections::BTreeMap,
    sync::{Arc, LazyLock, Mutex, RwLock},
};

use serde::{Deserialize, Serialize};
use thiserror::Error;

#[cfg(with_testing)]
use crate::random::generate_test_namespace;
#[cfg(with_testing)]
use crate::store::TestKeyValueStore;
use crate::{
    batch::{Batch, WriteOperation},
    common::get_interval,
    store::{
        AdminKeyValueStore, CommonStoreInternalConfig, KeyValueStoreError, ReadableKeyValueStore,
        WithError, WritableKeyValueStore,
    },
};

/// The initial configuration of the system
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct MemoryStoreConfig {
    /// The common configuration of the key value store
    pub common_config: CommonStoreInternalConfig,
}

impl MemoryStoreConfig {
    /// Creates a `MemoryStoreConfig`. `max_concurrent_queries` and `cache_size` are not used.
    pub fn new(max_stream_queries: usize) -> Self {
        let common_config = CommonStoreInternalConfig {
            max_concurrent_queries: None,
            max_stream_queries,
        };
        Self { common_config }
    }
}

/// The number of streams for the test
pub const TEST_MEMORY_MAX_STREAM_QUERIES: usize = 10;

/// The data is serialized in memory just like for RocksDB / DynamoDB
/// The analog of the database is the `BTreeMap`
type MemoryStoreMap = BTreeMap<Vec<u8>, Vec<u8>>;

/// The container for the `MemoryStoreMap`s by namespace and then root key
#[derive(Default)]
struct MemoryStores {
    stores: BTreeMap<String, BTreeMap<Vec<u8>, Arc<RwLock<MemoryStoreMap>>>>,
}

impl MemoryStores {
    fn sync_connect(
        &mut self,
        config: &MemoryStoreConfig,
        namespace: &str,
        root_key: &[u8],
        kill_on_drop: bool,
    ) -> Result<MemoryStore, MemoryStoreError> {
        let max_stream_queries = config.common_config.max_stream_queries;
        let Some(stores) = self.stores.get_mut(namespace) else {
            return Err(MemoryStoreError::NamespaceNotFound);
        };
        let store = stores.entry(root_key.to_vec()).or_insert_with(|| {
            let map = MemoryStoreMap::new();
            Arc::new(RwLock::new(map))
        });
        let map = store.clone();
        let namespace = namespace.to_string();
        let root_key = root_key.to_vec();
        Ok(MemoryStore {
            map,
            max_stream_queries,
            namespace,
            root_key,
            kill_on_drop,
        })
    }

    fn sync_list_all(&self) -> Vec<String> {
        self.stores.keys().cloned().collect::<Vec<_>>()
    }

    fn sync_list_root_keys(&self, namespace: &str) -> Vec<Vec<u8>> {
        match self.stores.get(namespace) {
            None => Vec::new(),
            Some(map) => map.keys().cloned().collect::<Vec<_>>(),
        }
    }

    fn sync_exists(&self, namespace: &str) -> bool {
        self.stores.contains_key(namespace)
    }

    fn sync_create(&mut self, namespace: &str) {
        self.stores.insert(namespace.to_string(), BTreeMap::new());
    }

    fn sync_delete(&mut self, namespace: &str) {
        self.stores.remove(namespace);
    }
}

/// The global variables of the Namespace memory stores
static MEMORY_STORES: LazyLock<Mutex<MemoryStores>> =
    LazyLock::new(|| Mutex::new(MemoryStores::default()));

/// A virtual DB client where data are persisted in memory.
#[derive(Clone)]
pub struct MemoryStore {
    /// The map used for storing the data.
    map: Arc<RwLock<MemoryStoreMap>>,
    /// The maximum number of queries used for the stream.
    max_stream_queries: usize,
    /// The namespace of the store
    namespace: String,
    /// The root key of the store
    root_key: Vec<u8>,
    /// Whether to kill on drop or not the
    kill_on_drop: bool,
}

impl Drop for MemoryStore {
    fn drop(&mut self) {
        if self.kill_on_drop {
            let mut memory_stores = MEMORY_STORES
                .lock()
                .expect("MEMORY_STORES lock should not be poisoned");
            let stores = memory_stores.stores.get_mut(&self.namespace).unwrap();
            stores.remove(&self.root_key);
        }
    }
}

impl WithError for MemoryStore {
    type Error = MemoryStoreError;
}

impl ReadableKeyValueStore for MemoryStore {
    const MAX_KEY_SIZE: usize = usize::MAX;
    type Keys = Vec<Vec<u8>>;
    type KeyValues = Vec<(Vec<u8>, Vec<u8>)>;

    fn max_stream_queries(&self) -> usize {
        self.max_stream_queries
    }

    async fn read_value_bytes(&self, key: &[u8]) -> Result<Option<Vec<u8>>, MemoryStoreError> {
        let map = self
            .map
            .read()
            .expect("MemoryStore lock should not be poisoned");
        Ok(map.get(key).cloned())
    }

    async fn contains_key(&self, key: &[u8]) -> Result<bool, MemoryStoreError> {
        let map = self
            .map
            .read()
            .expect("MemoryStore lock should not be poisoned");
        Ok(map.contains_key(key))
    }

    async fn contains_keys(&self, keys: Vec<Vec<u8>>) -> Result<Vec<bool>, MemoryStoreError> {
        let map = self
            .map
            .read()
            .expect("MemoryStore lock should not be poisoned");
        Ok(keys
            .into_iter()
            .map(|key| map.contains_key(&key))
            .collect::<Vec<_>>())
    }

    async fn read_multi_values_bytes(
        &self,
        keys: Vec<Vec<u8>>,
    ) -> Result<Vec<Option<Vec<u8>>>, MemoryStoreError> {
        let map = self
            .map
            .read()
            .expect("MemoryStore lock should not be poisoned");
        let mut result = Vec::new();
        for key in keys {
            result.push(map.get(&key).cloned());
        }
        Ok(result)
    }

    async fn find_keys_by_prefix(
        &self,
        key_prefix: &[u8],
    ) -> Result<Vec<Vec<u8>>, MemoryStoreError> {
        let map = self
            .map
            .read()
            .expect("MemoryStore lock should not be poisoned");
        let mut values = Vec::new();
        let len = key_prefix.len();
        for (key, _value) in map.range(get_interval(key_prefix.to_vec())) {
            values.push(key[len..].to_vec())
        }
        Ok(values)
    }

    async fn find_key_values_by_prefix(
        &self,
        key_prefix: &[u8],
    ) -> Result<Vec<(Vec<u8>, Vec<u8>)>, MemoryStoreError> {
        let map = self
            .map
            .read()
            .expect("MemoryStore lock should not be poisoned");
        let mut key_values = Vec::new();
        let len = key_prefix.len();
        for (key, value) in map.range(get_interval(key_prefix.to_vec())) {
            let key_value = (key[len..].to_vec(), value.to_vec());
            key_values.push(key_value);
        }
        Ok(key_values)
    }
}

impl WritableKeyValueStore for MemoryStore {
    const MAX_VALUE_SIZE: usize = usize::MAX;

    async fn write_batch(&self, batch: Batch) -> Result<(), MemoryStoreError> {
        let mut map = self
            .map
            .write()
            .expect("MemoryStore lock should not be poisoned");
        for ent in batch.operations {
            match ent {
                WriteOperation::Put { key, value } => {
                    map.insert(key, value);
                }
                WriteOperation::Delete { key } => {
                    map.remove(&key);
                }
                WriteOperation::DeletePrefix { key_prefix } => {
                    let key_list = map
                        .range(get_interval(key_prefix))
                        .map(|x| x.0.to_vec())
                        .collect::<Vec<_>>();
                    for key in key_list {
                        map.remove(&key);
                    }
                }
            }
        }
        Ok(())
    }

    async fn clear_journal(&self) -> Result<(), MemoryStoreError> {
        Ok(())
    }
}

impl MemoryStore {
    /// Connects to a memory store. Creates it if it does not exist yet
    fn sync_maybe_create_and_connect(
        config: &MemoryStoreConfig,
        namespace: &str,
        root_key: &[u8],
        kill_on_drop: bool,
    ) -> Result<Self, MemoryStoreError> {
        let mut memory_stores = MEMORY_STORES.lock().expect("lock should not be poisoned");
        if !memory_stores.sync_exists(namespace) {
            memory_stores.sync_create(namespace);
        }
        memory_stores.sync_connect(config, namespace, root_key, kill_on_drop)
    }

    /// Creates a `MemoryStore` from a number of queries and a namespace.
    pub fn new(
        max_stream_queries: usize,
        namespace: &str,
        root_key: &[u8],
    ) -> Result<Self, MemoryStoreError> {
        let common_config = CommonStoreInternalConfig {
            max_concurrent_queries: None,
            max_stream_queries,
        };
        let config = MemoryStoreConfig { common_config };
        let kill_on_drop = false;
        MemoryStore::sync_maybe_create_and_connect(&config, namespace, root_key, kill_on_drop)
    }

    /// Creates a `MemoryStore` from a number of queries and a namespace for testing.
    #[cfg(with_testing)]
    pub fn new_for_testing(
        max_stream_queries: usize,
        namespace: &str,
        root_key: &[u8],
    ) -> Result<Self, MemoryStoreError> {
        let common_config = CommonStoreInternalConfig {
            max_concurrent_queries: None,
            max_stream_queries,
        };
        let config = MemoryStoreConfig { common_config };
        let kill_on_drop = true;
        MemoryStore::sync_maybe_create_and_connect(&config, namespace, root_key, kill_on_drop)
    }
}

impl AdminKeyValueStore for MemoryStore {
    type Config = MemoryStoreConfig;

    fn get_name() -> String {
        "memory".to_string()
    }

    async fn connect(
        config: &Self::Config,
        namespace: &str,
        root_key: &[u8],
    ) -> Result<Self, MemoryStoreError> {
        let mut memory_stores = MEMORY_STORES
            .lock()
            .expect("MEMORY_STORES lock should not be poisoned");
        let kill_on_drop = false;
        memory_stores.sync_connect(config, namespace, root_key, kill_on_drop)
    }

    fn clone_with_root_key(&self, root_key: &[u8]) -> Result<Self, MemoryStoreError> {
        let max_stream_queries = self.max_stream_queries;
        let common_config = CommonStoreInternalConfig {
            max_concurrent_queries: None,
            max_stream_queries,
        };
        let config = MemoryStoreConfig { common_config };
        let mut memory_stores = MEMORY_STORES
            .lock()
            .expect("MEMORY_STORES lock should not be poisoned");
        let kill_on_drop = self.kill_on_drop;
        let namespace = &self.namespace;
        memory_stores.sync_connect(&config, namespace, root_key, kill_on_drop)
    }

    async fn list_all(_config: &Self::Config) -> Result<Vec<String>, MemoryStoreError> {
        let memory_stores = MEMORY_STORES
            .lock()
            .expect("MEMORY_STORES lock should not be poisoned");
        Ok(memory_stores.sync_list_all())
    }

    async fn list_root_keys(
        _config: &Self::Config,
        namespace: &str,
    ) -> Result<Vec<Vec<u8>>, MemoryStoreError> {
        let memory_stores = MEMORY_STORES
            .lock()
            .expect("MEMORY_STORES lock should not be poisoned");
        Ok(memory_stores.sync_list_root_keys(namespace))
    }

    async fn exists(_config: &Self::Config, namespace: &str) -> Result<bool, MemoryStoreError> {
        let memory_stores = MEMORY_STORES
            .lock()
            .expect("MEMORY_STORES lock should not be poisoned");
        Ok(memory_stores.sync_exists(namespace))
    }

    async fn create(_config: &Self::Config, namespace: &str) -> Result<(), MemoryStoreError> {
        let mut memory_stores = MEMORY_STORES
            .lock()
            .expect("MEMORY_STORES lock should not be poisoned");
        memory_stores.sync_create(namespace);
        Ok(())
    }

    async fn delete(_config: &Self::Config, namespace: &str) -> Result<(), MemoryStoreError> {
        let mut memory_stores = MEMORY_STORES
            .lock()
            .expect("MEMORY_STORES lock should not be poisoned");
        memory_stores.sync_delete(namespace);
        Ok(())
    }
}

#[cfg(with_testing)]
impl TestKeyValueStore for MemoryStore {
    async fn new_test_config() -> Result<MemoryStoreConfig, MemoryStoreError> {
        let max_stream_queries = TEST_MEMORY_MAX_STREAM_QUERIES;
        let common_config = CommonStoreInternalConfig {
            max_concurrent_queries: None,
            max_stream_queries,
        };
        Ok(MemoryStoreConfig { common_config })
    }
}

/// Creates a test memory store for working.
#[cfg(with_testing)]
pub fn create_test_memory_store() -> MemoryStore {
    let namespace = generate_test_namespace();
    let root_key = &[];
    MemoryStore::new_for_testing(TEST_MEMORY_MAX_STREAM_QUERIES, &namespace, root_key).unwrap()
}

/// The error type for [`MemoryStore`].
#[derive(Error, Debug)]
pub enum MemoryStoreError {
    /// Serialization error with BCS.
    #[error(transparent)]
    BcsError(#[from] bcs::Error),

    /// The value is too large for the `MemoryStore`
    #[error("The value is too large for the MemoryStore")]
    TooLargeValue,

    /// The namespace does not exist
    #[error("The namespace does not exist")]
    NamespaceNotFound,
}

impl KeyValueStoreError for MemoryStoreError {
    const BACKEND: &'static str = "memory";
}