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
//! A basic Key-Value store for use with Crux
//!
//! `crux_kv` allows Crux apps to store and retrieve arbitrary data by asking the Shell to
//! persist the data using platform native capabilities (e.g. disk or web localStorage)

pub mod error;
pub mod value;

use serde::{Deserialize, Serialize};

use crux_core::capability::{CapabilityContext, Operation};
use crux_core::macros::Capability;

use error::KeyValueError;
use value::Value;

/// Supported operations
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum KeyValueOperation {
    /// Read bytes stored under a key
    Get { key: String },
    /// Write bytes under a key
    Set { key: String, value: Vec<u8> },
    /// Remove a key and its value
    Delete { key: String },
    /// Test if a key exists
    Exists { key: String },
    // List keys that start with a prefix, starting at the cursor
    ListKeys {
        /// The prefix to list keys for, or an empty string to list all keys
        prefix: String,
        /// The cursor to start listing from, or 0 to start from the beginning.
        /// If there are more keys to list, the response will include a new cursor.
        /// If there are no more keys, the response will include a cursor of 0.
        /// The cursor is opaque to the caller, and should be passed back to the
        /// `ListKeys` operation to continue listing keys.
        /// If the cursor is not found for the specified prefix, the response will include
        /// a `KeyValueError::CursorNotFound` error.
        cursor: u64,
    },
}

/// The result of an operation on the store.
///
/// Note: we can't use `Result` and `Option` here because generics are not currently
/// supported across the FFI boundary, when using the builtin typegen.
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
pub enum KeyValueResult {
    Ok { response: KeyValueResponse },
    Err { error: KeyValueError },
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum KeyValueResponse {
    /// Response to a `KeyValueOperation::Get`,
    /// returning the value stored under the key, which may be empty
    Get { value: Value },
    /// Response to a `KeyValueOperation::Set`,
    /// returning the value that was previously stored under the key, may be empty
    Set { previous: Value },
    /// Response to a `KeyValueOperation::Delete`,
    /// returning the value that was previously stored under the key, may be empty
    Delete { previous: Value },
    /// Response to a `KeyValueOperation::Exists`,
    /// returning whether the key is present in the store
    Exists { is_present: bool },
    /// Response to a `KeyValueOperation::ListKeys`,
    /// returning a list of keys that start with the prefix, and a cursor to continue listing
    /// if there are more keys
    ///
    /// Note: the cursor is 0 if there are no more keys
    ListKeys {
        keys: Vec<String>,
        /// The cursor to continue listing keys, or 0 if there are no more keys.
        /// If the cursor is not found for the specified prefix, the response should instead
        /// include a `KeyValueError::CursorNotFound` error.
        next_cursor: u64,
    },
}

impl Operation for KeyValueOperation {
    type Output = KeyValueResult;
}

#[derive(Capability)]
pub struct KeyValue<Ev> {
    context: CapabilityContext<KeyValueOperation, Ev>,
}

impl<Ev> Clone for KeyValue<Ev> {
    fn clone(&self) -> Self {
        Self {
            context: self.context.clone(),
        }
    }
}

impl<Ev> KeyValue<Ev>
where
    Ev: 'static,
{
    pub fn new(context: CapabilityContext<KeyValueOperation, Ev>) -> Self {
        Self { context }
    }

    /// Read a value under `key`, will dispatch the event with a
    /// `KeyValueResult::Get { value: Vec<u8> }` as payload
    pub fn get<F>(&self, key: String, make_event: F)
    where
        F: FnOnce(Result<Option<Vec<u8>>, KeyValueError>) -> Ev + Send + Sync + 'static,
    {
        self.context.spawn({
            let context = self.context.clone();
            async move {
                let response = get(&context, key).await;
                context.update_app(make_event(response));
            }
        });
    }

    /// Read a value under `key`, while in an async context. This is used together with
    /// [`crux_core::compose::Compose`].
    ///
    /// Returns the value stored under the key, or `None` if the key is not present.
    pub async fn get_async(&self, key: String) -> Result<Option<Vec<u8>>, KeyValueError> {
        get(&self.context, key).await
    }

    /// Set `key` to be the provided `value`. Typically the bytes would be
    /// a value serialized/deserialized by the app.
    ///
    /// Will dispatch the event with a `KeyValueResult::Set { previous: Vec<u8> }` as payload
    pub fn set<F>(&self, key: String, value: Vec<u8>, make_event: F)
    where
        F: FnOnce(Result<Option<Vec<u8>>, KeyValueError>) -> Ev + Send + Sync + 'static,
    {
        self.context.spawn({
            let context = self.context.clone();
            async move {
                let response = set(&context, key, value).await;
                context.update_app(make_event(response))
            }
        });
    }

    /// Set `key` to be the provided `value`, while in an async context. This is used together with
    /// [`crux_core::compose::Compose`].
    ///
    /// Returns the previous value stored under the key, if any.
    pub async fn set_async(
        &self,
        key: String,
        value: Vec<u8>,
    ) -> Result<Option<Vec<u8>>, KeyValueError> {
        set(&self.context, key, value).await
    }

    /// Remove a `key` and its value, will dispatch the event with a
    /// `KeyValueResult::Delete { previous: Vec<u8> }` as payload
    pub fn delete<F>(&self, key: String, make_event: F)
    where
        F: FnOnce(Result<Option<Vec<u8>>, KeyValueError>) -> Ev + Send + Sync + 'static,
    {
        self.context.spawn({
            let context = self.context.clone();
            async move {
                let response = delete(&context, key).await;
                context.update_app(make_event(response))
            }
        });
    }

    /// Remove a `key` and its value, while in an async context. This is used together with
    /// [`crux_core::compose::Compose`].
    ///
    /// Returns the previous value stored under the key, if any.
    pub async fn delete_async(&self, key: String) -> Result<Option<Vec<u8>>, KeyValueError> {
        delete(&self.context, key).await
    }

    /// Check to see if a `key` exists, will dispatch the event with a
    /// `KeyValueResult::Exists { is_present: bool }` as payload
    pub fn exists<F>(&self, key: String, make_event: F)
    where
        F: FnOnce(Result<bool, KeyValueError>) -> Ev + Send + Sync + 'static,
    {
        self.context.spawn({
            let context = self.context.clone();
            async move {
                let response = exists(&context, key).await;
                context.update_app(make_event(response))
            }
        });
    }

    /// Check to see if a `key` exists, while in an async context. This is used together with
    /// [`crux_core::compose::Compose`].
    ///
    /// Returns `true` if the key exists, `false` otherwise.
    pub async fn exists_async(&self, key: String) -> Result<bool, KeyValueError> {
        exists(&self.context, key).await
    }

    /// List keys that start with the provided `prefix`, starting from the provided `cursor`.
    /// Will dispatch the event with a `KeyValueResult::ListKeys { keys: Vec<String>, cursor: u64 }`
    /// as payload.
    ///
    /// A cursor is an opaque value that points to the first key in the next page of keys.
    ///
    /// If the cursor is not found for the specified prefix, the response will include
    /// a `KeyValueError::CursorNotFound` error.
    ///
    /// If the cursor is found the result will be a tuple of the keys and the next cursor
    /// (if there are more keys to list, the cursor will be non-zero, otherwise it will be zero)
    pub fn list_keys<F>(&self, prefix: String, cursor: u64, make_event: F)
    where
        F: FnOnce(Result<(Vec<String>, u64), KeyValueError>) -> Ev + Send + Sync + 'static,
    {
        self.context.spawn({
            let context = self.context.clone();
            async move {
                let response = list_keys(&context, prefix, cursor).await;
                context.update_app(make_event(response))
            }
        });
    }

    /// List keys that start with the provided `prefix`, starting from the provided `cursor`,
    /// while in an async context. This is used together with [`crux_core::compose::Compose`].
    ///
    /// A cursor is an opaque value that points to the first key in the next page of keys.
    ///
    /// If the cursor is not found for the specified prefix, the response will include
    /// a `KeyValueError::CursorNotFound` error.
    ///
    /// If the cursor is found the result will be a tuple of the keys and the next cursor
    /// (if there are more keys to list, the cursor will be non-zero, otherwise it will be zero)
    pub async fn list_keys_async(
        &self,
        prefix: String,
        cursor: u64,
    ) -> Result<(Vec<String>, u64), KeyValueError> {
        list_keys(&self.context, prefix, cursor).await
    }
}

async fn get<Ev: 'static>(
    context: &CapabilityContext<KeyValueOperation, Ev>,
    key: String,
) -> Result<Option<Vec<u8>>, KeyValueError> {
    context
        .request_from_shell(KeyValueOperation::Get { key })
        .await
        .unwrap_get()
}

async fn set<Ev: 'static>(
    context: &CapabilityContext<KeyValueOperation, Ev>,
    key: String,
    value: Vec<u8>,
) -> Result<Option<Vec<u8>>, KeyValueError> {
    context
        .request_from_shell(KeyValueOperation::Set { key, value })
        .await
        .unwrap_set()
}

async fn delete<Ev: 'static>(
    context: &CapabilityContext<KeyValueOperation, Ev>,
    key: String,
) -> Result<Option<Vec<u8>>, KeyValueError> {
    context
        .request_from_shell(KeyValueOperation::Delete { key })
        .await
        .unwrap_delete()
}

async fn exists<Ev: 'static>(
    context: &CapabilityContext<KeyValueOperation, Ev>,
    key: String,
) -> Result<bool, KeyValueError> {
    context
        .request_from_shell(KeyValueOperation::Exists { key })
        .await
        .unwrap_exists()
}

async fn list_keys<Ev: 'static>(
    context: &CapabilityContext<KeyValueOperation, Ev>,
    prefix: String,
    cursor: u64,
) -> Result<(Vec<String>, u64), KeyValueError> {
    context
        .request_from_shell(KeyValueOperation::ListKeys { prefix, cursor })
        .await
        .unwrap_list_keys()
}

impl KeyValueResult {
    fn unwrap_get(self) -> Result<Option<Vec<u8>>, KeyValueError> {
        match self {
            KeyValueResult::Ok { response } => match response {
                KeyValueResponse::Get { value } => Ok(value.into()),
                _ => {
                    panic!("attempt to convert KeyValueResponse other than Get to Option<Vec<u8>>")
                }
            },
            KeyValueResult::Err { error } => Err(error.clone()),
        }
    }

    fn unwrap_set(self) -> Result<Option<Vec<u8>>, KeyValueError> {
        match self {
            KeyValueResult::Ok { response } => match response {
                KeyValueResponse::Set { previous } => Ok(previous.into()),
                _ => {
                    panic!("attempt to convert KeyValueResponse other than Set to Option<Vec<u8>>")
                }
            },
            KeyValueResult::Err { error } => Err(error.clone()),
        }
    }

    fn unwrap_delete(self) -> Result<Option<Vec<u8>>, KeyValueError> {
        match self {
            KeyValueResult::Ok { response } => match response {
                KeyValueResponse::Delete { previous } => Ok(previous.into()),
                _ => panic!(
                    "attempt to convert KeyValueResponse other than Delete to Option<Vec<u8>>"
                ),
            },
            KeyValueResult::Err { error } => Err(error.clone()),
        }
    }

    fn unwrap_exists(self) -> Result<bool, KeyValueError> {
        match self {
            KeyValueResult::Ok { response } => match response {
                KeyValueResponse::Exists { is_present } => Ok(is_present),
                _ => panic!("attempt to convert KeyValueResponse other than Exists to bool"),
            },
            KeyValueResult::Err { error } => Err(error.clone()),
        }
    }

    fn unwrap_list_keys(self) -> Result<(Vec<String>, u64), KeyValueError> {
        match self {
            KeyValueResult::Ok { response } => match response {
                KeyValueResponse::ListKeys {
                    keys,
                    next_cursor: cursor,
                } => Ok((keys, cursor)),
                _ => panic!(
                    "attempt to convert KeyValueResponse other than ListKeys to (Vec<String>, u64)"
                ),
            },
            KeyValueResult::Err { error } => Err(error.clone()),
        }
    }
}

#[cfg(test)]
mod tests;