tauri_store/
collection.rs

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
27/// Closure to be called when a store is loaded.
28pub type OnLoadFn<R> = dyn Fn(&Store<R>) -> Result<()> + Send + Sync;
29
30/// A collection of stores.
31/// This is the core component for store plugins.
32pub 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  /// Builds a new store collection.
50  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  /// Gets the resource id for a store.
75  fn rid(&self, store_id: &StoreId) -> Option<ResourceId> {
76    self.stores.get(store_id).map(|it| *it.value())
77  }
78
79  /// Gets the resource ids for all the stores.
80  fn rids(&self) -> Vec<ResourceId> {
81    self.stores.iter().map(|it| *it.value()).collect()
82  }
83
84  /// Lists all the store ids.
85  pub fn ids(&self) -> Vec<StoreId> {
86    self
87      .stores
88      .iter()
89      .map(|it| it.key().clone())
90      .collect()
91  }
92
93  /// Calls a closure with a mutable reference to the store with the given id.
94  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  /// Gets a clone of the store state.
102  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  /// Gets the store state, then tries to parse it as an instance of type `T`.
109  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  /// Gets a value from a store.
119  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  /// Gets a value from a store and tries to parse it as an instance of type `T`.
127  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  /// Gets a value from a store and tries to parse it as an instance of type `T`.
137  ///
138  /// If the key does not exist, returns the provided default value.
139  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  /// Gets a value from a store and tries to parse it as an instance of type `T`.
147  ///
148  /// If the key does not exist, returns the default value of `T`.
149  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  /// Gets a value from a store and tries to parse it as an instance of type `T`.
157  ///
158  /// If the key does not exist, returns the result of the provided closure.
159  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  /// Sets a key-value pair in a store.
174  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  /// Patches a store state.
185  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  /// Saves a store to the disk.
195  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  /// Saves a store to the disk immediately, ignoring the save strategy.
202  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  /// Saves some stores to the disk.
210  pub fn save_some(&self, ids: &[impl AsRef<str>]) -> Result<()> {
211    ids.iter().try_for_each(|id| self.save(id))
212  }
213
214  /// Saves some stores to the disk immediately, ignoring the save strategy.
215  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  /// Saves all the stores to the disk.
220  pub fn save_all(&self) -> Result<()> {
221    // I suppose going through the rids is better than through the store ids.
222    // This way, we don't need to hold references into the dashmap nor clone its keys.
223    // The downside (?) is that we need to use the StoreResource directly.
224    self
225      .rids()
226      .into_iter()
227      .try_for_each(|rid| StoreResource::save(&self.app, rid))
228  }
229
230  /// Saves all the stores to the disk immediately, ignoring the save strategy.
231  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  /// Default save strategy for the stores.
239  /// This can be overridden on a per-store basis.
240  #[inline]
241  pub fn default_save_strategy(&self) -> SaveStrategy {
242    self.default_save_strategy
243  }
244
245  /// Saves the stores periodically.
246  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  /// Stops the autosave.
254  pub fn clear_autosave(&self) {
255    if let Ok(mut autosave) = self.autosave.lock() {
256      autosave.stop();
257    }
258  }
259
260  /// Watches a store for changes.
261  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  /// Removes a watcher from a store.
271  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  /// Removes the store from the collection.
282  #[doc(hidden)]
283  pub fn unload_store(&self, id: &StoreId) -> Result<()> {
284    if let Some((_, rid)) = self.stores.remove(id) {
285      // The store needs to be saved immediately here.
286      // Otherwise, the plugin might try to load it again if `StoreCollection::get_resource` is called.
287      // This scenario will happen whenever the save strategy is not `Immediate`.
288      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  /// Runs any necessary tasks before the application exits.
298  #[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}