Skip to content

Commit 2e72314

Browse files
committed
fix: fix theoretical race condition
1 parent 4a31185 commit 2e72314

1 file changed

Lines changed: 14 additions & 8 deletions

File tree

src/commands.rs

Lines changed: 14 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -58,15 +58,21 @@ pub async fn load<R: Runtime>(
5858

5959
let mut instances = db_instances.0.write().await;
6060

61-
// Double-check in case another thread loaded it while we waited for write lock
62-
if instances.contains_key(&db) {
63-
return Ok(db);
61+
// Use entry API to atomically check and insert, avoiding race conditions
62+
// where two callers could both create wrappers
63+
use std::collections::hash_map::Entry;
64+
match instances.entry(db.clone()) {
65+
Entry::Occupied(_) => {
66+
// Another caller won the race and inserted while we waited for write lock
67+
Ok(db)
68+
}
69+
Entry::Vacant(entry) => {
70+
// We won the race, create and insert the wrapper
71+
let wrapper = DatabaseWrapper::connect(&db, &app, custom_config).await?;
72+
entry.insert(wrapper);
73+
Ok(db)
74+
}
6475
}
65-
66-
let wrapper = DatabaseWrapper::connect(&db, &app, custom_config).await?;
67-
instances.insert(db.clone(), wrapper);
68-
69-
Ok(db)
7076
}
7177

7278
/// Wait for migrations to complete for a database, if any are registered.

0 commit comments

Comments
 (0)