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
// Copyright (c) Zefchain Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

//! Functions and types to interface with the system API available to application views.

#[cfg(with_testing)]
use std::sync::Arc;

use linera_base::ensure;
use linera_views::{
    batch::Batch,
    store::{ReadableKeyValueStore, WithError, WritableKeyValueStore},
};
use thiserror::Error;

#[cfg(with_testing)]
use super::mock_key_value_store::MockKeyValueStore;
use crate::{
    contract::wit::{
        base_runtime_api::{self as contract_wit},
        contract_runtime_api::{self, WriteOperation},
    },
    service::wit::base_runtime_api as service_wit,
    util::yield_once,
};

/// We need to have a maximum key size that handles all possible underlying
/// sizes. The constraint so far is DynamoDB which has a key length of 1024.
/// That key length is decreased by 4 due to the use of a value splitting.
/// Then the [`KeyValueStore`] needs to handle some base key and so we
/// reduce to 900. Depending on the size, the error can occur in `system_api`
/// or in the `KeyValueStoreView`.
const MAX_KEY_SIZE: usize = 900;

/// A type to interface with the key value storage provided to applications.
#[derive(Clone)]
pub struct KeyValueStore {
    wit_api: WitInterface,
}

#[cfg_attr(with_testing, allow(dead_code))]
impl KeyValueStore {
    /// Returns a [`KeyValueStore`] that uses the contract WIT interface.
    pub(crate) fn for_contracts() -> Self {
        KeyValueStore {
            wit_api: WitInterface::Contract,
        }
    }

    /// Returns a [`KeyValueStore`] that uses the service WIT interface.
    pub(crate) fn for_services() -> Self {
        KeyValueStore {
            wit_api: WitInterface::Service,
        }
    }

    /// Returns a new [`KeyValueStore`] that just keeps the storage contents in memory.
    #[cfg(with_testing)]
    pub fn mock() -> Self {
        KeyValueStore {
            wit_api: WitInterface::Mock {
                store: Arc::new(MockKeyValueStore::default()),
                read_only: true,
            },
        }
    }

    /// Returns a mocked [`KeyValueStore`] that shares the memory storage with this instance but
    /// allows write operations.
    #[cfg(with_testing)]
    pub fn to_mut(&self) -> Self {
        let WitInterface::Mock { store, .. } = &self.wit_api else {
            panic!("Real `KeyValueStore` should not be used in unit tests");
        };

        KeyValueStore {
            wit_api: WitInterface::Mock {
                store: store.clone(),
                read_only: false,
            },
        }
    }
}

impl WithError for KeyValueStore {
    type Error = KeyValueStoreError;
}

/// The error type for [`KeyValueStore`] operations.
#[derive(Error, Debug)]
pub enum KeyValueStoreError {
    /// Key too long
    #[error("Key too long")]
    KeyTooLong,

    /// BCS serialization error.
    #[error(transparent)]
    BcsError(#[from] bcs::Error),
}

impl linera_views::store::KeyValueStoreError for KeyValueStoreError {
    const BACKEND: &'static str = "key_value_store";
}

impl ReadableKeyValueStore for KeyValueStore {
    // The KeyValueStore of the system_api does not have limits
    // on the size of its values.
    const MAX_KEY_SIZE: usize = MAX_KEY_SIZE;
    type Keys = Vec<Vec<u8>>;
    type KeyValues = Vec<(Vec<u8>, Vec<u8>)>;

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

    async fn contains_key(&self, key: &[u8]) -> Result<bool, KeyValueStoreError> {
        ensure!(
            key.len() <= Self::MAX_KEY_SIZE,
            KeyValueStoreError::KeyTooLong
        );
        let promise = self.wit_api.contains_key_new(key);
        yield_once().await;
        Ok(self.wit_api.contains_key_wait(promise))
    }

    async fn contains_keys(&self, keys: Vec<Vec<u8>>) -> Result<Vec<bool>, KeyValueStoreError> {
        for key in &keys {
            ensure!(
                key.len() <= Self::MAX_KEY_SIZE,
                KeyValueStoreError::KeyTooLong
            );
        }
        let promise = self.wit_api.contains_keys_new(&keys);
        yield_once().await;
        Ok(self.wit_api.contains_keys_wait(promise))
    }

    async fn read_multi_values_bytes(
        &self,
        keys: Vec<Vec<u8>>,
    ) -> Result<Vec<Option<Vec<u8>>>, KeyValueStoreError> {
        for key in &keys {
            ensure!(
                key.len() <= Self::MAX_KEY_SIZE,
                KeyValueStoreError::KeyTooLong
            );
        }
        let promise = self.wit_api.read_multi_values_bytes_new(&keys);
        yield_once().await;
        Ok(self.wit_api.read_multi_values_bytes_wait(promise))
    }

    async fn read_value_bytes(&self, key: &[u8]) -> Result<Option<Vec<u8>>, KeyValueStoreError> {
        ensure!(
            key.len() <= Self::MAX_KEY_SIZE,
            KeyValueStoreError::KeyTooLong
        );
        let promise = self.wit_api.read_value_bytes_new(key);
        yield_once().await;
        Ok(self.wit_api.read_value_bytes_wait(promise))
    }

    async fn find_keys_by_prefix(
        &self,
        key_prefix: &[u8],
    ) -> Result<Self::Keys, KeyValueStoreError> {
        ensure!(
            key_prefix.len() <= Self::MAX_KEY_SIZE,
            KeyValueStoreError::KeyTooLong
        );
        let promise = self.wit_api.find_keys_new(key_prefix);
        yield_once().await;
        Ok(self.wit_api.find_keys_wait(promise))
    }

    async fn find_key_values_by_prefix(
        &self,
        key_prefix: &[u8],
    ) -> Result<Self::KeyValues, KeyValueStoreError> {
        ensure!(
            key_prefix.len() <= Self::MAX_KEY_SIZE,
            KeyValueStoreError::KeyTooLong
        );
        let promise = self.wit_api.find_key_values_new(key_prefix);
        yield_once().await;
        Ok(self.wit_api.find_key_values_wait(promise))
    }
}

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

    async fn write_batch(&self, batch: Batch) -> Result<(), KeyValueStoreError> {
        self.wit_api.write_batch(batch);
        Ok(())
    }

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

/// Which system API should be used to interface with the storage.
#[derive(Clone)]
#[cfg_attr(with_testing, allow(dead_code))]
enum WitInterface {
    /// The contract system API.
    Contract,
    /// The service system API.
    Service,
    #[cfg(with_testing)]
    /// A mock system API.
    Mock {
        store: Arc<MockKeyValueStore>,
        read_only: bool,
    },
}

impl WitInterface {
    /// Creates a promise for testing if a key exist in the key-value store
    fn contains_key_new(&self, key: &[u8]) -> u32 {
        match self {
            WitInterface::Contract => contract_wit::contains_key_new(key),
            WitInterface::Service => service_wit::contains_key_new(key),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.contains_key_new(key),
        }
    }

    /// Resolves a promise for testing if a key exist in the key-value store
    fn contains_key_wait(&self, promise: u32) -> bool {
        match self {
            WitInterface::Contract => contract_wit::contains_key_wait(promise),
            WitInterface::Service => service_wit::contains_key_wait(promise),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.contains_key_wait(promise),
        }
    }

    /// Creates a promise for testing if multiple keys exist in the key-value store
    fn contains_keys_new(&self, keys: &[Vec<u8>]) -> u32 {
        match self {
            WitInterface::Contract => contract_wit::contains_keys_new(keys),
            WitInterface::Service => service_wit::contains_keys_new(keys),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.contains_keys_new(keys),
        }
    }

    /// Resolves a promise for testing if multiple keys exist in the key-value store
    fn contains_keys_wait(&self, promise: u32) -> Vec<bool> {
        match self {
            WitInterface::Contract => contract_wit::contains_keys_wait(promise),
            WitInterface::Service => service_wit::contains_keys_wait(promise),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.contains_keys_wait(promise),
        }
    }

    /// Creates a promise for reading multiple keys in the key-value store
    fn read_multi_values_bytes_new(&self, keys: &[Vec<u8>]) -> u32 {
        match self {
            WitInterface::Contract => contract_wit::read_multi_values_bytes_new(keys),
            WitInterface::Service => service_wit::read_multi_values_bytes_new(keys),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.read_multi_values_bytes_new(keys),
        }
    }

    /// Resolves a promise for reading multiple keys in the key-value store
    fn read_multi_values_bytes_wait(&self, promise: u32) -> Vec<Option<Vec<u8>>> {
        match self {
            WitInterface::Contract => contract_wit::read_multi_values_bytes_wait(promise),
            WitInterface::Service => service_wit::read_multi_values_bytes_wait(promise),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.read_multi_values_bytes_wait(promise),
        }
    }

    /// Creates a promise for reading a key in the key-value store
    fn read_value_bytes_new(&self, key: &[u8]) -> u32 {
        match self {
            WitInterface::Contract => contract_wit::read_value_bytes_new(key),
            WitInterface::Service => service_wit::read_value_bytes_new(key),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.read_value_bytes_new(key),
        }
    }

    /// Resolves a promise for reading a key in the key-value store
    fn read_value_bytes_wait(&self, promise: u32) -> Option<Vec<u8>> {
        match self {
            WitInterface::Contract => contract_wit::read_value_bytes_wait(promise),
            WitInterface::Service => service_wit::read_value_bytes_wait(promise),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.read_value_bytes_wait(promise),
        }
    }

    /// Creates a promise for finding keys having a specified prefix in the key-value store
    fn find_keys_new(&self, key_prefix: &[u8]) -> u32 {
        match self {
            WitInterface::Contract => contract_wit::find_keys_new(key_prefix),
            WitInterface::Service => service_wit::find_keys_new(key_prefix),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.find_keys_new(key_prefix),
        }
    }

    /// Resolves a promise for finding keys having a specified prefix in the key-value store
    fn find_keys_wait(&self, promise: u32) -> Vec<Vec<u8>> {
        match self {
            WitInterface::Contract => contract_wit::find_keys_wait(promise),
            WitInterface::Service => service_wit::find_keys_wait(promise),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.find_keys_wait(promise),
        }
    }

    /// Creates a promise for finding the key/values having a specified prefix in the key-value store
    fn find_key_values_new(&self, key_prefix: &[u8]) -> u32 {
        match self {
            WitInterface::Contract => contract_wit::find_key_values_new(key_prefix),
            WitInterface::Service => service_wit::find_key_values_new(key_prefix),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.find_key_values_new(key_prefix),
        }
    }

    /// Resolves a promise for finding the key/values having a specified prefix in the key-value store
    fn find_key_values_wait(&self, promise: u32) -> Vec<(Vec<u8>, Vec<u8>)> {
        match self {
            WitInterface::Contract => contract_wit::find_key_values_wait(promise),
            WitInterface::Service => service_wit::find_key_values_wait(promise),
            #[cfg(with_testing)]
            WitInterface::Mock { store, .. } => store.find_key_values_wait(promise),
        }
    }

    /// Calls the `write_batch` WIT function.
    fn write_batch(&self, batch: Batch) {
        match self {
            WitInterface::Contract => {
                let batch_operations = batch
                    .operations
                    .into_iter()
                    .map(WriteOperation::from)
                    .collect::<Vec<_>>();

                contract_runtime_api::write_batch(&batch_operations);
            }
            WitInterface::Service => panic!("Attempt to modify storage from a service"),
            #[cfg(with_testing)]
            WitInterface::Mock {
                store,
                read_only: false,
            } => {
                store.write_batch(batch);
            }
            #[cfg(with_testing)]
            WitInterface::Mock {
                read_only: true, ..
            } => {
                panic!("Attempt to modify storage from a service")
            }
        }
    }
}

/// Implementation of [`linera_views::context::Context`] to be used for data storage
/// by Linera applications.
pub type ViewStorageContext = linera_views::context::ViewContext<(), KeyValueStore>;

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_key_value_store_mock() -> anyhow::Result<()> {
        // Create a mock key-value store for testing
        let store = KeyValueStore::mock();
        let mock_store = store.to_mut();

        // Check if key exists
        let is_key_existing = mock_store.contains_key(b"foo").await?;
        assert!(!is_key_existing);

        // Check if keys exist
        let is_keys_existing = mock_store
            .contains_keys(vec![b"foo".to_vec(), b"bar".to_vec()])
            .await?;
        assert!(!is_keys_existing[0]);
        assert!(!is_keys_existing[1]);

        // Read and write values
        let mut batch = Batch::new();
        batch.put_key_value(b"foo".to_vec(), &32_u128)?;
        batch.put_key_value(b"bar".to_vec(), &42_u128)?;
        mock_store.write_batch(batch).await?;

        let is_key_existing = mock_store.contains_key(b"foo").await?;
        assert!(is_key_existing);

        let value = mock_store.read_value(b"foo").await?;
        assert_eq!(value, Some(32_u128));

        let value = mock_store.read_value(b"bar").await?;
        assert_eq!(value, Some(42_u128));

        Ok(())
    }
}