anystore 0.2.1

Polymorphic, type-safe, composable async API for arbitrary stores
Documentation
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
use std::sync::Arc;

use futures::{stream, StreamExt, TryStreamExt};
use tokio::sync::{RwLock, RwLockReadGuard};

use serde_json::Value;

use crate::{
    address::{
        primitive::Existence,
        traits::{
            AddressableGet, AddressableInsert, AddressableList, AddressableSet, AddressableTree,
            BranchOrLeaf,
        },
        Address, Addressable, SubAddress,
    },
    location::Location,
    store::{Store, StoreResult},
    stores::json::paths::*,
    stores::json::traverse::*,
};
// todo: stop using anyhow, implement wrapper error
use anyhow::anyhow;

// #[derive(Debug, Display, Error)]
type LocatedJsonStoreError = anyhow::Error;

// #[derive(Debug, Error)]
// pub enum LocatedJsonStoreError {
//     #[error("StoreError({0})")]
//     StoreError(dyn std::error::Error),
//     // #[error("CustomError({0})")]
//     // CustomError(String),

//     // #[error("SerdeError({0})")]
//     // SerdeError(
//     //     #[backtrace]
//     //     #[source]
//     //     serde_json::Error,
//     // ),

//     // #[error("ParseError({0})")]
//     // ParseError(
//     //     #[backtrace]
//     //     #[source]
//     //     JsonPathParseError,
//     // ),

//     // #[error("TraverseError({0})")]
//     // TraverseError(
//     //     #[backtrace]
//     //     #[source]
//     //     JsonTraverseError,
//     // ),
// }

/// Turn any store of Strings into JSON store
///
#[cfg_attr(not(all(feature = "json", feature = "fs")), doc = "```ignore")]
#[cfg_attr(all(feature = "json", feature = "fs"), doc = "```")]
/// use serde_json::json;
///
/// use anystore::stores::located::json::LocatedJsonStore;
/// use anystore::stores::fs::FileSystemStore;
///
/// use anystore::store::StoreEx;
/// use anystore::address::primitive::Existence;
///
///
/// # tokio_test::block_on(async {
///     let _ = tokio::fs::remove_file("test.json").await;
///
///     let fileloc = FileSystemStore::here()?.path("test.json")?;
///
///     assert_eq!(fileloc.get::<Existence>().await?, None);
///     assert_eq!(fileloc.get::<Existence>().await?, None);
///
///     let json_there = LocatedJsonStore::new(fileloc.clone());
///
///     let l = json_there.path("sub.key")?;
///
///     l.set(&Some(json!("wow"))).await?;
///
///     assert_eq!(fileloc.get::<Existence>().await?, Some(Existence));
///
///     assert_eq!(l.get().await?, Some(json!("wow")));
///
///     assert_eq!(fileloc.get::<String>().await?, Some(serde_json::to_string(&json!({"sub": {"key": "wow"}}))?));
///
///     tokio::fs::remove_file("test.json").await?;
///
/// #    Ok::<(), anyhow::Error>(())
/// # }).unwrap()
/// ```
#[derive(Clone)]
pub struct LocatedJsonStore<A: Address, S: Addressable<A>> {
    pub pretty: bool,

    location: Arc<RwLock<Location<A, S>>>,
}

impl<A: Address, S: Addressable<A>> LocatedJsonStore<A, S>
where
    S::Error: std::error::Error,
{
    /// Wrap a store of Strings into a JSON store
    pub fn new(location: Location<A, S>) -> Self {
        LocatedJsonStore {
            location: Arc::new(RwLock::new(location)),
            pretty: false,
        }
    }

    /// Wrap a store of Strings into a JSON store,
    /// that formats JSON with pretty print
    pub fn new_pretty(location: Location<A, S>) -> Self {
        LocatedJsonStore {
            location: Arc::new(RwLock::new(location)),
            pretty: true,
        }
    }

    async fn lock_read_value(&self) -> StoreResult<(RwLockReadGuard<()>, Value), Self>
    where
        S: AddressableGet<String, A>,
    {
        let loc = self.location.read().await;

        let value = loc
            .get::<String>()
            .await?
            // .map_err(LocatedJsonStoreError::StoreError)
            .map(|s| serde_json::from_str(&s))
            .transpose()?
            .unwrap_or(Value::Null);

        let lock = RwLockReadGuard::map(loc, |_| &());

        Ok((lock, value))
    }

    async fn change_value<R, F: FnOnce(&mut Value) -> R>(&self, mutator: F) -> StoreResult<R, Self>
    where
        S: AddressableGet<String, A> + AddressableSet<String, A>,
    {
        let loc = self.location.write().await;

        let str = loc.get::<String>().await?;

        // .map_err(LocatedJsonStoreError::StoreError)
        let mut value = str
            .map(|s| serde_json::from_str(&s))
            .transpose()?
            .unwrap_or(Value::Null);

        let result = mutator(&mut value);

        let stored = if self.pretty {
            serde_json::to_string_pretty(&value)
        } else {
            serde_json::to_string(&value)
        }?;

        loc.set(&Some(stored))
            .await
            // .map_err(LocatedJsonStoreError::StoreError)
            ?;

        Ok(result)
    }
}

impl<A: Address, S: Addressable<A>> Store for LocatedJsonStore<A, S> {
    type Error = LocatedJsonStoreError;
    type RootAddress = JsonPath;
}

impl<A: Address, S: Addressable<A>> Addressable<JsonPath> for LocatedJsonStore<A, S> {
    type DefaultValue = Value;
}

impl<A: Address, S: AddressableGet<String, A>> AddressableGet<Value, JsonPath>
    for LocatedJsonStore<A, S>
where
    <S as Store>::Error: std::error::Error,
{
    async fn addr_get(&self, addr: &JsonPath) -> StoreResult<Option<Value>, Self> {
        let (_, value) = self.lock_read_value().await?;

        return Ok(get_pathvalue(&value, &addr.0[..])?
            // .map_err(LocatedJsonStoreError::TraverseError)
            .cloned());
    }
}

impl<A: Address, S: AddressableGet<String, A> + AddressableSet<String, A>>
    AddressableSet<Value, JsonPath> for LocatedJsonStore<A, S>
where
    <S as Store>::Error: std::error::Error,
{
    async fn set_addr(&self, addr: &JsonPath, value: &Option<Value>) -> StoreResult<(), Self> {
        self.change_value(|cur| {
            let addr = &addr.0;

            match value {
                // Set
                Some(value) => {
                    let insert_at = get_mut_pathvalue(cur, &addr[..], true)?.unwrap();

                    *insert_at = value.clone();

                    Ok(())
                }

                // Delete
                None => {
                    let Some((last, path)) = addr.split_last() else {
                    *cur = Value::Null;
                    return Ok(());
                };

                    let delete_from = get_mut_pathvalue(cur, path, false)?;

                    match delete_from {
                        None => Ok(()),
                        Some(Value::Null) => Ok(()),

                        Some(delete_from) => match (last, delete_from) {
                            (JsonPathPart::Key(key), Value::Object(obj)) => {
                                obj.remove(key);
                                Ok(())
                            }
                            (JsonPathPart::Index(ix), Value::Array(arr)) => {
                                if arr.len() <= *ix {
                                } else if arr.len() == *ix {
                                    arr.pop();
                                } else {
                                    arr[*ix] = Value::Null;
                                }

                                Ok(())
                            }
                            (_, value) => {
                                Err(anyhow!("Incompatible value at key {last}: {value}",))
                            }
                        },
                    }
                }
            }
        })
        .await?
    }
}

impl<A: Address, S: AddressableGet<String, A>> AddressableGet<Existence, JsonPath>
    for LocatedJsonStore<A, S>
where
    <S as Store>::Error: std::error::Error,
{
    async fn addr_get(&self, addr: &JsonPath) -> StoreResult<Option<Existence>, Self> {
        let v: Option<Value> =
            <LocatedJsonStore<A, S> as AddressableGet<Value, JsonPath>>::addr_get(self, addr)
                .await?;

        Ok(v.map(|_| Existence))
    }
}

impl<'a, A: Address, S: 'a + AddressableGet<String, A>> AddressableList<'a, JsonPath>
    for LocatedJsonStore<A, S>
where
    S::Error: std::error::Error,
{
    type AddedAddress = JsonPathPart;

    type ItemAddress = JsonPath;

    fn list(&self, addr: &JsonPath) -> Self::ListOfAddressesStream {
        let this = self.clone();
        let addr = addr.clone();

        stream::once(async move {
            let value = this.lock_read_value().await?.1;

            let val: StoreResult<_, Self> =
                try { get_pathvalue(&value, &addr.0[..])?.ok_or(anyhow!("Path doesn't exist"))? };

            let vec = match val {
                Ok(Value::Array(arr)) => (0..arr.len())
                    .map(JsonPathPart::Index)
                    .map(|i| Ok((i.clone(), addr.clone().sub(i))))
                    .collect(),
                Ok(Value::Object(obj)) => obj
                    .keys()
                    .map(|k| JsonPathPart::Key(k.to_owned()))
                    .map(|i| Ok((i.clone(), addr.clone().sub(i))))
                    .collect(),
                Err(e) => vec![Err(e)],
                _ => vec![Err(anyhow!("Can't list: {val:?}"))],
            };

            Ok::<_, Self::Error>(stream::iter(vec.into_iter()))
        })
        .try_flatten()
        .boxed_local()
    }
}

impl<'a, A: Address, S: 'a + AddressableGet<String, A>> AddressableTree<'a, JsonPath, JsonPath>
    for LocatedJsonStore<A, S>
where
    S::Error: std::error::Error,
{
    async fn branch_or_leaf(
        &self,
        addr: JsonPath,
    ) -> StoreResult<BranchOrLeaf<JsonPath, JsonPath>, Self> {
        let value = self.lock_read_value().await?.1;
        let val = get_pathvalue(&value, &addr.0[..])?.ok_or(anyhow!("Path doesn't exist"))?;

        Ok(match val {
            Value::Array(_) => BranchOrLeaf::Branch(addr),
            Value::Object(_) => BranchOrLeaf::Branch(addr),

            _ => BranchOrLeaf::Leaf(addr),
        })
    }
}

impl<'a, A: Address, S: 'a + AddressableGet<String, A> + AddressableSet<String, A>>
    AddressableInsert<'a, Value, JsonPath> for LocatedJsonStore<A, S>
where
    S::Error: std::error::Error,
{
    fn insert(&self, addr: &JsonPath, items: Vec<Value>) -> Self::ListOfAddressesStream {
        let addr = addr.clone();
        let this = self.clone();

        stream::once(async move {
            let addr = addr.clone();
            let path = addr.0.clone();
            let paths = this
                .change_value(move |cur| {
                    let insert_at = get_mut_pathvalue(cur, &path[..], true)?.unwrap();

                    if insert_at.is_null() {
                        *insert_at = Value::Array(vec![]);
                    }

                    let arr = match insert_at {
                        Value::Array(at) => at,
                        _ => {
                            return Err::<_, Self::Error>(anyhow!(
                                "Can't insert into non-array value"
                            ))
                        }
                    };

                    let ixes = arr.len()..arr.len() + items.len();

                    arr.extend(items);

                    Ok(ixes
                        .map(JsonPathPart::Index)
                        .map(move |i| (i.clone(), addr.clone().sub(i))))
                })
                .await??;

            Ok::<_, Self::Error>(stream::iter(paths.map(Ok)))
        })
        .try_flatten()
        .boxed_local()
    }
}

#[cfg(test)]
#[cfg(feature = "json")]
mod test {
    use serde_json::json;

    use crate::{store::StoreEx, stores::json::json_value_store};
    use futures::TryStreamExt;

    #[tokio::test]
    async fn test() -> Result<(), anyhow::Error> {
        let root = json_value_store(json!({
            "test": {"a": 2},
            "list": [{"a":8}, {"b":2}, {"a": 3}]
        }))?
        .root();

        let vc: Vec<_> = root
            .clone()
            .path("list")?
            .insert(vec![json!({"a": 1}), json!({"b": 2}), json!({"a": 3})])
            .try_collect()
            .await?;

        assert_eq!(vc.len(), 3);
        assert_eq!(vc[0].0.to_string(), "[3]");
        assert_eq!(vc[1].1.to_string(), "list[4]");

        let vc: Vec<_> = root
            .path("test.deeper")?
            .insert(vec![json!({"a": 1}), json!({"b": 2})])
            .try_collect()
            .await?;

        assert_eq!(vc.len(), 2);
        assert_eq!(vc[0].0.to_string(), "[0]");
        assert_eq!(vc[1].1.to_string(), "test.deeper[1]");

        Ok(())
    }
}