lock concurrent fetch_or_creates to prevent inconsistencies

feat/vaults
Tomáš Mládek 2021-12-05 22:36:16 +01:00
parent dacfc57d11
commit cb832b6789
1 changed files with 13 additions and 4 deletions

View File

@ -145,6 +145,10 @@ pub async fn list_node<C: Connection<Backend = Sqlite>>(
.collect::<Vec<Entry>>())
}
lazy_static! {
static ref FETCH_CREATE_LOCK: Mutex<()> = Mutex::new(());
}
pub fn fetch_or_create_dir<C: Connection<Backend = Sqlite>>(
connection: &C,
parent: Option<Address>,
@ -156,6 +160,11 @@ pub fn fetch_or_create_dir<C: Connection<Backend = Sqlite>>(
None => trace!("FETCHING/CREATING /{:#}", directory),
}
let _lock;
if create {
_lock = FETCH_CREATE_LOCK.lock().unwrap();
}
let matching_directories = query(
connection,
Query::SingleQuery(QueryPart::Matches(EntryQuery {
@ -220,8 +229,9 @@ pub fn fetch_or_create_dir<C: Connection<Backend = Sqlite>>(
}
1 => Ok(valid_directories[0].clone()),
_ => Err(anyhow!(format!(
"Invalid database state - more than one directory matches the query {:?}/{:#}!", parent, directory)
)),
"Invalid database state - more than one directory matches the query {:?}/{:#}!",
parent, directory
))),
}
}
@ -269,8 +279,7 @@ pub fn resolve_path_cached<C: Connection<Backend = Sqlite>>(
result.push(address.clone());
} else {
drop(cache_lock);
let address =
fetch_or_create_dir(connection, parent, node, create)?;
let address = fetch_or_create_dir(connection, parent, node, create)?;
result.push(address.clone());
cache.lock().unwrap().put(key, address);
}