From a7af6612f2983f48a86709bd0cd0d82716947fd8 Mon Sep 17 00:00:00 2001 From: Lucas Nogueira Date: Tue, 15 Oct 2024 10:28:58 -0300 Subject: [PATCH] keep store lock throughout whole new_or_existing_inner --- plugins/store/src/lib.rs | 4 ++-- plugins/store/src/store.rs | 27 ++++++++++++++------------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/plugins/store/src/lib.rs b/plugins/store/src/lib.rs index ae71b3c9..e44e2d3e 100644 --- a/plugins/store/src/lib.rs +++ b/plugins/store/src/lib.rs @@ -42,7 +42,7 @@ struct ChangePayload<'a> { #[derive(Debug)] pub struct StoreState { - stores: Mutex>, + stores: Arc>>, serialize_fns: HashMap, deserialize_fns: HashMap, default_serialize: SerializeFn, @@ -477,7 +477,7 @@ impl Builder { ]) .setup(move |app_handle, _api| { app_handle.manage(StoreState { - stores: Mutex::new(HashMap::new()), + stores: Arc::new(Mutex::new(HashMap::new())), serialize_fns: self.serialize_fns, deserialize_fns: self.deserialize_fns, default_serialize: self.default_serialize, diff --git a/plugins/store/src/store.rs b/plugins/store/src/store.rs index 42240cec..409a13e4 100644 --- a/plugins/store/src/store.rs +++ b/plugins/store/src/store.rs @@ -8,7 +8,7 @@ use std::{ collections::HashMap, fs, path::{Path, PathBuf}, - sync::{Arc, Mutex}, + sync::{Arc, Mutex, MutexGuard}, time::Duration, }; use tauri::{path::BaseDirectory, AppHandle, Emitter, Manager, Resource, ResourceId, Runtime}; @@ -170,10 +170,11 @@ impl StoreBuilder { self } - pub(crate) fn build_inner(mut self, load: bool) -> crate::Result<(Arc>, ResourceId)> { - let state = self.app.state::(); - let mut stores = state.stores.lock().unwrap(); - + pub(crate) fn build_inner( + mut self, + load: bool, + mut stores: MutexGuard<'_, HashMap>, + ) -> crate::Result<(Arc>, ResourceId)> { if stores.contains_key(&self.path) { return Err(crate::Error::AlreadyExists(self.path)); } @@ -227,7 +228,8 @@ impl StoreBuilder { } pub(crate) fn create_inner(self) -> crate::Result<(Arc>, ResourceId)> { - self.build_inner(false) + let stores = self.app.state::().stores.clone(); + self.build_inner(false, stores.lock().unwrap()) } /// Get the existing store with the same path or creates a new [`Store`]. @@ -251,14 +253,13 @@ impl StoreBuilder { } pub(crate) fn new_or_existing_inner(self) -> crate::Result<(Arc>, ResourceId)> { - { - let state = self.app.state::(); - let stores = state.stores.lock().unwrap(); - if let Some(rid) = stores.get(&self.path) { - return Ok((self.app.resources_table().get(*rid).unwrap(), *rid)); - } + let stores = self.app.state::().stores.clone(); + let stores_ = stores.lock().unwrap(); + if let Some(rid) = stores_.get(&self.path) { + return Ok((self.app.resources_table().get(*rid).unwrap(), *rid)); } - self.build_inner(true) + + self.build_inner(true, stores_) } }