@@ -39,15 +39,14 @@ impl ConnectionManager {
3939 return None ;
4040 }
4141
42- // Try read lock first for cache hit
43- if let Ok ( pools) = self . pools . read ( ) {
44- if let Some ( cached_pool) = pools. get ( & key) {
45- // Can't update last_accessed with read lock, but that's okay for occasional misses
46- return Some ( cached_pool . pool . clone ( ) ) ;
42+ {
43+ if let Ok ( pools) = self . pools . read ( ) {
44+ if let Some ( cached_pool) = pools. get ( & key) {
45+ return Some ( cached_pool . pool . clone ( ) ) ;
46+ }
4747 }
4848 }
4949
50- // Cache miss or need to update timestamp - use write lock
5150 let mut pools = self . pools . write ( ) . unwrap ( ) ;
5251
5352 // Double-check after acquiring write lock
@@ -57,7 +56,19 @@ impl ConnectionManager {
5756 }
5857
5958 // Clean up idle connections before creating new ones to avoid unbounded growth
60- self . cleanup_idle_pools_with_lock ( & mut pools, & key) ;
59+ let now = Instant :: now ( ) ;
60+ pools. retain ( |k, cached_pool| {
61+ let idle_duration = now. duration_since ( cached_pool. last_accessed ) ;
62+ if idle_duration > cached_pool. idle_timeout && k != & key {
63+ tracing:: debug!(
64+ "Removing idle database connection (idle for {:?})" ,
65+ idle_duration
66+ ) ;
67+ false
68+ } else {
69+ true
70+ }
71+ } ) ;
6172
6273 // Create a new pool
6374 let config = PgConnectOptions :: new ( )
@@ -85,28 +96,4 @@ impl ConnectionManager {
8596
8697 Some ( pool)
8798 }
88-
89- /// Remove pools that haven't been accessed for longer than the idle timeout
90- /// This version works with an existing write lock to avoid deadlocks
91- fn cleanup_idle_pools_with_lock (
92- & self ,
93- pools : & mut HashMap < ConnectionKey , CachedPool > ,
94- ignore_key : & ConnectionKey ,
95- ) {
96- let now = Instant :: now ( ) ;
97-
98- // Use retain to keep only non-idle connections
99- pools. retain ( |key, cached_pool| {
100- let idle_duration = now. duration_since ( cached_pool. last_accessed ) ;
101- if idle_duration > cached_pool. idle_timeout && key != ignore_key {
102- tracing:: debug!(
103- "Removing idle database connection (idle for {:?})" ,
104- idle_duration
105- ) ;
106- false
107- } else {
108- true
109- }
110- } ) ;
111- }
11299}
0 commit comments