ouisync/repository/
params.rs

1use super::monitor::RepositoryMonitor;
2use crate::{db, device_id::DeviceId, error::Result};
3use metrics::{NoopRecorder, Recorder};
4use state_monitor::{metrics::MetricsRecorder, StateMonitor};
5use std::path::{Path, PathBuf};
6
7pub struct RepositoryParams<R> {
8    store: Store,
9    device_id: DeviceId,
10    monitor: Option<StateMonitor>,
11    recorder: Option<R>,
12}
13
14impl<R> RepositoryParams<R> {
15    pub fn with_device_id(self, device_id: DeviceId) -> Self {
16        Self { device_id, ..self }
17    }
18
19    pub fn with_monitor(self, monitor: StateMonitor) -> Self {
20        Self {
21            monitor: Some(monitor),
22            ..self
23        }
24    }
25
26    pub fn with_recorder<S>(self, recorder: S) -> RepositoryParams<S> {
27        RepositoryParams {
28            store: self.store,
29            device_id: self.device_id,
30            monitor: self.monitor,
31            recorder: Some(recorder),
32        }
33    }
34
35    pub(super) async fn create(&self) -> Result<db::Pool, db::Error> {
36        match &self.store {
37            Store::Path(path) => db::create(path).await,
38            #[cfg(test)]
39            Store::Pool(pool) => Ok(pool.clone()),
40        }
41    }
42
43    pub(super) async fn open(&self) -> Result<db::Pool, db::Error> {
44        match &self.store {
45            Store::Path(path) => db::open(path).await,
46            #[cfg(test)]
47            Store::Pool(pool) => Ok(pool.clone()),
48        }
49    }
50
51    pub(super) fn device_id(&self) -> DeviceId {
52        self.device_id
53    }
54}
55
56impl<R> RepositoryParams<R>
57where
58    R: Recorder,
59{
60    pub(super) fn monitor(&self) -> RepositoryMonitor {
61        let monitor = if let Some(monitor) = &self.monitor {
62            monitor.clone()
63        } else {
64            StateMonitor::make_root()
65        };
66
67        if let Some(recorder) = &self.recorder {
68            RepositoryMonitor::new(monitor, recorder)
69        } else {
70            RepositoryMonitor::new(monitor.clone(), &MetricsRecorder::new(monitor))
71        }
72    }
73}
74
75impl RepositoryParams<NoopRecorder> {
76    pub fn new(path: impl AsRef<Path>) -> Self {
77        Self::with_store(Store::Path(path.as_ref().to_path_buf()))
78    }
79
80    #[cfg(test)]
81    pub(crate) fn with_pool(pool: db::Pool) -> Self {
82        Self::with_store(Store::Pool(pool))
83    }
84
85    fn with_store(store: Store) -> Self {
86        Self {
87            store,
88            device_id: rand::random(),
89            monitor: None,
90            recorder: None,
91        }
92    }
93}
94
95enum Store {
96    Path(PathBuf),
97    #[cfg(test)]
98    Pool(db::Pool),
99}