elemental_shared/
loader.rs1use std::{marker::PhantomData, sync::Arc};
2
3use crate::{
4 error::{Error, Result},
5 migrator::Migrator,
6 profile::Profile,
7 version::{Persistor, VersionControlled, Versioned},
8};
9use tokio::sync::RwLock;
10
11#[derive(Clone)]
12pub struct Loader<M, S, V, P>
13where
14 M: Migrator<S, V>,
15 S: Versioned,
16 V: VersionControlled,
17 P: Persistor<S>,
18{
19 pub inner: Arc<RwLock<V>>,
20 pub migrator: M,
21 pub persistor: P,
22 pub target_version: usize,
23 _source: PhantomData<S>,
24}
25
26impl<M, S, V, P> Loader<M, S, V, P>
27where
28 M: Migrator<S, V>,
29 S: Versioned,
30 V: VersionControlled + Default,
31 P: Persistor<S>,
32{
33 pub async fn load(migrator: M, persistor: P, target_version: usize) -> Result<Self> {
34 let value = match persistor.load().await? {
35 Some(source) => {
36 if source.version() > target_version {
37 return Err(Error::StoredVersionNewer {
38 stored: source.version(),
39 supported: target_version,
40 });
41 }
42
43 let should_save = source.version() < target_version;
44 let value = migrator.migrate(source)?.with_version(target_version);
45
46 if should_save {
47 let stored = encode_for_storage(&migrator, &value, target_version)?;
48 persistor.save(&stored).await?;
49 }
50
51 value
52 }
53 None => V::default().with_version(target_version),
54 };
55
56 Ok(Self {
57 inner: Arc::new(RwLock::new(value)),
58 migrator,
59 persistor,
60 target_version,
61 _source: PhantomData,
62 })
63 }
64
65 pub async fn cloned(&self) -> V
66 where
67 V: Clone,
68 {
69 let guard = self.inner.read().await;
70 guard.clone()
71 }
72
73 pub async fn get<T>(&self, f: impl FnOnce(&V) -> T) -> T {
74 let guard = self.inner.read().await;
75 f(&*guard)
76 }
77
78 pub async fn set(&self, f: impl FnOnce(&mut V)) -> Result<()> {
79 let mut guard = self.inner.write().await;
80 f(&mut *guard);
81 let stored = encode_for_storage(&self.migrator, &*guard, self.target_version)?;
82 self.persistor.save(&stored).await?;
83 Ok(())
84 }
85}
86
87fn encode_for_storage<M, S, V>(migrator: &M, value: &V, target_version: usize) -> Result<S>
88where
89 M: Migrator<S, V>,
90 S: Versioned,
91 V: VersionControlled,
92{
93 let stored = migrator.encode(value)?;
94 let stored_version = stored.version();
95
96 if stored_version != target_version {
97 return Err(Error::EncodedVersionMismatch {
98 encoded: stored_version,
99 target: target_version,
100 });
101 }
102
103 Ok(stored)
104}
105
106pub type ProfileLoader<M, S, C, P> = Loader<M, S, Profile<C>, P>;