object_rainbow_history_store/
lib.rs1use std::{marker::PhantomData, sync::Arc};
2
3use object_rainbow::{Fetch, Inline, Object};
4use object_rainbow_history::{Apply, History};
5use object_rainbow_store::{RainbowStoreMut, StoreMut};
6
7pub struct HistoryStore<T, D, S, Extra = ()> {
8 key: Arc<str>,
9 store: StoreMut<S, Extra>,
10 _marker: PhantomData<(T, D)>,
11}
12
13impl<T, D, S> HistoryStore<T, D, S> {
14 pub fn new(key: &str, store: S) -> Self {
15 Self::new_extra(key, store, ())
16 }
17}
18
19impl<T, D, S, Extra> HistoryStore<T, D, S, Extra> {
20 pub fn new_extra(key: &str, store: S, extra: Extra) -> Self {
21 Self {
22 key: key.into(),
23 store: StoreMut::new_extra(store, extra),
24 _marker: PhantomData,
25 }
26 }
27}
28
29impl<T, D, S: Clone, Extra: Clone> Clone for HistoryStore<T, D, S, Extra> {
30 fn clone(&self) -> Self {
31 Self {
32 key: self.key.clone(),
33 store: self.store.clone(),
34 _marker: PhantomData,
35 }
36 }
37}
38
39impl<
40 T: Inline<Extra> + Clone + Default + Apply<D>,
41 D: Object<Extra> + Clone,
42 S: RainbowStoreMut,
43 Extra: 'static + Send + Sync + Clone,
44> HistoryStore<T, D, S, Extra>
45{
46 pub async fn commit(&self, diff: D) -> object_rainbow::Result<()> {
47 let mut history = self
48 .store
49 .load_or_init::<History<T, D>, _>(self.key.as_ref())
50 .await?;
51 history.fetch_mut().await?.commit(diff).await?;
52 history.save().await?;
53 Ok(())
54 }
55
56 pub async fn load(&self) -> object_rainbow::Result<T> {
57 self.history().await?.tree().await
58 }
59
60 pub async fn history(&self) -> object_rainbow::Result<History<T, D>> {
61 self.store
62 .load_or_init(self.key.as_ref())
63 .await?
64 .fetch()
65 .await
66 }
67
68 pub async fn forward(&self, other: History<T, D>) -> object_rainbow::Result<()> {
69 let mut history = self
70 .store
71 .load_or_init::<History<T, D>, _>(self.key.as_ref())
72 .await?;
73 history.fetch_mut().await?.forward(other).await?;
74 history.save().await?;
75 Ok(())
76 }
77}