1mod autosave;
2mod builder;
3mod path;
4
5use crate::error::Result;
6use crate::event::{emit, STORE_UNLOAD_EVENT};
7use crate::meta::Meta;
8use crate::store::{SaveStrategy, Store, StoreId, StoreResource, StoreState, WatcherId};
9use autosave::Autosave;
10use dashmap::DashMap;
11use serde::de::DeserializeOwned;
12use serde_json::Value as Json;
13use std::collections::HashSet;
14use std::fmt;
15use std::path::PathBuf;
16use std::sync::{Arc, Mutex, OnceLock};
17use std::time::Duration;
18use tauri::{AppHandle, Resource, ResourceId, Runtime};
19
20pub use builder::StoreCollectionBuilder;
21
22#[cfg(feature = "unstable-migration")]
23use crate::migration::Migrator;
24
25pub(crate) static RESOURCE_ID: OnceLock<ResourceId> = OnceLock::new();
26
27pub type OnLoadFn<R> = dyn Fn(&Store<R>) -> Result<()> + Send + Sync;
29
30pub struct StoreCollection<R: Runtime> {
33 pub(crate) app: AppHandle<R>,
34 pub(crate) name: Box<str>,
35 pub(crate) path: Mutex<PathBuf>,
36 pub(crate) stores: DashMap<StoreId, ResourceId>,
37 pub(crate) on_load: Option<Box<OnLoadFn<R>>>,
38 pub(crate) autosave: Mutex<Autosave>,
39 pub(crate) default_save_strategy: SaveStrategy,
40 pub(crate) save_denylist: Option<HashSet<StoreId>>,
41 pub(crate) sync_denylist: Option<HashSet<StoreId>>,
42 pub(crate) pretty: bool,
43
44 #[cfg(feature = "unstable-migration")]
45 pub(crate) migrator: Mutex<Migrator>,
46}
47
48impl<R: Runtime> StoreCollection<R> {
49 pub fn builder() -> StoreCollectionBuilder<R> {
51 StoreCollectionBuilder::new()
52 }
53
54 pub(crate) fn get_resource(&self, id: impl AsRef<str>) -> Result<Arc<StoreResource<R>>> {
55 let id = StoreId::from(id.as_ref());
56 let rid = match self.rid(&id) {
57 Some(rid) => rid,
58 None => self.load_store(id)?,
59 };
60
61 StoreResource::get(&self.app, rid)
62 }
63
64 fn load_store(&self, id: StoreId) -> Result<ResourceId> {
65 let (rid, resource) = Store::load(&self.app, &id)?;
66 if let Some(on_load) = &self.on_load {
67 resource.locked(|store| on_load(store))?;
68 }
69
70 self.stores.insert(id, rid);
71 Ok(rid)
72 }
73
74 fn rid(&self, store_id: &StoreId) -> Option<ResourceId> {
76 self.stores.get(store_id).map(|it| *it.value())
77 }
78
79 fn rids(&self) -> Vec<ResourceId> {
81 self.stores.iter().map(|it| *it.value()).collect()
82 }
83
84 pub fn ids(&self) -> Vec<StoreId> {
86 self
87 .stores
88 .iter()
89 .map(|it| it.key().clone())
90 .collect()
91 }
92
93 pub fn with_store<F, T>(&self, store_id: impl AsRef<str>, f: F) -> Result<T>
95 where
96 F: FnOnce(&mut Store<R>) -> T,
97 {
98 Ok(self.get_resource(store_id)?.locked(f))
99 }
100
101 pub fn state(&self, store_id: impl AsRef<str>) -> Result<StoreState> {
103 self
104 .get_resource(store_id)?
105 .locked(|store| Ok(store.state().clone()))
106 }
107
108 pub fn try_state<T>(&self, store_id: impl AsRef<str>) -> Result<T>
110 where
111 T: DeserializeOwned,
112 {
113 self
114 .get_resource(store_id)?
115 .locked(|store| store.try_state())
116 }
117
118 pub fn get(&self, store_id: impl AsRef<str>, key: impl AsRef<str>) -> Option<Json> {
120 self
121 .get_resource(store_id)
122 .ok()?
123 .locked(|store| store.get(key).cloned())
124 }
125
126 pub fn try_get<T>(&self, store_id: impl AsRef<str>, key: impl AsRef<str>) -> Result<T>
128 where
129 T: DeserializeOwned,
130 {
131 self
132 .get_resource(store_id)?
133 .locked(|store| store.try_get(key))
134 }
135
136 pub fn try_get_or<T>(&self, store_id: impl AsRef<str>, key: impl AsRef<str>, default: T) -> T
140 where
141 T: DeserializeOwned,
142 {
143 self.try_get(store_id, key).unwrap_or(default)
144 }
145
146 pub fn try_get_or_default<T>(&self, store_id: impl AsRef<str>, key: impl AsRef<str>) -> T
150 where
151 T: Default + DeserializeOwned,
152 {
153 self.try_get(store_id, key).unwrap_or_default()
154 }
155
156 pub fn try_get_or_else<T>(
160 &self,
161 store_id: impl AsRef<str>,
162 key: impl AsRef<str>,
163 f: impl FnOnce() -> T,
164 ) -> T
165 where
166 T: DeserializeOwned,
167 {
168 self
169 .try_get(store_id, key)
170 .unwrap_or_else(|_| f())
171 }
172
173 pub fn set<K, V>(&self, store_id: impl AsRef<str>, key: K, value: V) -> Result<()>
175 where
176 K: AsRef<str>,
177 V: Into<Json>,
178 {
179 self
180 .get_resource(store_id)?
181 .locked(|store| store.set(key, value))
182 }
183
184 pub fn patch<S>(&self, store_id: impl AsRef<str>, state: S) -> Result<()>
186 where
187 S: Into<StoreState>,
188 {
189 self
190 .get_resource(store_id)?
191 .locked(|store| store.patch(state))
192 }
193
194 pub fn save(&self, store_id: impl AsRef<str>) -> Result<()> {
196 self
197 .get_resource(store_id)?
198 .locked(|store| store.save())
199 }
200
201 pub fn save_now(&self, store_id: impl AsRef<str>) -> Result<()> {
203 self.get_resource(store_id)?.locked(|store| {
204 store.abort_pending_save();
205 store.save_now()
206 })
207 }
208
209 pub fn save_some(&self, ids: &[impl AsRef<str>]) -> Result<()> {
211 ids.iter().try_for_each(|id| self.save(id))
212 }
213
214 pub fn save_some_now(&self, ids: &[impl AsRef<str>]) -> Result<()> {
216 ids.iter().try_for_each(|id| self.save_now(id))
217 }
218
219 pub fn save_all(&self) -> Result<()> {
221 self
225 .rids()
226 .into_iter()
227 .try_for_each(|rid| StoreResource::save(&self.app, rid))
228 }
229
230 pub fn save_all_now(&self) -> Result<()> {
232 self
233 .rids()
234 .into_iter()
235 .try_for_each(|rid| StoreResource::save_now(&self.app, rid))
236 }
237
238 #[inline]
241 pub fn default_save_strategy(&self) -> SaveStrategy {
242 self.default_save_strategy
243 }
244
245 pub fn set_autosave(&self, duration: Duration) {
247 if let Ok(mut autosave) = self.autosave.lock() {
248 autosave.set_duration(duration);
249 autosave.start(&self.app);
250 }
251 }
252
253 pub fn clear_autosave(&self) {
255 if let Ok(mut autosave) = self.autosave.lock() {
256 autosave.stop();
257 }
258 }
259
260 pub fn watch<F>(&self, store_id: impl AsRef<str>, f: F) -> Result<WatcherId>
262 where
263 F: Fn(AppHandle<R>) -> Result<()> + Send + Sync + 'static,
264 {
265 self
266 .get_resource(store_id)?
267 .locked(|store| Ok(store.watch(f)))
268 }
269
270 pub fn unwatch(
272 &self,
273 store_id: impl AsRef<str>,
274 watcher_id: impl Into<WatcherId>,
275 ) -> Result<bool> {
276 self
277 .get_resource(store_id)?
278 .locked(|store| Ok(store.unwatch(watcher_id)))
279 }
280
281 #[doc(hidden)]
283 pub fn unload_store(&self, id: &StoreId) -> Result<()> {
284 if let Some((_, rid)) = self.stores.remove(id) {
285 let resource = StoreResource::take(&self.app, rid)?;
289 resource.locked(|store| store.save_now())?;
290
291 emit(&self.app, STORE_UNLOAD_EVENT, id, None::<&str>)?;
292 }
293
294 Ok(())
295 }
296
297 #[doc(hidden)]
299 pub fn on_exit(&self) -> Result<()> {
300 self.clear_autosave();
301
302 for rid in self.rids() {
303 if let Ok(resource) = StoreResource::take(&self.app, rid) {
304 resource.locked(|store| {
305 store.abort_pending_save();
306 if store.save_on_exit {
307 let _ = store.save_now();
308 }
309 });
310 }
311 }
312
313 Meta::write(self)?;
314
315 Ok(())
316 }
317}
318
319impl<R: Runtime> Resource for StoreCollection<R> {}
320
321impl<R: Runtime> fmt::Debug for StoreCollection<R> {
322 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
323 f.debug_struct("StoreCollection")
324 .field("default_save_strategy", &self.default_save_strategy)
325 .field("pretty", &self.pretty)
326 .finish_non_exhaustive()
327 }
328}