object-rainbow-store 0.0.0-a.10

storage abstraction for object-rainbow
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
use std::{
    ops::{Deref, DerefMut},
    pin::Pin,
    sync::Arc,
};

use object_rainbow::{
    Address, ExtraFor, FullHash, Hash, Inline, InlineOutput, ListHashes, MaybeHasNiche, Object,
    ObjectHashes, OptionalHash, Parse, ParseInline, PointInput, PointVisitor, Resolve, Singular,
    SingularFetch, Size, Tagged, ToOutput, Topological, Traversible, assert_impl,
    derive_for_wrapped,
};
use object_rainbow_point::{Extras, Point};

pub trait RainbowFuture: Send + Future<Output = object_rainbow::Result<Self::T>> {
    type T;
}

impl<F: Send + Future<Output = object_rainbow::Result<T>>, T> RainbowFuture for F {
    type T = T;
}

struct StoreVisitor<'a, 'x, S: ?Sized> {
    store: &'a S,
    futures: &'x mut Vec<Pin<Box<dyn 'a + Send + Future<Output = object_rainbow::Result<()>>>>>,
}

impl<'a, 'x, S: RainbowStore> PointVisitor for StoreVisitor<'a, 'x, S> {
    fn visit<T: Traversible>(&mut self, point: &(impl 'static + SingularFetch<T = T> + Clone)) {
        let point = point.clone();
        let store = self.store;
        self.futures.push(Box::pin(async move {
            store.save_point(&point).await.map(|_| ())
        }));
    }
}

struct StoreResolve<S> {
    store: S,
}

impl<S: 'static + Send + RainbowStore> Resolve for StoreResolve<S> {
    fn resolve<'a>(
        &'a self,
        address: Address,
        this: &'a Arc<dyn Resolve>,
    ) -> object_rainbow::FailFuture<'a, object_rainbow::ByteNode> {
        Box::pin(async move {
            let bytes = self.store.fetch(address.hash).await?.as_ref().to_vec();
            Ok((bytes, this.clone()))
        })
    }

    fn resolve_data(&'_ self, address: Address) -> object_rainbow::FailFuture<'_, Vec<u8>> {
        Box::pin(async move {
            let bytes = self.store.fetch(address.hash).await?.as_ref().to_vec();
            Ok(bytes)
        })
    }
}

#[derive_for_wrapped]
pub trait RainbowStore: 'static + Send + Sync + Clone {
    fn saved_point<T: 'static + Traversible, Extra: 'static + Send + Sync + Clone + ExtraFor<T>>(
        &self,
        point: &Point<T>,
        extra: Extra,
    ) -> impl RainbowFuture<T = Point<T>> {
        async {
            self.save_point(point).await?;
            Ok(point.with_resolve(self.resolve(), extra))
        }
    }
    fn save_point(&self, point: &impl SingularFetch<T: Traversible>) -> impl RainbowFuture<T = ()> {
        async {
            if !self.contains(point.hash()).await? {
                self.save_object(&point.fetch().await?).await?;
            }
            Ok(())
        }
    }
    fn save_topology(&self, object: &impl Topological) -> impl RainbowFuture<T = ()> {
        let mut futures = Vec::with_capacity(object.point_count());
        object.traverse(&mut StoreVisitor {
            store: self,
            futures: &mut futures,
        });
        async {
            for future in futures {
                future.await?;
            }
            Ok(())
        }
    }
    fn save_object(&self, object: &impl Traversible) -> impl RainbowFuture<T = ()> {
        async {
            self.save_topology(object).await?;
            self.save_data(object.hashes(), &object.vec()).await?;
            Ok(())
        }
    }
    fn resolve(&self) -> Arc<dyn Resolve> {
        Arc::new(StoreResolve {
            store: self.clone(),
        })
    }
    fn point_extra<T: 'static + FullHash, Extra: 'static + Send + Sync + Clone + ExtraFor<T>>(
        &self,
        hash: Hash,
        extra: Extra,
    ) -> Point<T> {
        Point::from_address_extra(Address::from_hash(hash), self.resolve(), extra)
    }
    fn point<T: Object>(&self, hash: Hash) -> Point<T> {
        self.point_extra(hash, ())
    }
    fn save_data(&self, hashes: ObjectHashes, data: &[u8]) -> impl RainbowFuture<T = ()>;
    fn contains(&self, hash: Hash) -> impl RainbowFuture<T = bool>;
    fn fetch(&self, hash: Hash)
    -> impl RainbowFuture<T = impl 'static + Send + Sync + AsRef<[u8]>>;
}

pub trait RainbowStoreMut: RainbowStore {
    fn create_ref(
        &self,
        hash: Hash,
    ) -> impl RainbowFuture<T = impl 'static + Send + Sync + AsRef<str>> {
        let _ = hash;
        async { Err::<String, _>(object_rainbow::Error::Unimplemented) }
    }
    fn update_ref(
        &self,
        key: &str,
        old: Option<OptionalHash>,
        hash: Hash,
    ) -> impl RainbowFuture<T = ()>;
    fn fetch_ref(&self, key: &str) -> impl RainbowFuture<T = OptionalHash>;
    fn ref_exists(&self, key: &str) -> impl RainbowFuture<T = bool>;
    fn store_ref_raw<
        T: Object<Extra>,
        K: Send + Sync + AsRef<str>,
        Extra: 'static + Send + Sync + Clone,
    >(
        &self,
        key: K,
        point: Point<T>,
        extra: Extra,
    ) -> StoreRef<Self, K, T, Extra> {
        StoreRef {
            store: self.clone(),
            key,
            old: point.hash().into(),
            point,
            extra,
        }
    }
}

#[derive(Clone)]
pub struct StoreMut<S, Extra = ()> {
    store: S,
    extra: Extra,
}

impl<S> StoreMut<S> {
    pub const fn new(store: S) -> Self {
        Self::new_extra(store, ())
    }
}

impl<S, Extra> StoreMut<S, Extra> {
    pub const fn new_extra(store: S, extra: Extra) -> Self {
        Self { store, extra }
    }
}

impl<S: RainbowStoreMut, Extra: 'static + Send + Sync + Clone> StoreMut<S, Extra> {
    pub async fn exists<K: Send + Sync + AsRef<str>>(
        &self,
        key: K,
    ) -> object_rainbow::Result<bool> {
        self.store.ref_exists(key.as_ref()).await
    }

    pub async fn create<T: Object<Extra>>(
        &self,
        point: Point<T>,
    ) -> object_rainbow::Result<StoreRef<S, impl 'static + Send + Sync + AsRef<str>, T, Extra>>
    {
        let point = self.store.saved_point(&point, self.extra.clone()).await?;
        let key = self.store.create_ref(point.hash()).await?;
        Ok(self.store.store_ref_raw(key, point, self.extra.clone()))
    }

    pub async fn update<T: Object<Extra>, K: Send + Sync + AsRef<str>>(
        &self,
        key: K,
        point: Point<T>,
    ) -> object_rainbow::Result<StoreRef<S, K, T, Extra>> {
        let point = self.store.saved_point(&point, self.extra.clone()).await?;
        self.store
            .update_ref(key.as_ref(), None, point.hash())
            .await?;
        Ok(self.store.store_ref_raw(key, point, self.extra.clone()))
    }

    pub async fn init<T: Object<Extra>, K: Send + Sync + AsRef<str>>(
        &self,
        key: K,
        point: Point<T>,
    ) -> object_rainbow::Result<StoreRef<S, K, T, Extra>> {
        let point = self.store.saved_point(&point, self.extra.clone()).await?;
        self.store
            .update_ref(key.as_ref(), Some(OptionalHash::NONE), point.hash())
            .await?;
        Ok(self.store.store_ref_raw(key, point, self.extra.clone()))
    }

    pub async fn load<T: Object<Extra>, K: Send + Sync + AsRef<str>>(
        &self,
        key: K,
    ) -> object_rainbow::Result<StoreRef<S, K, T, Extra>> {
        let hash = self
            .store
            .fetch_ref(key.as_ref())
            .await?
            .get()
            .ok_or(object_rainbow::Error::HashNotFound)?;
        let point = self.store.point_extra(hash, self.extra.clone());
        Ok(self.store.store_ref_raw(key, point, self.extra.clone()))
    }

    pub async fn load_or_init<T: Object<Extra> + Default + Clone, K: Send + Sync + AsRef<str>>(
        &self,
        key: K,
    ) -> object_rainbow::Result<StoreRef<S, K, T, Extra>> {
        if let Some(hash) = self.store.fetch_ref(key.as_ref()).await?.get() {
            let point = self.store.point_extra(hash, self.extra.clone());
            Ok(self.store.store_ref_raw(key, point, self.extra.clone()))
        } else {
            self.init(key, Default::default()).await
        }
    }

    pub async fn reference<T: Object<Extra>, K: Send + Sync + AsRef<str>>(
        &self,
        key: K,
        point: Point<T>,
    ) -> object_rainbow::Result<StoreRef<S, K, T, Extra>> {
        Ok(StoreRef {
            old: self.store.fetch_ref(key.as_ref()).await?,
            ..self.store.store_ref_raw(key, point, self.extra.clone())
        })
    }
}

pub struct StoreRef<S, K, T, Extra> {
    store: S,
    key: K,
    old: OptionalHash,
    point: Point<T>,
    extra: Extra,
}

impl<S, K, T, Extra> Deref for StoreRef<S, K, T, Extra> {
    type Target = Point<T>;

    fn deref(&self) -> &Self::Target {
        &self.point
    }
}

impl<S, K, T, Extra> DerefMut for StoreRef<S, K, T, Extra> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.point
    }
}

impl<
    S: RainbowStoreMut,
    K: Send + Sync + AsRef<str>,
    T: Object<Extra>,
    Extra: 'static + Send + Sync + Clone,
> StoreRef<S, K, T, Extra>
{
    pub fn is_modified(&self) -> bool {
        self.point.hash() != self.old
    }

    pub fn is_new(&self) -> bool {
        self.old.is_none()
    }

    pub async fn save_point(&mut self) -> object_rainbow::Result<()> {
        self.point = self
            .store
            .saved_point(&self.point, self.extra.clone())
            .await?;
        Ok(())
    }

    pub async fn save(&mut self) -> object_rainbow::Result<()> {
        if self.is_modified() {
            self.save_point().await?;
            self.store
                .update_ref(self.key.as_ref(), Some(self.old), self.point.hash())
                .await?;
            self.old = self.point.hash().into();
        }
        Ok(())
    }
}

#[derive(Parse, ParseInline)]
struct StoredInner<S, E> {
    hash: Hash,
    extra: Extras<E>,
    store: S,
}

#[derive(
    ToOutput, InlineOutput, Tagged, Size, MaybeHasNiche, Clone, PartialEq, Eq, PartialOrd, Ord, Hash,
)]
pub struct Stored<S, T> {
    point: Point<T>,
    store: S,
}

impl<S: ListHashes, T> ListHashes for Stored<S, T> {
    fn list_hashes(&self, f: &mut impl FnMut(Hash)) {
        self.store.list_hashes(f);
    }
}

impl<S: Topological, T> Topological for Stored<S, T> {
    fn traverse(&self, visitor: &mut impl PointVisitor) {
        self.store.traverse(visitor);
    }
}

impl<S: RainbowStore, T: 'static + FullHash> Stored<S, T> {
    fn from_inner<E: 'static + Send + Sync + Clone + ExtraFor<T>>(
        StoredInner { hash, extra, store }: StoredInner<S, E>,
    ) -> Self {
        let point = store.point_extra(hash, extra.0);
        Self { point, store }
    }
}

impl<
    S: RainbowStore + Parse<I>,
    T: 'static + FullHash + Parse<I>,
    I: PointInput<Extra: Send + Sync + ExtraFor<T>>,
> Parse<I> for Stored<S, T>
{
    fn parse(input: I) -> object_rainbow::Result<Self> {
        input.parse().map(Self::from_inner)
    }
}

impl<
    S: RainbowStore + ParseInline<I>,
    T: 'static + FullHash + Parse<I>,
    I: PointInput<Extra: Send + Sync + ExtraFor<T>>,
> ParseInline<I> for Stored<S, T>
{
    fn parse_inline(input: &mut I) -> object_rainbow::Result<Self> {
        input.parse_inline().map(Self::from_inner)
    }
}

assert_impl!(
    impl<S, T, E> Object<E> for Stored<S, T>
    where
        S: RainbowStore + Object<E>,
        T: Object<E>,
        E: 'static + Send + Sync + Clone,
    {
    }
);

assert_impl!(
    impl<S, T, E> Inline<E> for Stored<S, T>
    where
        S: RainbowStore + Inline<E>,
        T: Object<E>,
        E: 'static + Send + Sync + Clone,
    {
    }
);

impl<S, T> Stored<S, T> {
    pub fn load(&self) -> &Point<T> {
        &self.point
    }
}

impl<S: RainbowStore, T: Traversible> Stored<S, T> {
    pub async fn replace(&mut self, point: Point<T>) -> object_rainbow::Result<Point<T>> {
        self.store.save_point(&point).await?;
        Ok(std::mem::replace(&mut self.point, point))
    }

    pub async fn new(store: S, point: Point<T>) -> object_rainbow::Result<Self> {
        store.save_point(&point).await?;
        Ok(Self { point, store })
    }
}